Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(chronicle): #5329 cap events per page extraction at chronicle.max_events_per_page

garrytan8f201bc94ebd
diff --git a/docs/architecture/key-files/core-services-1.md b/docs/architecture/key-files/core-services-1.md
index cf36f48aa9..2d797d0207 100644
--- a/docs/architecture/key-files/core-services-1.md
+++ b/docs/architecture/key-files/core-services-1.md
@@ -31,7 +31,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,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/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`/`max_events_per_page` (#5329, default 25) 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), then keeps at most `chronicle.max_events_per_page` of the survivors in the judge's order (#5329, the rest `over_cap`, no model call to count); 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`, `chronicle-max-events-5329`; 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; `GRAMMAR_REVISIONS` (per-language chunker revisions: `lua: 1` after the tree-sitter-grammars v0.3.0 swap that ended the `gbrain serve` Lua-fence hang; `typescript`/`tsx`/`javascript`/`python`/`ruby: 1` for the #5001 `__module__` chunks) folds into that language's hash only, and `chunkerStamp()` (`8;lua=1;typescript=1;…`) is the `sources.chunker_version` gate value every sync path reads and writes, so a per-language change walks each source once and re-imports only that language's files while the cost gate (`grammarOnlyDrift`, `grammar_drift`) prices those files alone. Top-level statements that contain a call (`describe(...)`, `app.use(...)`, `print(f())`, Ruby `RSpec.describe ... do`) are chunked through `code-module-chunks.ts` (below) so their call edges have a chunk to hang on. Grammar provenance and the vendoring scripts: `src/assets/wasm/README.md`; pinned by `test/chunkers/code-lua.test.ts`. `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/life-chronicle.md b/docs/guides/life-chronicle.md
index c4371dd779..2cf7f63f03 100644
--- a/docs/guides/life-chronicle.md
+++ b/docs/guides/life-chronicle.md
@@ -62,10 +62,14 @@ Two rules are enforced after the model answers, before anything is written:
- **No invented days.** Events are stored by day. A past event the text dates
only by year or month ("back in 2024", "last month") is dropped as
`date_imprecise` rather than pinned to January 1 or the first of the month.
+- **At most `chronicle.max_events_per_page` events per page** (default 25).
+ The cap runs after the two date rules, so a proposal dropped for its date
+ never takes a slot; the first dated proposals in the extraction's order are
+ kept and the rest are dropped as `over_cap`. Counting costs no model call.
The phase result reports dropped proposals by reason in `events_dropped`. When
every proposed event of a page is dropped, its ledger row records that reason
-instead of `no_events`.
+instead of `no_events` (never `over_cap`: the cap always keeps at least one).
## Calendar invites
@@ -116,6 +120,7 @@ correcting one event moves only that event.
| `chronicle.auto_recent_days` | `30` | How old a page's own date may be for automatic extraction. |
| `chronicle.auto_settle_seconds` | `180` | How long a page must stay unchanged before extraction. |
| `chronicle.judge_max_tokens` | `4000` | Output-token cap for one extraction call. |
+| `chronicle.max_events_per_page` | `25` | Events published from one page extraction; later proposals are dropped as `over_cap` (1 to 1000). |
`gbrain config set` refuses values outside each range and names the range. A
value already stored out of range falls back to its default, and doctor warns
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index f840885c50..322ed487c4 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -36,7 +36,7 @@ src/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0
src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refresh
src/commands/hook.ts 1926 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + import; +2 fix wave 11 integration: W1 router help guard import beside the W2 managed-root import
src/core/chunkers/code.ts 1598 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts); +10 Lua grammar swap: GRAMMAR_REVISIONS + chunkerStamp() (per-language re-chunk gate)
-src/core/config.ts 1932 ratchet +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept)
+src/core/config.ts 1933 ratchet +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts)
src/core/bootstrap/harness.ts 2610 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts)
src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option
src/core/ops/pages.ts 683 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept)
diff --git a/src/core/chronicle/config.ts b/src/core/chronicle/config.ts
index 959d6d342f..a1c312f7d9 100644
--- a/src/core/chronicle/config.ts
+++ b/src/core/chronicle/config.ts
@@ -67,6 +67,9 @@ export const CHRONICLE_NUMERIC_KEYS = {
meaning: 'seconds a page must stay unchanged before automatic extraction' },
'chronicle.judge_max_tokens': { fallback: 4000, min: 1, max: 128_000, integer: true,
meaning: 'output-token cap for one extraction call' },
+ // #5329 (e): the judge's array had no length bound; the surplus is counted `events_dropped.over_cap`, never written.
+ 'chronicle.max_events_per_page': { fallback: 25, min: 1, max: 1000, integer: true,
+ meaning: 'events published from one page extraction; later proposals are dropped as over_cap' },
} as const satisfies Record<string, NumericKeySpec>;
export type ChronicleNumericKey = keyof typeof CHRONICLE_NUMERIC_KEYS;
@@ -116,6 +119,8 @@ export interface ChronicleSettings {
recentDays: number;
settleSeconds: number;
judgeMaxTokens: number;
+ /** #5329: events published from one page extraction; the rest of the judge's proposals are counted `over_cap`. */
+ maxEventsPerPage: number;
/** When the automatic path activated on this brain (stamped by the first decision or phase run); null when unset or unreadable. */
activatedAt: Date | null;
/** Stored values outside the valid range; each fell back to its default. */
@@ -145,6 +150,7 @@ export async function chronicleSettings(engine: BrainEngine): Promise<ChronicleS
recentDays: values['chronicle.auto_recent_days'],
settleSeconds: values['chronicle.auto_settle_seconds'],
judgeMaxTokens: values['chronicle.judge_max_tokens'],
+ maxEventsPerPage: values['chronicle.max_events_per_page'],
activatedAt: activatedAt && !Number.isNaN(activatedAt.getTime()) ? activatedAt : null,
invalid,
};
diff --git a/src/core/chronicle/contract.ts b/src/core/chronicle/contract.ts
index f2a4ad0a12..948f7f073f 100644
--- a/src/core/chronicle/contract.ts
+++ b/src/core/chronicle/contract.ts
@@ -116,7 +116,7 @@ export interface ChronicleRunDetails {
reasons: Partial<Record<ChronicleReasonCode, number>>;
events_written: number;
events_retired: number;
- /** Proposed events refused before publication, by reason (`future_dated`, `date_imprecise`); never written. */
+ /** Proposed events refused before publication, by reason (`future_dated`, `date_imprecise`, `over_cap`); never written. */
events_dropped: ChronicleDropCounts;
/** Pending automatic rows left for the next run because the daily limit is used up. */
deferred_daily_limit: number;
diff --git a/src/core/chronicle/execute.ts b/src/core/chronicle/execute.ts
index 977b2bbfc3..db6d78e331 100644
--- a/src/core/chronicle/execute.ts
+++ b/src/core/chronicle/execute.ts
@@ -238,7 +238,7 @@ export async function executeChronicleRow(ctx: ChronicleExecContext, row: Chroni
const proposals = result?.events ?? [];
const { events, dropped } = buildChronicleEvents(proposals, judgeCtx,
- { slug: pin.slug, visibility: pin.visibility, contentHash: pin.contentHash }, { tz: ctx.tz, now });
+ { slug: pin.slug, visibility: pin.visibility, contentHash: pin.contentHash }, { tz: ctx.tz, now, maxEvents: settings.maxEventsPerPage });
let generation;
try {
generation = await publishChronicleGeneration(engine, {
diff --git a/src/core/chronicle/extract-events.ts b/src/core/chronicle/extract-events.ts
index ba6abb916b..fe8c1f0ade 100644
--- a/src/core/chronicle/extract-events.ts
+++ b/src/core/chronicle/extract-events.ts
@@ -14,6 +14,7 @@ import { matchingCloseBracket } from '../llm-json.ts';
import { maintenancePreflight } from '../persistence/prepared-maintenance.ts';
import { parseConversation } from '../conversation-parser/parse.ts';
import { chroniclePageDate } from './eligibility.ts';
+import { chronicleSettings } from './config.ts';
import { buildChronicleEvent, pinDepth, publishChronicleGeneration, type BuiltChronicleEvent } from './publish.ts';
export interface ChronicleEventProposal {
@@ -51,8 +52,9 @@ export type ChronicleJudge = (input: ChronicleJudgeInput) => Promise<ChronicleJu
* Proposals refused before publication, never written:
* - 'future_dated': dated after the depth page's own day (a plan, follow-up or scheduled item).
* - 'date_imprecise': the judge could not give the day ("back in 2024" → "2024").
+ * - 'over_cap' (#5329): past the page's `chronicle.max_events_per_page` after the date screen, in the judge's order.
*/
-export type ChronicleDropReason = 'future_dated' | 'date_imprecise';
+export type ChronicleDropReason = 'future_dated' | 'date_imprecise' | 'over_cap';
export type ChronicleDropCounts = Partial<Record<ChronicleDropReason, number>>;
export interface ChronicleExtractResult {
@@ -148,15 +150,20 @@ const DAY_PRECISION = /^\d{4}-\d{2}-\d{2}(?:$|[T ])/;
* CL-1/CL-2: refuse proposals the page cannot support before anything is written. A `when` without
* a day (YYYY, YYYY-MM) is `date_imprecise`: the timeline stores days, so pinning it to the first of
* the month or year would invent one. A day after the page's own day is `future_dated`.
+ * #5329: of the dated survivors, at most `maxEvents` are kept, the first in the judge's order (a
+ * deterministic cut: the judge lists a page's events as it reads them); the rest are `over_cap`.
+ * The cap runs after the screen, so a proposal dropped for its date never takes a slot. Counting
+ * costs no provider call.
*/
export function screenChronicleProposals(proposals: ChronicleEventProposal[], ctx: Pick<ChronicleJudgeContext, 'pageDates'>,
- tz: string, now: Date): { kept: ChronicleEventProposal[]; dropped: ChronicleDropCounts } {
+ tz: string, now: Date, cap: { maxEvents: number }): { kept: ChronicleEventProposal[]; dropped: ChronicleDropCounts } {
const cutoff = chronicleEventCutoff(ctx, tz, now);
const kept: ChronicleEventProposal[] = [];
const dropped: ChronicleDropCounts = {};
for (const ev of proposals) {
const reason: ChronicleDropReason | null = !DAY_PRECISION.test(ev.when.trim()) ? 'date_imprecise'
- : isoDay(ev.when.trim(), tz) > cutoff ? 'future_dated' : null;
+ : isoDay(ev.when.trim(), tz) > cutoff ? 'future_dated'
+ : kept.length >= cap.maxEvents ? 'over_cap' : null;
if (reason) dropped[reason] = (dropped[reason] ?? 0) + 1;
else kept.push(ev);
}
@@ -207,11 +214,11 @@ export function chronicleJudgeContext(page: { slug: string; type: string; title:
};
}
-/** Proposals → event pages for one depth snapshot; proposals the page cannot support are dropped first. */
+/** Proposals → event pages for one depth snapshot; proposals the page cannot support, then those past the cap, are dropped first. */
export function buildChronicleEvents(proposals: ChronicleEventProposal[], ctx: ChronicleJudgeContext,
- depth: { slug: string; visibility: 'private' | 'world'; contentHash: string }, opts: { tz: string; now: Date },
+ depth: { slug: string; visibility: 'private' | 'world'; contentHash: string }, opts: { tz: string; now: Date; maxEvents: number },
): { events: BuiltChronicleEvent[]; dropped: ChronicleDropCounts } {
- const { kept, dropped } = screenChronicleProposals(proposals, ctx, opts.tz, opts.now);
+ const { kept, dropped } = screenChronicleProposals(proposals, ctx, opts.tz, opts.now, { maxEvents: opts.maxEvents });
const events = kept.map((ev) => buildChronicleEvent(ev, {
depthSlug: depth.slug, attendees: ctx.attendees, effectiveDate: ctx.effectiveDate, tz: opts.tz,
visibility: depth.visibility, depthHash: depth.contentHash, isoDay, normalizeKind,
@@ -229,10 +236,13 @@ export function buildChronicleEvents(proposals: ChronicleEventProposal[], ctx: C
*/
export async function runChronicleExtract(
engine: BrainEngine,
- opts: { slug: string; sourceId?: string; judge?: ChronicleJudge; tz?: string; signal?: AbortSignal },
+ opts: { slug: string; sourceId?: string; judge?: ChronicleJudge; tz?: string; signal?: AbortSignal;
+ /** #5329: events published from this page; `chronicle.max_events_per_page` when omitted. */
+ maxEvents?: number },
): Promise<ChronicleExtractResult> {
const sourceId = opts.sourceId ?? 'default';
const tz = opts.tz ?? 'UTC';
+ const maxEvents = opts.maxEvents ?? (await chronicleSettings(engine)).maxEventsPerPage;
const snapshot = await engine.readPageSnapshot(opts.slug, { sourceId });
if (!snapshot) return { slug: opts.slug, status: 'skipped', events_written: 0, reason: 'page_not_found' };
const ctx = chronicleJudgeContext(snapshot.page);
@@ -262,7 +272,7 @@ export async function runChronicleExtract(
}
const pin = pinDepth(snapshot);
const built = buildChronicleEvents(proposals, ctx, { slug: pin.slug, visibility: pin.visibility, contentHash: pin.contentHash },
- { tz, now: new Date() });
+ { tz, now: new Date(), maxEvents });
const generation = await publishChronicleGeneration(engine, {
sourceId, pin, maintenance, decisionRequestId: null, signal: opts.signal, events: built.events,
});
diff --git a/src/core/config.ts b/src/core/config.ts
index ae149dc029..72aef0f374 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1662,6 +1662,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
// no_events; the cap is now configurable and truncation is surfaced.
'chronicle.judge_max_tokens',
'chronicle.job_budget_usd', 'chronicle.auto_daily_limit', 'chronicle.auto_recent_days', 'chronicle.auto_settle_seconds', // #5876 rails (chronicle/config.ts validates)
+ 'chronicle.max_events_per_page', // #5329: events published per page extraction (default 25); the surplus is counted over_cap
// Takes bootstrap (v0.41.18.0, A12). The onboard remediation's two-gate
// consent reads this key, and enabling it is the documented path to
// `gbrain takes extract --from-pages` — same unregistered-key class.
diff --git a/test/chronicle-config-5876.test.ts b/test/chronicle-config-5876.test.ts
index 2a346b81cd..032bfae4b0 100644
--- a/test/chronicle-config-5876.test.ts
+++ b/test/chronicle-config-5876.test.ts
@@ -54,7 +54,7 @@ describe('auto_chronicle parsing', () => {
test('chronicle.* rails: defaults, explicit budget flag, malformed rows fall back', async () => {
expect(await chronicleSettings(engine)).toMatchObject({ jobBudgetUsd: 0.25, explicitBudget: false, dailyLimit: 200,
- recentDays: 30, settleSeconds: 180, judgeMaxTokens: 4000, invalid: [] });
+ recentDays: 30, settleSeconds: 180, judgeMaxTokens: 4000, maxEventsPerPage: 25, invalid: [] });
await engine.setConfig('chronicle.job_budget_usd', '0.4');
await engine.setConfig('chronicle.auto_daily_limit', 'lots');
const s = await chronicleSettings(engine);
diff --git a/test/chronicle-date-quality.test.ts b/test/chronicle-date-quality.test.ts
index 6312765bb3..2aa3d7e8ec 100644
--- a/test/chronicle-date-quality.test.ts
+++ b/test/chronicle-date-quality.test.ts
@@ -147,7 +147,7 @@ describe('cutoff arithmetic', () => {
expect(chronicleEventCutoff(ctx, 'Asia/Tokyo', now)).toBe('2026-04-18');
const { kept, dropped } = screenChronicleProposals([
ev('2026-04-18T22:00:00-07:00', 'Late call'), ev('2026-04-19', 'Next day'), ev('2026-04', 'Sometime in April'),
- ], ctx, 'America/Los_Angeles', now);
+ ], ctx, 'America/Los_Angeles', now, { maxEvents: 25 });
expect(kept.map((k) => k.what)).toEqual(['Late call']);
expect(dropped).toEqual({ future_dated: 1, date_imprecise: 1 });
});
diff --git a/test/chronicle-event-identity.test.ts b/test/chronicle-event-identity.test.ts
index a827ae18eb..e7e4c81bb1 100644
--- a/test/chronicle-event-identity.test.ts
+++ b/test/chronicle-event-identity.test.ts
@@ -60,7 +60,7 @@ const at = (whenIso: string) => new Date(whenIso).toISOString();
function slugsFor(proposals: ChronicleEventProposal[], tz = 'UTC', existing = new Map<string, string>()) {
const ctx = { input: {} as never, effectiveDate: today, attendees: [], pageDates: [new Date(`${today}T23:59:59Z`)] };
- const { events: built, dropped } = buildChronicleEvents(proposals, ctx, { slug: 'meetings/day', visibility: 'world', contentHash: 'h' }, { tz, now: new Date(`${today}T23:59:59Z`) });
+ const { events: built, dropped } = buildChronicleEvents(proposals, ctx, { slug: 'meetings/day', visibility: 'world', contentHash: 'h' }, { tz, now: new Date(`${today}T23:59:59Z`), maxEvents: 25 });
expect(dropped).toEqual({});
return { legacy: built.map((e) => e.slug), assigned: assignChronicleEventSlugs(built, existing).map((e) => e.slug) };
}
diff --git a/test/chronicle-max-events-5329.test.ts b/test/chronicle-max-events-5329.test.ts
new file mode 100644
index 0000000000..ff286c6101
--- /dev/null
+++ b/test/chronicle-max-events-5329.test.ts
@@ -0,0 +1,101 @@
+/**
+ * #5329 (e): a proposal-count cap per page extraction.
+ *
+ * Protects: a judge that returns an unbounded array (an event-dense transcript, a model that lists every sentence)
+ * publishes at most `chronicle.max_events_per_page` events (default 25). The cap is applied after the date screen,
+ * so a proposal without a day or dated after the page never occupies a slot; the kept proposals are the first in the
+ * judge's order (deterministic) and the rest are counted `events_dropped.over_cap`, never written. Counting costs no
+ * provider call: the judge runs once.
+ * Fails when: more than the cap reaches life/events/, the drop is uncounted, or the knob is unregistered or unvalidated.
+ * Seams: injected judge (`runPhaseChronicle({ judge })`, `runChronicleExtract({ judge })`), `engine.setConfig`.
+ */
+import { describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { operationsByName } from '../src/core/operations.ts';
+import { runPhaseChronicle } from '../src/core/cycle/chronicle.ts';
+import { KNOWN_CONFIG_KEYS } from '../src/core/config.ts';
+import { CHRONICLE_CONFIG_KEYS, chronicleSettings, validateChronicleConfigValue } from '../src/core/chronicle/config.ts';
+import {
+ chronicleJudgeContext, runChronicleExtract, screenChronicleProposals, type ChronicleEventProposal,
+} from '../src/core/chronicle/extract-events.ts';
+import { managedBrain, type ManagedBrain } from './helpers/managed-brain.ts';
+import { requirePostgresTestDatabase } from './helpers/test-backends.ts';
+
+/** PGLite in the unit lane; the e2e wrapper reruns every case on an isolated Postgres database. */
+const databaseUrl = process.env.GBRAIN_TEST_BACKEND === 'postgres' ? requirePostgresTestDatabase() : undefined;
+const brain = (run: (b: ManagedBrain) => Promise<void>) => managedBrain(run, { databaseUrl });
+
+const day = (offsetDays: number) => new Date(Date.now() + offsetDays * 86_400_000).toISOString().slice(0, 10);
+const PAGE_DAY = day(-3);
+const BODY = 'Alice and Bob walked the whole quarter: every launch, every hire, every decision, one after another. '.repeat(3);
+const meeting = () => `---\ntype: meeting\ntitle: Quarter review\ndate: ${PAGE_DAY}\n---\n\n${BODY}`;
+const ev = (when: string, what: string, kind = 'decision'): ChronicleEventProposal => ({ when, who: ['people/alice-example'], what, kind });
+const proposals = (n: number, when = PAGE_DAY) => Array.from({ length: n }, (_, i) => ev(when, `Decision ${String(i + 1).padStart(2, '0')}`));
+
+async function put(ctx: OperationContext, slug: string, content: string) {
+ return operationsByName.put_page.handler(ctx, { slug, content });
+}
+async function settle(engine: BrainEngine) {
+ await engine.executeRaw("UPDATE chronicle_page_state SET next_attempt_at=now()-interval '1 second', decided_at=now()-interval '1 hour' WHERE state='pending'");
+}
+async function written(engine: BrainEngine): Promise<string[]> {
+ const rows = await engine.executeRaw<{ what: string }>(
+ "SELECT frontmatter->'event'->>'what' AS what FROM pages WHERE type='event' AND deleted_at IS NULL ORDER BY what");
+ return rows.map((r) => r.what);
+}
+
+describe('#5329 chronicle.max_events_per_page', () => {
+ test('the knob is registered, validated and read with its default', async () => {
+ expect(KNOWN_CONFIG_KEYS).toContain('chronicle.max_events_per_page');
+ expect(CHRONICLE_CONFIG_KEYS).toContain('chronicle.max_events_per_page');
+ expect(validateChronicleConfigValue('chronicle.max_events_per_page', '25')).toBeNull();
+ expect(validateChronicleConfigValue('chronicle.max_events_per_page', '0')).toContain('Nothing was written');
+ expect(validateChronicleConfigValue('chronicle.max_events_per_page', '2.5')).toContain('Nothing was written');
+ });
+
+ test('40 proposals under the default cap: 25 kept in judge order, 15 counted over_cap; undated proposals take no slot', () => {
+ const ctx = chronicleJudgeContext({ slug: 'meetings/q', type: 'meeting', title: 'Q', compiled_truth: BODY, frontmatter: { date: '2026-04-18' } });
+ const now = new Date('2026-10-04T12:00:00Z');
+ const { kept, dropped } = screenChronicleProposals(proposals(40, '2026-04-18'), ctx, 'UTC', now, { maxEvents: 25 });
+ expect(kept.map((k) => k.what)).toEqual(proposals(25).map((p) => p.what));
+ expect(dropped).toEqual({ over_cap: 15 });
+
+ // Two imprecise and one future proposal in front: dropped for their own reasons, and the 25 slots still go to dated proposals.
+ const mixed = [ev('2024', 'Pilot', 'work'), ev('2026-04-19', 'Offsite', 'travel'), ev('2026-03', 'Closing', 'milestone'), ...proposals(30, '2026-04-18')];
+ const screened = screenChronicleProposals(mixed, ctx, 'UTC', now, { maxEvents: 25 });
+ expect(screened.kept.map((k) => k.what)).toEqual(proposals(25).map((p) => p.what));
+ expect(screened.dropped).toEqual({ date_imprecise: 2, future_dated: 1, over_cap: 5 });
+
+ // At or under the cap nothing is counted.
+ expect(screenChronicleProposals(proposals(25, '2026-04-18'), ctx, 'UTC', now, { maxEvents: 25 }).dropped).toEqual({});
+ });
+
+ test('the phase writes the cap and reports the rest; one judge call', () => brain(async ({ engine, ctx }) => {
+ expect((await chronicleSettings(engine)).maxEventsPerPage).toBe(25);
+ await put(ctx, 'meetings/quarter', meeting());
+ await settle(engine);
+ let calls = 0;
+ const r = await runPhaseChronicle(engine, { judge: async () => { calls++; return { events: proposals(40) }; } });
+ expect(calls).toBe(1);
+ expect(r.details).toMatchObject({ judged: 1, extracted: 1, events_written: 25, events_dropped: { over_cap: 15 } });
+ expect(await written(engine)).toEqual(proposals(25).map((p) => p.what));
+ const ledger = await engine.executeRaw<{ state: string; reason: string | null }>('SELECT state, reason FROM chronicle_page_state WHERE attempts > 0');
+ expect(ledger).toEqual([{ state: 'extracted', reason: null }]);
+ }), 120_000);
+
+ test('the operator lowers the cap; the direct extractor honors it too', () => brain(async ({ engine, ctx }) => {
+ await engine.setConfig('chronicle.max_events_per_page', '3');
+ expect((await chronicleSettings(engine)).maxEventsPerPage).toBe(3);
+ await put(ctx, 'meetings/quarter', meeting());
+ const r = await runChronicleExtract(engine, { slug: 'meetings/quarter', judge: async () => ({ events: proposals(8) }) });
+ expect(r).toMatchObject({ status: 'extracted', events_written: 3, events_dropped: { over_cap: 5 } });
+ expect(await written(engine)).toEqual(proposals(3).map((p) => p.what));
+
+ // A malformed stored value falls back to the default and is listed, like every other chronicle.* knob.
+ await engine.setConfig('chronicle.max_events_per_page', 'many');
+ const s = await chronicleSettings(engine);
+ expect(s.maxEventsPerPage).toBe(25);
+ expect(s.invalid).toEqual([{ key: 'chronicle.max_events_per_page', raw: 'many', fallback: 25 }]);
+ }), 120_000);
+});
diff --git a/test/e2e/chronicle-max-events-5329-postgres.test.ts b/test/e2e/chronicle-max-events-5329-postgres.test.ts
new file mode 100644
index 0000000000..88860f9e94
--- /dev/null
+++ b/test/e2e/chronicle-max-events-5329-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../chronicle-max-events-5329.test.ts'));