Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(chronicle): an empty or partial re-derivation never retires the previous event generation (#7013)

garrytan4b8e8d3f33ea
diff --git a/docs/architecture/key-files/core-services-1.md b/docs/architecture/key-files/core-services-1.md
index d49981e172..99dde6cb1a 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`/`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/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 retires the previous generation's owned events it did not reproduce (`retired_by: life-chronicle`; restored when produced again) only when the caller passes `replaces`: `execute.ts` and `runChronicleExtract` pass it for a complete judged generation (`extract-events.replacesPreviousGeneration`: at least one event, no proposal dropped by the date screen or the per-page cap, and a body no longer than the JUDGE_BODY_CHARS the judge reads; a segmented page's truth lead is read one character past it to tell) and for an ineligible revision's empty generation, so an empty or partial generation publishes what it has, retires nothing and still records its ledger outcome (#7013). `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 15ead9d02a..614506d689 100644
--- a/docs/guides/life-chronicle.md
+++ b/docs/guides/life-chronicle.md
@@ -278,4 +278,7 @@ brackets are filled in with real values on each surface.
<!-- chronicle-reasons:end -->
Don't hand-write `life/events/` pages: extraction owns them and retires events
-the page no longer supports. Edit the meeting page instead.
+the page no longer supports. Edit the meeting page instead. Only a complete
+re-extraction retires events: one that finds no events, drops or caps a
+proposal, or reads a page longer than the judge's window keeps the earlier
+events live.
diff --git a/src/core/chronicle/execute.ts b/src/core/chronicle/execute.ts
index 3d9dd6587b..d7797e1d73 100644
--- a/src/core/chronicle/execute.ts
+++ b/src/core/chronicle/execute.ts
@@ -10,9 +10,12 @@
* reconciliation → ledger outcome. An ended calendar invite takes the judge's
* place with its deterministic projection (invite-projection.ts): no
* reservation, no model call. A failed or superseded run never retires
- * the previous generation. A segmented page is never materialized: the judge
- * reads its compiled truth's first JUDGE_BODY_CHARS and its last message time
- * comes from a block-by-block parse (segmentedJudgePage).
+ * the previous generation, and neither does an empty or partial one (#7013:
+ * no events, a proposal dropped or capped, or a body longer than the judge
+ * read); an ineligible revision still retires it. A segmented page is never
+ * materialized: the judge reads its compiled truth's first JUDGE_BODY_CHARS
+ * and its last message time comes from a block-by-block parse
+ * (segmentedJudgePage).
*/
import type { BrainEngine } from '../engine.ts';
import { BudgetTracker, type PricingOverrides } from '../budget/budget-tracker.ts';
@@ -29,7 +32,7 @@ import type { ChronicleReasonCode } from './reasons.ts';
import type { ChronicleSettings } from './config.ts';
import { chroniclePageDate, isChronicleEligible } from './eligibility.ts';
import {
- allDroppedReason, buildChronicleEvents, chronicleJudgeContext, isValidProposal, JUDGE_BODY_CHARS, lastMessageAt,
+ allDroppedReason, buildChronicleEvents, chronicleJudgeContext, isValidProposal, JUDGE_BODY_CHARS, lastMessageAt, replacesPreviousGeneration,
type ChronicleDropCounts, type ChronicleJudge, type ChronicleJudgeResult,
} from './extract-events.ts';
import { endedInviteProposal, markInviteEvents } from './invite-projection.ts';
@@ -172,7 +175,7 @@ export async function executeChronicleRow(ctx: ChronicleExecContext, row: Chroni
// An ineligible revision of a page that once produced events retires them (E8). No model call.
if (row.state === 'skipped') {
const generation = await publishChronicleGeneration(engine, { sourceId: row.source_id, pin, events: [],
- decisionRequestId: null, maintenance: ctx.maintenance, signal: ctx.signal });
+ decisionRequestId: null, replaces: true, maintenance: ctx.maintenance, signal: ctx.signal });
await setNextAttempt(engine, row, null);
return done('skipped', row.reason, { retired: generation.retired.length });
}
@@ -181,7 +184,8 @@ export async function executeChronicleRow(ctx: ChronicleExecContext, row: Chroni
await finish(engine, row, row.attempts, { state: 'skipped', reason: 'no_extract', nextAttemptAt: null });
return done('skipped', 'no_extract');
}
- const { page, lastMessage } = isSegmentedPage(snapshot.page) ? await segmentedJudgePage(engine, snapshot.page) : { page: snapshot.page, lastMessage: undefined };
+ const { page, lastMessage, bodyTruncated } = isSegmentedPage(snapshot.page) ? await segmentedJudgePage(engine, snapshot.page)
+ : { page: snapshot.page, lastMessage: undefined, bodyTruncated: (snapshot.page.compiled_truth ?? '').length > JUDGE_BODY_CHARS };
const auto = row.trigger === 'auto';
const eligible = isChronicleEligible({
type: page.type, slug: page.slug, body: page.compiled_truth ?? '',
@@ -244,13 +248,14 @@ export async function executeChronicleRow(ctx: ChronicleExecContext, row: Chroni
}
const proposals = result?.events ?? [];
- const { events, dropped } = buildChronicleEvents(proposals, judgeCtx,
+ const built = buildChronicleEvents(proposals, judgeCtx,
{ slug: pin.slug, visibility: pin.visibility, contentHash: pin.contentHash }, { tz: ctx.tz, now, maxEvents: settings.maxEventsPerPage });
+ const { events, dropped } = built;
let generation;
try {
generation = await publishChronicleGeneration(engine, {
sourceId: row.source_id, pin, decisionRequestId: row.request_id, maintenance: ctx.maintenance, signal: ctx.signal,
- events: invite ? markInviteEvents(events) : events,
+ events: invite ? markInviteEvents(events) : events, replaces: replacesPreviousGeneration(built, bodyTruncated),
});
} catch (error) {
if ((error as Error)?.name === 'AbortError') throw error;
@@ -271,11 +276,13 @@ export type { ChronicleDepthPin };
/**
* A segmented page as the judge reads it, without materializing its body: `compiled_truth` is the truth's first
- * JUDGE_BODY_CHARS (all the judge and the length rule read), and `lastMessage` the latest message time over the truth,
- * parsed block by block; a block starting under a day header from an earlier block parses with that header's date.
+ * JUDGE_BODY_CHARS (all the judge and the length rule read), `bodyTruncated` whether the truth is longer than that,
+ * and `lastMessage` the latest message time over the truth, parsed block by block; a block starting under a day header
+ * from an earlier block parses with that header's date.
*/
-async function segmentedJudgePage(engine: BrainEngine, stored: Page): Promise<{ page: Page; lastMessage: Date | null }> {
- const page = { ...withoutBody(stored), compiled_truth: await truthLead(engine, Number(stored.id), JUDGE_BODY_CHARS), timeline: '' } as Page;
+async function segmentedJudgePage(engine: BrainEngine, stored: Page): Promise<{ page: Page; lastMessage: Date | null; bodyTruncated: boolean }> {
+ const lead = await truthLead(engine, Number(stored.id), JUDGE_BODY_CHARS + 1);
+ const page = { ...withoutBody(stored), compiled_truth: lead.slice(0, JUDGE_BODY_CHARS), timeline: '' } as Page;
let day = chroniclePageDate({ effectiveDate: stored.effective_date ?? null, effectiveDateSource: stored.effective_date_source ?? null,
frontmatter: stored.frontmatter ?? null })?.toISOString().slice(0, 10);
let lastMessage: Date | null = null;
@@ -284,5 +291,5 @@ async function segmentedJudgePage(engine: BrainEngine, stored: Page): Promise<{
if (last && (!lastMessage || last > lastMessage)) lastMessage = last;
for (const line of block.text.split('\n')) day = DAY_HEADER_RE.exec(line.trim())?.[1] ?? day;
}
- return { page, lastMessage };
+ return { page, lastMessage, bodyTruncated: lead.length > JUDGE_BODY_CHARS };
}
diff --git a/src/core/chronicle/extract-events.ts b/src/core/chronicle/extract-events.ts
index 3cf66c09cd..2d5837b107 100644
--- a/src/core/chronicle/extract-events.ts
+++ b/src/core/chronicle/extract-events.ts
@@ -13,6 +13,7 @@ import type { BrainEngine } from '../engine.ts';
import { matchingCloseBracket } from '../llm-json.ts';
import { maintenancePreflight } from '../persistence/prepared-maintenance.ts';
import { parseConversation } from '../conversation-parser/parse.ts';
+import { isSegmentedPage } from '../page-body/page-shape.ts';
import { chroniclePageDate } from './eligibility.ts';
import { chronicleSettings } from './config.ts';
import { buildChronicleEvent, pinDepth, publishChronicleGeneration, type BuiltChronicleEvent } from './publish.ts';
@@ -175,6 +176,15 @@ export function allDroppedReason(dropped: ChronicleDropCounts): ChronicleDropRea
return (dropped.date_imprecise ?? 0) > (dropped.future_dated ?? 0) ? 'date_imprecise' : 'future_dated';
}
+/**
+ * #7013: a judged generation replaces the previous one (its unreproduced owned events retire) only when it is complete:
+ * at least one event, no proposal dropped (date screen or cap) and the judge read the whole body. An empty or partial
+ * generation publishes what it has and retires nothing.
+ */
+export function replacesPreviousGeneration(built: { events: readonly unknown[]; dropped: ChronicleDropCounts }, bodyTruncated: boolean): boolean {
+ return built.events.length > 0 && Object.keys(built.dropped).length === 0 && !bodyTruncated;
+}
+
/** The latest message timestamp of a chat-shaped body (multi-day conversations end on their last message). */
export function lastMessageAt(body: string, fallbackDate: string | undefined): Date | null {
const { messages } = parseConversation(body, { fallbackDate, noPolish: true, noFallback: true });
@@ -279,8 +289,10 @@ 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(), maxEvents });
+ const bodyTruncated = isSegmentedPage(snapshot.page) || ctx.input.body.length > JUDGE_BODY_CHARS;
const generation = await publishChronicleGeneration(engine, {
sourceId, pin, maintenance, decisionRequestId: null, signal: opts.signal, events: built.events,
+ replaces: replacesPreviousGeneration(built, bodyTruncated),
});
const dropped = Object.keys(built.dropped).length ? { events_dropped: built.dropped } : {};
if (generation.superseded) {
diff --git a/src/core/chronicle/publish.ts b/src/core/chronicle/publish.ts
index 7976e6d25d..4fa8c5dc1a 100644
--- a/src/core/chronicle/publish.ts
+++ b/src/core/chronicle/publish.ts
@@ -15,11 +15,12 @@
* operator-edited event (hash changed) is never overwritten or retired;
* an operator-deleted event (deleted without `retired_by`) is never
* resurrected.
- * - Only after the whole generation published, the previous generation's
- * owned events it did not reproduce are retired (soft-deleted with
- * `retired_by: life-chronicle`, reversible); a later generation that
- * produces one again restores it. A failed or superseded run retires
- * nothing.
+ * - Only after the whole generation published, and only when the caller
+ * declares it a complete replacement (`replaces`), the previous
+ * generation's owned events it did not reproduce are retired (soft-deleted
+ * with `retired_by: life-chronicle`, reversible); a later generation that
+ * produces one again restores it. A failed or superseded run, and an empty
+ * or partial one (#7013), retires nothing.
*
* Managed brains publish through two maintenance intents (database-only);
* unmanaged brains write directly inside one attributed maintenance
@@ -164,12 +165,13 @@ export interface ChronicleGenerationResult {
}
/**
- * Publish one generation (possibly empty) for a pinned depth page and retire
- * the previous generation's owned events it did not reproduce.
+ * Publish one generation (possibly empty) for a pinned depth page. With `replaces` (a complete judged generation, or
+ * an ineligible revision's empty one) it then retires the previous generation's owned events it did not reproduce;
+ * without it (an empty or partial judged generation, #7013) it retires nothing.
*/
export async function publishChronicleGeneration(engine: BrainEngine, opts: {
sourceId: string; pin: ChronicleDepthPin; events: BuiltChronicleEvent[]; decisionRequestId: string | null;
- maintenance?: MaintenanceAuthority | null; signal?: AbortSignal;
+ replaces: boolean; maintenance?: MaintenanceAuthority | null; signal?: AbortSignal;
}): Promise<ChronicleGenerationResult> {
const { sourceId, pin } = opts;
const maintenance = opts.maintenance === undefined ? await maintenancePreflight(engine, sourceId) : opts.maintenance;
@@ -225,6 +227,7 @@ export async function publishChronicleGeneration(engine: BrainEngine, opts: {
}
}
+ if (!opts.replaces) return result;
const keep = new Set(events.map((e) => e.slug));
const stale = await engine.executeRaw<{ slug: string; revision: string; content_hash: string }>(
`SELECT slug, knowledge_revision::text AS revision, content_hash FROM pages
diff --git a/test/pathological/i7013-chronicle-partial-generation.test.ts b/test/pathological/i7013-chronicle-partial-generation.test.ts
new file mode 100644
index 0000000000..53e1e4b884
--- /dev/null
+++ b/test/pathological/i7013-chronicle-partial-generation.test.ts
@@ -0,0 +1,195 @@
+/**
+ * #7013 (Life Chronicle): an empty or partial re-derivation never retires the previous event generation.
+ *
+ * Protects: after a depth page's revision is re-judged, its earlier automatic events stay live unless the new
+ * generation is complete and non-empty. An honest empty judge answer ('[]'), a generation whose every proposal the
+ * date screen dropped, one the 'chronicle.max_events_per_page' cap trimmed, and one judged from a body longer than the
+ * judge reads (JUDGE_BODY_CHARS) publish what they have and retire nothing; the new revision's ledger row is still
+ * 'extracted', so the same content is not judged (paid for) again. A complete clean replacement still retires the
+ * events it no longer produces, and a page that stops being chronicle-shaped still retires its events.
+ * Fails when: an empty or partial generation soft-deletes ('retired_by: life-chronicle') an event the previous
+ * generation published, on a managed brain (maintenance intents) or an unmanaged one (direct transactions).
+ * Seams: the gateway's stub chat transport ('__setChatTransportForTests', no paid calls) behind the real default judge,
+ * so the judge reads only its body window. PGLite always, Postgres when DATABASE_URL is set.
+ */
+import { afterEach, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { operationsByName } from '../../src/core/operations.ts';
+import { runPhaseChronicle } from '../../src/core/cycle/chronicle.ts';
+import { importFromContent } from '../../src/core/import-file.ts';
+import { managedPersistenceEnabled } from '../../src/core/persistence/ownership.ts';
+import { JUDGE_BODY_CHARS } from '../../src/core/chronicle/extract-events.ts';
+import { configureGateway, resetGateway, __setChatTransportForTests, type ChatOpts, type ChatResult } from '../../src/core/ai/gateway.ts';
+import { _resetBudgetTrackerWarningsForTest } from '../../src/core/budget/budget-tracker.ts';
+import { isolatedSharedSkillsEngine } from '../helpers/shared-skills-engine.ts';
+import { withEnv } from '../helpers/with-env.ts';
+import { managedBrain, pathologicalArms } from './harness.ts';
+
+const today = new Date().toISOString().slice(0, 10);
+const future = new Date(Date.now() + 10 * 86_400_000).toISOString().slice(0, 10);
+const SLUG = 'notes/acme-example-sync';
+const BODY = 'Alice and Bob reviewed the launch plan and agreed on the next steps for the beta. '.repeat(3);
+const TAIL = 'Bob owns the launch email.';
+const ALICE = 'Alice agreed to ship the beta';
+const BOB = 'Bob owns the launch email';
+const meeting = (body: string, type = 'meeting') => `---\ntype: ${type}\ntitle: Acme example sync\ndate: ${today}\n---\n\n${body}\n`;
+const ev = (what: string, when = today) => ({ when, who: ['people/alice-example'], what, kind: 'commitment' });
+const BOTH_LIVE = [{ what: ALICE, deleted: false, retired_by: null }, { what: BOB, deleted: false, retired_by: null }];
+
+interface Brain {
+ engine: BrainEngine;
+ put(content: string): Promise<void>;
+ phase(): Promise<Record<string, unknown>>;
+}
+
+/** The stub chat model behind the default judge: 'answer' sees the user prompt the judge built (its body window). */
+function stubJudge(answer: (prompt: string) => unknown[]): string[] {
+ const prompts: string[] = [];
+ configureGateway({ chat_model: 'anthropic:claude-sonnet-4-6', env: { ANTHROPIC_API_KEY: 'sk-test' } });
+ __setChatTransportForTests(async (opts: ChatOpts): Promise<ChatResult> => {
+ const last = opts.messages[opts.messages.length - 1]!;
+ const prompt = typeof last.content === 'string' ? last.content : JSON.stringify(last.content);
+ prompts.push(prompt);
+ const text = JSON.stringify(answer(prompt));
+ return { text, blocks: [{ type: 'text', text }], stopReason: 'end', model: opts.model ?? 'anthropic:claude-sonnet-4-6', providerId: 'anthropic',
+ usage: { input_tokens: 10, output_tokens: 10, cache_read_tokens: 0, cache_creation_tokens: 0 } };
+ });
+ return prompts;
+}
+
+async function managed(databaseUrl: string | undefined, run: (brain: Brain) => Promise<void>): Promise<void> {
+ await managedBrain(async ({ engine, ctx }) => {
+ expect(await managedPersistenceEnabled(engine)).toBe(true);
+ await run({
+ engine,
+ put: async (content) => {
+ const current = await engine.readPageSnapshot(SLUG, { sourceId: 'default' });
+ await operationsByName.put_page.handler(ctx, { slug: SLUG, content, ...(current ? { expected_revision: current.revision } : {}) });
+ },
+ phase: async () => {
+ await engine.executeRaw("UPDATE chronicle_page_state SET next_attempt_at=now()-interval '1 second', decided_at=now()-interval '1 hour' WHERE state='pending'");
+ return (await runPhaseChronicle(engine)).details as Record<string, unknown>;
+ },
+ });
+ }, { databaseUrl });
+}
+
+async function unmanaged(databaseUrl: string | undefined, run: (brain: Brain) => Promise<void>): Promise<void> {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-chronicle-7013-'));
+ try {
+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {
+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);
+ try {
+ expect(await managedPersistenceEnabled(engine)).toBe(false);
+ await engine.setConfig('chronicle.auto_settle_seconds', '0');
+ await engine.setConfig('chronicle.activated_at', new Date(Date.now() - 60_000).toISOString());
+ await run({
+ engine,
+ put: async (content) => { await importFromContent(engine, SLUG, content, { noEmbed: true, sourceId: 'default' }); },
+ phase: async () => (await runPhaseChronicle(engine)).details as Record<string, unknown>,
+ });
+ } finally { await close(); }
+ });
+ } finally { rmSync(home, { recursive: true, force: true }); }
+}
+
+async function events(engine: BrainEngine) {
+ return engine.executeRaw<{ what: string; deleted: boolean; retired_by: string | null }>(
+ "SELECT frontmatter->'event'->>'what' AS what, deleted_at IS NOT NULL AS deleted, frontmatter->>'retired_by' AS retired_by FROM pages WHERE type='event' ORDER BY what");
+}
+
+/** The ledger row of the depth page's current revision. */
+async function currentRow(engine: BrainEngine) {
+ return engine.executeRaw<{ state: string; reason: string | null }>(
+ "SELECT c.state, c.reason FROM chronicle_page_state c JOIN pages p ON p.id=c.page_id AND p.content_hash=c.content_hash WHERE p.slug=$1 AND p.source_id='default'",
+ [SLUG]);
+}
+
+/** Generation 1 publishes Alice's and Bob's events from a short body. */
+async function firstGeneration(brain: Brain): Promise<void> {
+ await brain.put(meeting(`${BODY} ${TAIL}`));
+ expect(await brain.phase()).toMatchObject({ judged: 1, extracted: 1, events_written: 2 });
+ expect(await events(brain.engine)).toEqual(BOTH_LIVE);
+}
+
+afterEach(() => { __setChatTransportForTests(null); resetGateway(); _resetBudgetTrackerWarningsForTest(); });
+
+for (const { backend, databaseUrl } of pathologicalArms()) {
+ for (const [mode, brain] of [['managed', managed], ['unmanaged', unmanaged]] as const) {
+ describe(`#7013 chronicle re-derivation never retires on an empty or partial generation (${backend}, ${mode})`, () => {
+ test('an honest empty answer retires nothing and the new revision is not judged again', () => brain(databaseUrl, async (b) => {
+ let answer: unknown[] = [ev(ALICE), ev(BOB)];
+ const prompts = stubJudge(() => answer);
+ await firstGeneration(b);
+ answer = [];
+ await b.put(meeting(`${BODY} Wording changed. ${TAIL}`));
+ expect(await b.phase()).toMatchObject({ judged: 1, no_events: 1, events_written: 0, events_retired: 0, reasons: { no_events: 1 } });
+ expect(await events(b.engine)).toEqual(BOTH_LIVE);
+ expect(await currentRow(b.engine)).toEqual([{ state: 'extracted', reason: 'no_events' }]);
+ expect(prompts.length).toBe(2);
+ expect(await b.phase()).toMatchObject({ judged: 0, events_retired: 0 });
+ expect(prompts.length).toBe(2);
+ expect(await events(b.engine)).toEqual(BOTH_LIVE);
+ }), 180_000);
+
+ test('a generation whose every proposal the date screen drops retires nothing', () => brain(databaseUrl, async (b) => {
+ let answer: unknown[] = [ev(ALICE), ev(BOB)];
+ stubJudge(() => answer);
+ await firstGeneration(b);
+ answer = [ev('Offsite planning session', future)];
+ await b.put(meeting(`${BODY} Offsite next week. ${TAIL}`));
+ expect(await b.phase()).toMatchObject({ judged: 1, no_events: 1, events_written: 0, events_retired: 0, events_dropped: { future_dated: 1 } });
+ expect(await events(b.engine)).toEqual(BOTH_LIVE);
+ expect(await currentRow(b.engine)).toEqual([{ state: 'extracted', reason: 'future_dated' }]);
+ }), 180_000);
+
+ test('a generation the per-page cap trims retires nothing', () => brain(databaseUrl, async (b) => {
+ let answer: unknown[] = [ev(ALICE), ev(BOB)];
+ stubJudge(() => answer);
+ await firstGeneration(b);
+ await b.engine.setConfig('chronicle.max_events_per_page', '1');
+ answer = [ev(ALICE), ev('Carol joined the beta review')];
+ await b.put(meeting(`${BODY} Carol joined. ${TAIL}`));
+ expect(await b.phase()).toMatchObject({ judged: 1, extracted: 1, events_written: 1, events_retired: 0, events_dropped: { over_cap: 1 } });
+ expect(await events(b.engine)).toEqual(BOTH_LIVE);
+ expect(await currentRow(b.engine)).toEqual([{ state: 'extracted', reason: null }]);
+ }), 180_000);
+
+ test('a generation judged from a truncated body retires nothing past the window', () => brain(databaseUrl, async (b) => {
+ const prompts = stubJudge((prompt) => (prompt.includes(TAIL) ? [ev(ALICE), ev(BOB)] : [ev(ALICE)]));
+ await firstGeneration(b);
+ const long = BODY + 'The team walked through every launch metric in detail. '.repeat(Math.ceil(JUDGE_BODY_CHARS / 50)) + TAIL;
+ expect(long.length).toBeGreaterThan(JUDGE_BODY_CHARS);
+ await b.put(meeting(long));
+ expect(await b.phase()).toMatchObject({ judged: 1, extracted: 1, events_written: 1, events_retired: 0 });
+ expect(prompts.length).toBe(2);
+ expect(prompts[1]!.includes(TAIL)).toBe(false);
+ expect(await events(b.engine)).toEqual(BOTH_LIVE);
+ expect(await currentRow(b.engine)).toEqual([{ state: 'extracted', reason: null }]);
+ }), 180_000);
+
+ test('control: a complete clean replacement still retires the event it no longer produces', () => brain(databaseUrl, async (b) => {
+ let answer: unknown[] = [ev(ALICE), ev(BOB)];
+ stubJudge(() => answer);
+ await firstGeneration(b);
+ answer = [ev(ALICE)];
+ await b.put(meeting(`${BODY} Bob handed the email to Alice.`));
+ expect(await b.phase()).toMatchObject({ judged: 1, extracted: 1, events_written: 1, events_retired: 1 });
+ expect(await events(b.engine)).toEqual([{ what: ALICE, deleted: false, retired_by: null }, { what: BOB, deleted: true, retired_by: 'life-chronicle' }]);
+ expect(await currentRow(b.engine)).toEqual([{ state: 'extracted', reason: null }]);
+ }), 180_000);
+
+ test('control: a depth page that stops being a meeting still retires its events without a model call', () => brain(databaseUrl, async (b) => {
+ const prompts = stubJudge(() => [ev(ALICE), ev(BOB)]);
+ await firstGeneration(b);
+ await b.put(meeting(`${BODY} ${TAIL}`, 'note'));
+ expect(await b.phase()).toMatchObject({ judged: 0, events_retired: 2 });
+ expect(prompts.length).toBe(1);
+ expect(await events(b.engine)).toEqual([{ what: ALICE, deleted: true, retired_by: 'life-chronicle' }, { what: BOB, deleted: true, retired_by: 'life-chronicle' }]);
+ }), 180_000);
+ });
+ }
+}
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index c27db29bac..e5108d2c7d 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -294,6 +294,7 @@ test/pathological/d7-synthesize-reverse-write.test.ts
test/pathological/d8-patterns-reverse-write.test.ts
test/pathological/d9-dream-summary-overwrite.test.ts
test/pathological/facts-mirror-failures.test.ts
+test/pathological/i7013-chronicle-partial-generation.test.ts
test/pathological/w1-write-through-staging-window.serial.test.ts
test/persistence-background-pause.test.ts
test/persistence-bounded-read-session.test.ts
diff --git a/test/trust-taint.test.ts b/test/trust-taint.test.ts
index 38c289b0bd..206976cb55 100644
--- a/test/trust-taint.test.ts
+++ b/test/trust-taint.test.ts
@@ -256,7 +256,7 @@ describe('every other deriver stamps a non-unknown tier with edges', () => {
const depth = await page(`meetings/depth-${uniq()}`, 'agent_written');
const snapshot = (await engine.readPageSnapshot(depth.slug, { sourceId: 'default' }))!;
const slug = `events/2026-01-05-example-${uniq()}`;
- const out = await publishChronicleGeneration(engine, { sourceId: 'default', pin: pinDepth(snapshot), decisionRequestId: null, maintenance: null,
+ const out = await publishChronicleGeneration(engine, { sourceId: 'default', pin: pinDepth(snapshot), decisionRequestId: null, maintenance: null, replaces: true,
events: [{ slug, title: 'Example event', compiledTruth: 'An example event happened.', frontmatter: { captured_via: 'life-chronicle:auto', event: { depth: depth.slug } },
when: '2026-01-05', day: '2026-01-05', summary: 'Example event' }] });
expect(out.superseded).toBeUndefined();