Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): refuse remote put_page that omits the Timeline section and report removed rows (#5969)

garrytan3dd4c52c5094
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.md
index d82622755a..4f9768f8fb 100644
--- a/docs/architecture/key-files/core-persistence.md
+++ b/docs/architecture/key-files/core-persistence.md
@@ -24,7 +24,8 @@ Connector ingestion, item holds and checkpoint validation continue in [Core Pers
Accepted output replays provider-free after restart; page/take preparers recheck original/current grants, source incarnation and revisions. Unresolved facts remain DB-only without phantom pages. Retired takes skip; semantic fact snapshots exclude derived vector/cache fields and journal quotas reject overlarge retained intent. Managed consolidation retains the explicit chronological `valid_until` writeback from the legacy consolidation phase, scoped to the accepted source/fact IDs and revalidated semantic snapshots; contradiction probes never gain supersession authority. `submitMaintenanceIntent` admits a maintenance request with its own intent kind keyed by the intent; `prepareMaintenanceMutation` also handles `managed_maintenance_phantom_merge` and `managed_maintenance_phantom_delete` (both delegated to `cycle/phantom-redirect-managed.ts`). `publishMaintenancePage` accepts an optional `eventProjection` (Life Chronicle): the event page and its depth-page timeline row commit in the same publication with the depth page key locked. Remote maintenance remains refused.
- `src/core/persistence/derived-facts.ts` — database-only fact rows derived from page text (fence reconcile, conversation facts): `managedDerivedFactsPreflight` (managed check, accepting persistence, local writer, active source; before provider spend), `withDerivedFactsWrite` (one transaction holding the coordinator source capability and the page keys, like derived links), `writeDerivedFacts` (that on a managed brain, the caller's own engine call otherwise) and `replaceDerivedFactsForPage` (inside that transaction: the caller's current-page recheck, then the page's prior rows for one writer prefix are deleted and the replacement batch inserted, so a failed or raced extraction keeps the prior batch; `test/managed-facts-writers.test.ts`). No persistence request is admitted per row. Tests: `test/managed-extract-atoms.test.ts`, `test/managed-facts-backstop.test.ts`, `test/managed-maintenance.test.ts`.
-- `src/core/persistence/canonical-projections.ts` — installs the facts, takes and timeline projections of a canonical page body inside its publication transaction. Rows written by the conversation fact extractor (`cli:extract-conversation-facts*`) share the page coordinate without a fence and are never expired as rows that left it (#1928 parity with the extract_facts reconcile), so republishing a conversation keeps its extracted facts until their own replay replaces them. Preparation takes the caller's prior snapshot and writer class and pins the stored timeline rows and take row numbers. Writer classes: `editing` (revision-bound `put_page`, reconcile with an approved body decision), `preserving` (`put_page` without a revision, reconcile, connectors), `file` (managed sync of file edits and managed import) and `immutable` (company-brain imports). One pure decision table (`timelineRowAction`) maps each row state (`in_body`, `drifted`, `removed`, `removed_marked`, `database_only`) to `refresh_detail`, `delete`, `keep` or `materialize`: database-only rows are materialized by `editing` and `preserving` writers and kept by the others; a materialized bullet the new body drops is deleted by `editing`/`file`, rendered again by `preserving` and kept DB-side by `immutable`. `materializeTimeline` runs during preparation, before the body is imported, digested and rendered, and appends each round-trippable row after existing bullets in date-then-id order as a marked bullet (`timeline-marker.ts`); `renderMaterializedBullet` requires render-then-extract to return exactly the tuple and normalized detail, so backlink receipts, empty or delimiter-bearing sources are kept and never rendered. `pendingTimelineRows` counts materializable and kept rows for the repair and doctor. Deletes and detail refreshes match the pinned id, tuple and detail, so rows changed after preparation are untouched. Fence refusals are typed `invalid_fence` (`fence-repair/refusal.ts`): `compileCanonicalProjections`, the validation-only entry, refuses the first defect `scanCanonicalFences` finds (repeated marker, any strict-parser warning, a row number used twice on the page) with wire `invalid_params`; a new fence row whose number belongs to a database-only take refuses as `stored_row_collision` with wire `take_row_collision`. When the prior takes fence does not parse, the page's stored `takes.row_num` count as prior canonical rows (TE1), so a row Tier 1 normalized updates its take instead of colliding. `unrecordedCanonicalTimeline` returns the body's canonical tuples with no stored row under the normalized key (managed `extract --stale` inserts only these), and `materializedHistoryRanges` locates marker lines whose hash matches the bullet after it, plus that bullet's indented detail (the dream verifier's history exemption). Tests: `test/canonical-projection-history.test.ts`, `test/timeline-materialize.test.ts` (PGLite and Postgres). A write that would drop rows held by a fence quoted in markdown code (readers project nothing from it) is refused as `invalid_fence` / `quoted_fence_rows` instead of deleting them. Pinned by `test/fence-marker-projection.test.ts`.
+- `src/core/persistence/canonical-projections.ts` — installs the facts, takes and timeline projections of a canonical page body inside its publication transaction. Rows written by the conversation fact extractor (`cli:extract-conversation-facts*`) share the page coordinate without a fence and are never expired as rows that left it (#1928 parity with the extract_facts reconcile), so republishing a conversation keeps its extracted facts until their own replay replaces them. Preparation takes the caller's prior snapshot and writer class and pins the stored timeline rows and take row numbers. Writer classes: `editing` (revision-bound `put_page`, reconcile with an approved body decision), `preserving` (`put_page` without a revision, reconcile, connectors), `file` (managed sync of file edits and managed import) and `immutable` (company-brain imports). One pure decision table (`timelineRowAction`) maps each row state (`in_body`, `drifted`, `removed`, `removed_marked`, `database_only`) to `refresh_detail`, `delete`, `keep` or `materialize`: database-only rows are materialized by `editing` and `preserving` writers and kept by the others; a materialized bullet the new body drops is deleted by `editing`/`file`, rendered again by `preserving` and kept DB-side by `immutable`. `materializeTimeline` runs during preparation, before the body is imported, digested and rendered, and appends each round-trippable row after existing bullets in date-then-id order as a marked bullet (`timeline-marker.ts`); `renderMaterializedBullet` requires render-then-extract to return exactly the tuple and normalized detail, so backlink receipts, empty or delimiter-bearing sources are kept and never rendered. `pendingTimelineRows` counts materializable and kept rows for the repair and doctor. Deletes and detail refreshes match the pinned id, tuple and detail, so rows changed after preparation are untouched. Fence refusals are typed `invalid_fence` (`fence-repair/refusal.ts`): `compileCanonicalProjections`, the validation-only entry, refuses the first defect `scanCanonicalFences` finds (repeated marker, any strict-parser warning, a row number used twice on the page) with wire `invalid_params`; a new fence row whose number belongs to a database-only take refuses as `stored_row_collision` with wire `take_row_collision`. When the prior takes fence does not parse, the page's stored `takes.row_num` count as prior canonical rows (TE1), so a row Tier 1 normalized updates its take instead of colliding. `unrecordedCanonicalTimeline` returns the body's canonical tuples with no stored row under the normalized key (managed `extract --stale` inserts only these), and `materializedHistoryRanges` locates marker lines whose hash matches the bullet after it, plus that bullet's indented detail (the dream verifier's history exemption). Tests: `test/canonical-projection-history.test.ts`, `test/timeline-materialize.test.ts` (PGLite and Postgres). A write that would drop rows held by a fence quoted in markdown code (readers project nothing from it) is refused as `invalid_fence` / `quoted_fence_rows` instead of deleting them. Pinned by `test/fence-marker-projection.test.ts`. #5969 (D3): an ordinary `put_page` / `put_pages` intent carries a `TimelineWritePolicy` (`timeline-omission.ts`) that changes only the rows the writer saw (`removed`, `removed_marked`): an explicitly empty section deletes them for every writer class; an omitted section keeps them for a local preserving writer (`materialize`) and deletes them with `drop_timeline`; maintenance, reconcile and file writers pass no policy. The pinned timeline `DELETE` returns what it removed, and the projection closure returns `{ timelineRowsRemoved: { count, earliest, latest } }` counting only `removed`/`removed_marked` rows it actually deleted (a row changed after preparation is neither deleted nor counted); `timelineRowsToRemove` judges the same set ahead of publication.
+- `src/core/persistence/timeline-omission.ts` — #5969 (D3): `timelineSectionOf` reads a put_page body's Timeline section from the caller's raw content before normalization (`omitted`: no timeline sentinel and no `## Timeline`/`## History` heading outside code; `emptied`: a section with no entries; `present`). Admission (`page-mutations.ts`) records it on the intent as `timeline_section` (a caller-sent value is stripped; failed-writes replay passes the stored one through `submitPageMutation`'s `timelineSection`). `assertTimelineNotOmitted` refuses a remote omission that would delete rows with `timeline_rows_would_be_removed` (fix: `get_page include_content:true`, then the `drop_timeline: true` retry) before admission and again during preparation; `timelineWritePolicy` builds the projection policy. Successful deletes surface as the receipt's `timeline_rows_removed` advisory (`page-advisories.ts`, dates only), copied onto `put_pages` entries (`page-batch.ts`, which accepts `drop_timeline` per entry).
- `src/core/persistence/admission-retry.ts` — bounded retries for database-confirmed admission transaction aborts. Each retry reuses the UUID and normalized intent, rechecks guarded authority and reserves quota only on commitment. Standalone journal admission uses 100ms lock waits within the five-second retry budget to retain queue position behind short counter transactions; backoff occurs after rollback releases the connection so counter contention leaves pool capacity for reads. Ambiguous connection/commit errors are never classified as confirmed rollback. Real counter-lock, sustained-queue progress, read-capacity and after-insert rollback tests live in `test/persistence-journal.test.ts`. Withdrawal retries wrap its whole source-exclusive transaction with its existing lock policy; `admitWriteInTransaction` never backs off inside an existing unit of work. `test/persistence-withdrawal-retry.test.ts` verifies guard release, complete rollback and bounded contention.
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 4643e946af..5321aac16b 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -2334,6 +2334,16 @@ Reasons: `content_directory`.
|---|---|---|---|---|---|---|
| The skill target must remain within its selected root. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |
+### timeline_rows_would_be_removed
+
+<a id="timeline_rows_would_be_removed"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| A remote put_page or put_pages entry has no Timeline section and would delete the page's dated entries; resend it with the section or with drop_timeline: true. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |
+
+More: [docs/guides/write-refusals.md#timeline_rows_would_be_removed](../../docs/guides/write-refusals.md#timeline_rows_would_be_removed)
+
### timeout
<a id="timeout"></a>
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index 93bc81c66a..65950bd6e1 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -69,6 +69,7 @@ of making a duplicate.
| <a id="managed_pull_skipped"></a>`managed_pull_skipped` (cycle warn); doctor `sync_freshness` "upstream unknown" or "upstream N commit(s) ahead" | `managed_pull_skipped` | A managed brain never runs `git pull` inside a cycle: Git pull needs an explicit drained maintenance window, so an explicit `gbrain sync` without `--no-pull` is refused with `writer_coordinator_required`. An unattended cycle asked to pull (autopilot passes `pull: true`, `gbrain dream --pull`) instead syncs the checkout as it is and reports it: the sync phase result carries `details.upstream_refresh` (`pulled`, `failed`, `skipped_managed` or `not_requested`), and when the checkout tracks an upstream the phase is `warn` with `details.warning` (`code`, `cause`, `fix`, `docs`). Every sync also records the checkout's last upstream observation (the upstream commit, when it was last fetched or pushed, and how many upstream commits the synced commit lacks) in the source row. Doctor `sync_freshness` reports that separately from the local projection: a source with a `remote_url` whose observation is missing or older than 24 hours is "upstream unknown", and any source whose observation saw upstream commits it has not synced is "behind"; neither is reported fresh. `details.upstream_unknown_count` and `details.upstream_behind_count` count them. | `gbrain sources refresh <source>` (the printed `fix` fills in the source). It drains writes to the source's checkout, fast-forwards it to its upstream and runs the managed sync for every source bound to that checkout; see [worktree refresh refusals](#worktree-refresh-refusals) for what it can refuse. On a brain that is not managed, `gbrain sync --source <source>` pulls and records the observation. |
| <a id="facts_absorb_write_refused"></a>`facts_absorb_write_refused (<code>)`; `ingest_log` `write_refused: <code> …` | `facts_absorb_write_refused` | A durable `facts-absorb` job extracted facts but the write path refused to store them, for example `writer_coordinator_required` because the entity's Markdown file sits in a claimed canonical worktree before `sources writer activate`, or `permission_denied`, `invalid_params` or `writer_registration_required`. These refusals do not change on retry, so the job goes straight to `dead` on its first attempt instead of re-running inference; on a brain that is not yet activated, a job whose source root is a claimed worktree is refused before extraction starts, so it makes no model call; the `facts:absorb` row in `ingest_log` (and doctor `facts_extraction_health`) records `write_refused` with the real code, not a provider failure. The source page itself was already saved. | Fix the named cause first: `gbrain sources writer status <source>`, then finish the [claim and activate runbook](../architecture/topologies.md#claim-and-activate-runbook) for a claimed worktree, or fix the grant. Then `gbrain jobs retry <job id>` (the error names the id). |
| <a id="no_pricing"></a>`no_pricing` | `no_pricing` | A cost cap you set (`--max-cost`, `--max-usd`, `--max-cost-usd`, or an explicit cap in config such as `cycle.extract_atoms.budget_usd`) cannot be enforced, because gbrain has no price for the model the run was about to call. The run stops before that call. Under a default cap an unpriced model warns and runs instead. The message names the model, provider and kind, and JSON output carries the same guidance as fields: `code`, `model`, `provider`, `kind`, `units`, `lookup`, `register_command`, `register_scope` and `docs`. | Look up the provider's current price for the model, for example by searching the web for its pricing page. A chat model needs USD per 1M input tokens and USD per 1M output tokens; an embedding or reranker model needs USD per 1M tokens. On the brain host, run `gbrain pricing set <model> --input <usd> --output <usd> --source <pricing-page-url>` (or `--rate <usd>`), then retry. An agent connected over MCP cannot register prices: give the command to the brain's operator. See [registering a model price](../operations/spend-controls.md#registering-a-model-price). |
+| <a id="timeline_rows_would_be_removed"></a>`timeline_rows_would_be_removed` | `timeline_rows_would_be_removed` | A remote `put_page` (or a `put_pages` entry) has no Timeline section at all — no `<!-- timeline -->` sentinel and no `## Timeline` or `## History` heading — and would delete dated entries the page has, including rows `add_timeline_entry` added. `put_page` content replaces the whole page, so the omission must be explicit. Nothing was written. A section that is present but empty is a deliberate delete and is not refused; a local `gbrain put` without `--expected-revision` keeps the rows instead. | Re-read with `get_page include_content:true`, keep the Timeline section and resubmit with a new `request_id`; to remove every dated entry on purpose, resubmit the same content with `drop_timeline: true` (on put_pages, per entry). A successful write that deletes rows reports `timeline_rows_removed {count, earliest, latest, warning, fix}` (dates only); `get_versions` then `revert_version` restores them as new rows. |
| <a id="reconcile-private-facts"></a>reconcile private facts | `permission_denied` | `gbrain sources reconcile --apply` (and its preview) found a `## Facts` row that would edit, renumber or change the visibility of a stored private fact, copy a stored private claim into a row under another visibility, or copy a stored private row's context (24 characters or longer) verbatim into a world row. A row is identified by its row number and claim, so a world row that only shares a private row's claim is not a private row and publishes. The refusal names the row number, never its text. It guards against verbatim copies only; reworded text is not detected, so it is not a confidentiality proof. Sources are not compared, because rows share provenance such as "Slack import". Nothing was written. | Read the stored page with the printed `gbrain get --source <id> -- <slug>`, keep the named row as stored in the file (or remove the copied text), then run a fresh `gbrain sources reconcile <id> <slug> --preview` and apply it. Change private facts with `remember` and `forget`. |
### Other error codes
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 3d270b644a..3831179592 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -259,6 +259,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.99.0', text: 'Fixable facts and takes fences are now rewritten instead of held or refused: managed sync, put_page and the fact and take writers normalize a fence whose meaning is unambiguous (a missing end marker after the table, two-dash takes markers, zero or duplicate row numbers, header aliases, invented kinds and enum synonyms, assistant holders, percent confidences) without changing a claim or an existing row number, and managed sync commits the rewritten file. Results report `fences_normalized`; `gbrain sync --dry-run` lists `would_normalize`. `gbrain config set fences.normalize false` turns it off (such fences are then held or refused).' },
{ since: '0.0.0-wave11', text: '`gbrain repair <kind> --apply` and `gbrain doctor --remediate` now wait for each publication with the CLI write wait (`--wait`, `GBRAIN_WRITE_WAIT_MS`, `persistence.write_wait_ms`, else 30 s) instead of 5 s, so one run repairs a slow source; `--wait 0` stops at the first pending write and the rerun resumes.' },
{ since: '0.0.0-wave11', text: '`gbrain sources reconcile` now identifies a private fact row by its row number and claim, so a page whose world row shares a private row\'s claim publishes instead of being refused; it now also refuses a world row that copies a stored private row\'s context (24 or more characters) verbatim, naming only the row number.' },
+ { since: '0.0.0-wave11', text: 'A remote put_page or put_pages entry whose content has no Timeline section is now refused with `timeline_rows_would_be_removed` when it would delete the page\'s dated entries; keep the section (get_page include_content:true) or pass `drop_timeline: true`. A local `gbrain put` without an expected revision keeps those rows; an explicitly empty `## Timeline` still deletes them, and every write that deletes rows reports `timeline_rows_removed` (count and dates).' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/error-catalogue.ts b/src/core/error-catalogue.ts
index b0db478ed7..abddd82ee4 100644
--- a/src/core/error-catalogue.ts
+++ b/src/core/error-catalogue.ts
@@ -49,6 +49,8 @@ export const ERROR_CATALOGUE = {
source_checkout_missing: { code: 'recovery_required', docs: 'docs/guides/write-refusals.md#source_checkout_missing' },
managed_pull_skipped: { code: 'managed_pull_skipped', docs: 'docs/guides/write-refusals.md#managed_pull_skipped' },
no_pricing: { code: 'no_pricing', docs: 'docs/guides/write-refusals.md#no_pricing' },
+ timeline_rows_would_be_removed: { code: 'timeline_rows_would_be_removed', docs: 'docs/guides/write-refusals.md#timeline_rows_would_be_removed' },
+ reconcile_private_facts: { code: 'permission_denied', docs: 'docs/guides/write-refusals.md#reconcile-private-facts' },
// F0 `gbrain sources refresh` (worktree-wide coordinated ff-only refresh).
refresh_not_managed: { code: 'refresh_not_managed', docs: 'docs/guides/write-refusals.md#refresh_not_managed' },
refresh_not_owner: { code: 'refresh_not_owner', docs: 'docs/guides/write-refusals.md#refresh_not_owner' },
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index c035264c34..0ca035a597 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -316,6 +316,7 @@ export const CODES = {
sync_parser_regression: { class: 'server', summary: "Sync stopped because gbrain would hold a file whose exact bytes imported before; this is a gbrain bug.", why: "The upgrade invariant says a newer reader never refuses bytes an older one imported, so the run stops without advancing rather than hide a regression.", suggestion: 'Report it with the gbrain version, the file and the code; upgrade or pin the last good version, then run gbrain sync --source <id> --no-pull --retry-failed.' },
take_row_collision: { class: 'caller', summary: "A takes fence row number is already used by a different take that is not in this page's canonical fence." },
target_escape: { class: 'caller', summary: "The skill target must remain within its selected root." },
+ timeline_rows_would_be_removed: { class: 'caller', summary: "A remote put_page or put_pages entry has no Timeline section and would delete the page's dated entries; resend it with the section or with drop_timeline: true.", docs: 'docs/guides/write-refusals.md#timeline_rows_would_be_removed' },
timeout: { class: 'retryable', summary: "The operation did not finish within its time bound.", exit: 124 },
topology_change_required: { class: 'host_only', summary: "Adding this source would replace or overlap another owner root." },
trusted_local_only: { class: 'host_only', summary: 'The operation runs only from the trusted local CLI on the brain host; no MCP connection can call it.', legacy_error: 'permission_denied', suggestion: 'Ask the user to run the named gbrain command on the brain host.' },
diff --git a/src/core/ops/page-batch.ts b/src/core/ops/page-batch.ts
index 64f6a11420..0a86325549 100644
--- a/src/core/ops/page-batch.ts
+++ b/src/core/ops/page-batch.ts
@@ -19,6 +19,7 @@ const put_pages: Operation = {
content: { type: 'string', required: true, description: 'Complete markdown with frontmatter.' },
expected_revision: { type: 'string', description: 'Revision read; omit to create.' },
allow_empty: { type: 'boolean', description: 'Allow emptying a non-empty page.' },
+ drop_timeline: { type: 'boolean', description: 'Content without a Timeline section deletes its dated entries.' },
},
},
},
diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.ts
index a68a2d637d..1993bd36a3 100644
--- a/src/core/ops/pages.ts
+++ b/src/core/ops/pages.ts
@@ -297,6 +297,7 @@ const put_page: Operation = {
slug: { type: 'string', description: 'Page slug.', required: true },
content: { type: 'string', required: true, description: 'Complete markdown with frontmatter; read get_page include_content:true first.' },
allow_empty: { type: 'boolean', required: false, description: 'Allow emptying a non-empty page.' },
+ drop_timeline: { type: 'boolean', required: false, description: 'Content without a Timeline section deletes its dated entries; otherwise refused.' },
wait_ms: WRITE_WAIT_PARAM,
// v0.39.3.0 provenance write-through (WARN-8 + A1 + CV6). Optional fields
// for trusted local callers (capture CLI, autopilot, dream cycle). Remote
diff --git a/src/core/persistence/canonical-projections.ts b/src/core/persistence/canonical-projections.ts
index ea58e2e5ea..910df6f1ae 100644
--- a/src/core/persistence/canonical-projections.ts
+++ b/src/core/persistence/canonical-projections.ts
@@ -83,8 +83,21 @@ const TIMELINE_DECISIONS: Record<ProjectionWriter, Record<TimelineRowState, Time
immutable: { in_body: 'refresh_detail', drifted: 'delete', removed: 'delete', removed_marked: 'keep', database_only: 'keep' },
};
-export function timelineRowAction(writer: ProjectionWriter, state: TimelineRowState): TimelineRowAction {
- return TIMELINE_DECISIONS[writer][state];
+/**
+ * #5969 (D3): what an ordinary put_page / put_pages body says about its
+ * Timeline section (`timeline-omission.ts`); other writers pass none and keep
+ * the table above. Only rows the writer saw (`removed`, `removed_marked`)
+ * change: an explicitly empty section deletes them for every writer class; a
+ * body with no section at all keeps them for a local preserving writer
+ * (rendered back like a marked row) and, with `drop_timeline`, deletes them.
+ */
+export interface TimelineWritePolicy { section: 'present' | 'emptied' | 'omitted'; drop: boolean; preserveOmitted: boolean }
+
+export function timelineRowAction(writer: ProjectionWriter, state: TimelineRowState, policy?: TimelineWritePolicy): TimelineRowAction {
+ const action = TIMELINE_DECISIONS[writer][state];
+ if (!policy || (state !== 'removed' && state !== 'removed_marked')) return action;
+ if (policy.section === 'emptied' || (policy.section === 'omitted' && policy.drop)) return 'delete';
+ return policy.section === 'omitted' && policy.preserveOmitted ? 'materialize' : action;
}
function exactTimelineKey(entry: { date: string; source?: string | null; summary: string }): string {
@@ -159,7 +172,8 @@ export async function unrecordedCanonicalTimeline(engine: BrainEngine, pageId: n
}
/** Classify stored rows against a new body and the writer's prior snapshot. */
-function classifyTimeline(rows: StoredTimelineRow[], body: CanonicalBody, prior: CanonicalBody | null, slug: string, writer: ProjectionWriter) {
+function classifyTimeline(rows: StoredTimelineRow[], body: CanonicalBody, prior: CanonicalBody | null, slug: string, writer: ProjectionWriter,
+ policy?: TimelineWritePolicy) {
const timeline = canonicalTimeline(body, slug);
const exactIncoming = new Map([...timeline.values()].map(t => [exactTimelineKey(t), sanitizeForJsonb(t.detail ?? '')]));
const priorTimeline = prior ? new Set(canonicalTimeline(prior, slug).keys()) : new Set<string>();
@@ -168,11 +182,32 @@ function classifyTimeline(rows: StoredTimelineRow[], body: CanonicalBody, prior:
const key = timelineKey(row);
const state: TimelineRowState = exactIncoming.has(exactTimelineKey(row)) ? 'in_body' : timeline.has(key) ? 'drifted'
: priorMarked.has(key) ? 'removed_marked' : priorTimeline.has(key) ? 'removed' : 'database_only';
- return { ...row, key, state, action: timelineRowAction(writer, state) };
+ return { ...row, key, state, action: timelineRowAction(writer, state, policy) };
});
return { timeline, exactIncoming, pinned };
}
+/** True when the body carries at least one timeline entry the coordinator would project. */
+export function bodyHasTimelineEntries(body: CanonicalBody, slug: string): boolean {
+ return canonicalTimeline(body, slug).size > 0;
+}
+
+/** Dates of the timeline rows a write removed (or would remove): the rows it saw in the prior body and dropped. */
+export interface TimelineRowsRemoved { count: number; earliest: string; latest: string }
+
+function removedSummary(dates: string[]): TimelineRowsRemoved | null {
+ if (!dates.length) return null;
+ const sorted = dates.map(d => d.slice(0, 10)).sort();
+ return { count: sorted.length, earliest: sorted[0]!, latest: sorted[sorted.length - 1]! };
+}
+
+/** The stored rows this writer would delete because the new body dropped their bullets, judged now. */
+export async function timelineRowsToRemove(engine: BrainEngine, body: CanonicalBody, prior: PageSnapshot, slug: string,
+ writer: ProjectionWriter, policy?: TimelineWritePolicy): Promise<TimelineRowsRemoved | null> {
+ const { pinned } = classifyTimeline(await storedTimeline(engine, prior.page.id), body, prior.page, slug, writer, policy);
+ return removedSummary(pinned.filter(row => row.action === 'delete' && (row.state === 'removed' || row.state === 'removed_marked')).map(row => row.date));
+}
+
const collapse = (text: string) => sanitizeForJsonb(text).replace(/\s+/g, ' ').trim();
/**
@@ -203,10 +238,10 @@ export interface TimelineMaterialization { timeline: string; materialized: numbe
* digested, by writers that render the canonical file from the database.
*/
export async function materializeTimeline(engine: BrainEngine, body: CanonicalBody, slug: string,
- prior: PageSnapshot | null, writer: ProjectionWriter): Promise<TimelineMaterialization> {
+ prior: PageSnapshot | null, writer: ProjectionWriter, policy?: TimelineWritePolicy): Promise<TimelineMaterialization> {
const timelineText = body.timeline ?? '';
if (!prior) return { timeline: timelineText, materialized: 0, unrenderable: 0 };
- const { pinned } = classifyTimeline(await storedTimeline(engine, prior.page.id), body, prior.page, slug, writer);
+ const { pinned } = classifyTimeline(await storedTimeline(engine, prior.page.id), body, prior.page, slug, writer, policy);
const blocks: string[] = [];
const seen = new Set<string>();
let unrenderable = 0;
@@ -288,12 +323,12 @@ function takeCollision(rows: number[], sections: Map<number, FenceSection>, slug
* what this writer actually edited.
*/
export async function prepareCanonicalProjections(engine: BrainEngine, page: ParsedPage, slug: string, sourceId: string,
- prior: PageSnapshot | null, writer: ProjectionWriter): Promise<(tx: BrainEngine, pageId?: number) => Promise<void>> {
+ prior: PageSnapshot | null, writer: ProjectionWriter, policy?: TimelineWritePolicy): Promise<(tx: BrainEngine, pageId?: number) => Promise<CanonicalProjectionResult>> {
const { factRows, takes, quoted, sections } = compileCanonicalProjections(page, slug, sourceId);
const { timeline, exactIncoming, pinned } = classifyTimeline(prior ? await storedTimeline(engine, prior.page.id) : [],
- page, prior?.page ?? null, slug, writer);
+ page, prior?.page ?? null, slug, writer, policy);
const deletions = JSON.stringify(pinned.filter(row => row.action === 'delete')
- .map(({ id, date, source, summary, detail }) => ({ id, date, source, summary, detail })));
+ .map(({ id, date, source, summary, detail, state }) => ({ id, date, source, summary, detail, removed: state === 'removed' || state === 'removed_marked' })));
const refreshes = JSON.stringify(pinned.filter(row => row.action === 'refresh_detail')
.map(row => ({ id: row.id, detail: row.detail, next: exactIncoming.get(exactTimelineKey(row)) }))
.filter(row => row.next !== row.detail));
@@ -318,7 +353,9 @@ export async function prepareCanonicalProjections(engine: BrainEngine, page: Par
// statement (insertFacts, addTakesBatch) ends one, so order is kept.
return async (tx, pageId) => {
const id = pageId ?? (await tx.readPageSnapshot(slug, { sourceId }))?.page.id;
- if (id == null) return;
+ if (id == null) return { timelineRowsRemoved: null };
+ // #5969: only rows this statement actually deleted count; a row changed since preparation is left alone and uncounted.
+ const removedDates: string[] = [];
if (quoted) await refuseQuotedFenceLoss(tx, id, quoted, takeRowsGone, factRows, slug, sourceId);
// Fact IDs in permanent receipts remain meaningful when a canonical row is
// removed/replaced. Expire and detach its row position instead of deleting it.
@@ -351,9 +388,10 @@ export async function prepareCanonicalProjections(engine: BrainEngine, page: Par
// Event-page references have a different canonical origin and remain intact;
// new rows carry their Markdown detail on insert, pinned rows refresh only from their preimage.
const timelineRows = [
- () => tx.executeRaw(`DELETE FROM timeline_entries t USING jsonb_to_recordset($2::text::jsonb) AS d(id integer,date date,source text,summary text,detail text)
+ () => tx.executeRaw<{ date: string; removed: boolean }>(`DELETE FROM timeline_entries t USING jsonb_to_recordset($2::text::jsonb) AS d(id integer,date date,source text,summary text,detail text,removed boolean)
WHERE t.page_id=$1 AND t.event_page_id IS NULL AND t.id=d.id AND t.date=d.date AND t.source=d.source
- AND t.summary=d.summary AND t.detail=d.detail`, [id, deletions]),
+ AND t.summary=d.summary AND t.detail=d.detail RETURNING t.date::text AS date, d.removed`, [id, deletions])
+ .then(rows => { for (const row of rows) if (row.removed) removedDates.push(row.date); return rows; }),
...[...timeline.values()].map(entry => () => tx.addTimelineEntry(slug, entry, { sourceId })),
() => tx.executeRaw(`UPDATE timeline_entries t SET detail=r.next FROM jsonb_to_recordset($2::text::jsonb) AS r(id integer,detail text,next text)
WHERE t.page_id=$1 AND t.event_page_id IS NULL AND t.id=r.id AND t.detail=r.detail`, [id, refreshes]),
@@ -367,5 +405,8 @@ export async function prepareCanonicalProjections(engine: BrainEngine, page: Par
await tx.addTakesBatch(takes.map(t => takesPreparation.toCanonicalBatchInput(id, t)));
await pipelined(tx, [...resolveTakes, ...timelineRows]);
} else await pipelined(tx, timelineRows);
+ return { timelineRowsRemoved: removedSummary(removedDates) };
};
}
+
+export interface CanonicalProjectionResult { timelineRowsRemoved: TimelineRowsRemoved | null }
diff --git a/src/core/persistence/page-advisories.ts b/src/core/persistence/page-advisories.ts
index 64b76fd62c..1a5f9c5abe 100644
--- a/src/core/persistence/page-advisories.ts
+++ b/src/core/persistence/page-advisories.ts
@@ -3,6 +3,7 @@ import type { ParsedPage } from '../import-file.ts';
import { sanitizeRemoteBody } from '../remote-body.ts';
import { writerLintForPutPage } from '../output/post-write.ts';
import type { WriteRequest } from './model.ts';
+import type { TimelineRowsRemoved } from './canonical-projections.ts';
import type { PageSnapshot } from '../page-state/types.ts';
import { prepareFactsBackstop } from './effect-facts.ts';
import { lineGrammarOptions, parseLineGrammar } from '../line-grammar.ts';
@@ -70,6 +71,17 @@ async function lineGrammarAdvisory(engine: BrainEngine, row: WriteRequest, page:
const LINT_MESSAGES: Record<string,string> = { citation:'Paragraph has no citation marker.',
link:'A link target is unavailable.', 'back-link':'A reverse link is missing.', 'triple-hr':'An ambiguous timeline separator was found.' };
+/**
+ * #5969: the timeline rows this write deleted (rows whose bullets the new body dropped). Dates only:
+ * page-write receipts never carry stored text.
+ */
+export function timelineRowsRemovedAdvisory(row: WriteRequest, removed: TimelineRowsRemoved): Record<string, unknown> {
+ return { ...removed,
+ warning: `This write deleted ${removed.count} timeline row(s) of ${row.slug} dated ${removed.earliest}${removed.latest !== removed.earliest ? ` to ${removed.latest}` : ''}, because the content dropped their bullets.`,
+ fix: readFix(`Lists ${row.slug}'s recent versions, read-only. If the rows were removed by mistake, revert_version with the id of the version before this write restores them (as new rows).`,
+ { mcp: { tool: 'get_versions', arguments: { slug: row.slug, limit: 5, include_body: false } } }) };
+}
+
export function remoteLinkHint(row: WriteRequest): Record<string, unknown> {
return row.authority.remote && !row.authority.autoLinkTrusted ? { auto_links: { skipped: 'remote',
hint: 'Body wikilinks are saved as text but NOT reconciled into the graph inline. With mention_links: queued, a post-commit `links` effect (listed by get_write_request) adds plain mention edges to existing pages this connection can read; typed and frontmatter edges are not added. A stdio `gbrain serve` sweeps them at startup + on idle; `gbrain serve --http` does not self-sweep — run `gbrain sweep --once` (delegates to a live serve over IPC), use trusted local capture/put_page for inline link extraction, or add_link for edges needed now.' } } : {};
diff --git a/src/core/persistence/page-batch.ts b/src/core/persistence/page-batch.ts
index 9a028391b0..89a3b27773 100644
--- a/src/core/persistence/page-batch.ts
+++ b/src/core/persistence/page-batch.ts
@@ -35,8 +35,8 @@ export const PAGE_BATCH_DEFAULT_WAIT_MS = 25_000;
const PREPARE_CONCURRENCY = 8;
/** Batch admission is one transaction over every page; it gets more than a single write's budget. */
const BATCH_ADMISSION_BUDGET_MS = 30_000;
-const PAGE_KEYS = new Set(['slug', 'content', 'expected_revision', 'allow_empty']);
-interface BatchPage { slug: string; content: string; expected_revision?: unknown; allow_empty?: unknown }
+const PAGE_KEYS = new Set(['slug', 'content', 'expected_revision', 'allow_empty', 'drop_timeline']);
+interface BatchPage { slug: string; content: string; expected_revision?: unknown; allow_empty?: unknown; drop_timeline?: unknown }
interface PageResult { index: number; slug: string; row?: WriteRequest; refusal?: OperationError; typeWarning?: PageTypeWarning | null }
interface BatchMarker { id: string; index: number; size: number }
@@ -50,10 +50,10 @@ function parsePages(value: unknown): BatchPage[] {
const seen = new Set<string>();
let bytes = 0;
const pages = value.map((page, index) => {
- if (!page || typeof page !== 'object' || Array.isArray(page)) throw invalid(`pages[${index}] must be an object {slug, content}; nothing was written.`, 'Pass each page as {slug, content} with optional expected_revision and allow_empty.');
+ if (!page || typeof page !== 'object' || Array.isArray(page)) throw invalid(`pages[${index}] must be an object {slug, content}; nothing was written.`, 'Pass each page as {slug, content} with optional expected_revision, allow_empty and drop_timeline.');
const record = page as Record<string, unknown>;
const extra = Object.keys(record).filter(key => !PAGE_KEYS.has(key));
- if (extra.length) throw invalid(`pages[${index}] has unsupported fields (${extra.join(', ')}); nothing was written.`, 'Each page accepts only slug, content, expected_revision and allow_empty; put frontmatter inside content.');
+ if (extra.length) throw invalid(`pages[${index}] has unsupported fields (${extra.join(', ')}); nothing was written.`, 'Each page accepts only slug, content, expected_revision, allow_empty and drop_timeline; put frontmatter inside content.');
if (typeof record.slug !== 'string' || !record.slug) throw invalid(`pages[${index}].slug must be a non-empty string; nothing was written.`, 'Give every page its slug, for example "notes/topic-name".');
if (typeof record.content !== 'string') throw invalid(`pages[${index}].content must be a string; nothing was written.`, 'Pass the complete markdown page, frontmatter included, as content.');
const key = record.slug.toLowerCase();
@@ -95,7 +95,8 @@ function pageEntry(result: PageResult): Record<string, unknown> {
return { ...base, request_id: row.request_id, state: 'committed', revision: receipt.revision ?? outcome.revision ?? null,
status: outcome.status, ...(typeof outcome.slug === 'string' && outcome.slug !== result.slug ? { duplicate_of: outcome.slug } : {}),
...(outcome.embedding_state !== undefined ? { embedding_state: outcome.embedding_state } : {}), ...warning,
- ...(outcome.fences_normalized ? { fences_normalized: outcome.fences_normalized } : {}) };
+ ...(outcome.fences_normalized ? { fences_normalized: outcome.fences_normalized } : {}),
+ ...(outcome.timeline_rows_removed ? { timeline_rows_removed: outcome.timeline_rows_removed } : {}) };
} catch (error) {
if (!(error instanceof OperationError)) throw error;
return { ...base, request_id: row.request_id, state: row.state, error: error.toJSON(), ...warning };
@@ -175,6 +176,7 @@ async function preparePages(own: OperationContext, shared: OperationContext, bat
const params: Record<string, unknown> = { slug: page.slug, content: page.content, source_id: sourceId };
if (page.expected_revision !== undefined) params.expected_revision = page.expected_revision;
if (page.allow_empty !== undefined) params.allow_empty = page.allow_empty;
+ if (page.drop_timeline !== undefined) params.drop_timeline = page.drop_timeline;
try {
prepared[index] = await preparePageAdmission(ctx, { operation: 'put_page', params,
batch: { id: batchId, index, size: pages.length, requestId: pageBatchChildRequestId(batchId, index) } });
diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.ts
index 8a16eaf9a0..7a14ff6ded 100644
--- a/src/core/persistence/page-mutations.ts
+++ b/src/core/persistence/page-mutations.ts
@@ -13,6 +13,7 @@ import { scannerSlugRootMode, scannerSourcePath } from '../write-through.ts';
import { sha256 } from './digest.ts';
import { assertPersistenceAccepting, estimatedRetryAfterMs, waitForWrite, writeResponse } from './service.ts';
import { parseWireWriteWaitMs } from './write-wait.ts';
+import { assertTimelineNotOmitted, isTimelineSection, timelineSectionOf, type TimelineSection } from './timeline-omission.ts';
import { admitWrite, assertPageRequestIdentity, assertReplayIntent, getWriteRequest, intentDigest, type WriteAdmission } from './journal.ts';
import { submissionAuthority, authorizeStoredRequest } from './authority.ts';
import { currentVerifiedLocalWriter, localHostId, readLocalWriter, registerLocalWriter, withVerifiedLocalRegistration } from './identity.ts';
@@ -148,7 +149,7 @@ const OWNER_FILE_INTENTS: ReadonlySet<string> = new Set(['managed_file_import',
export interface PageBatchMember { id: string; index: number; size: number; requestId: string }
export async function submitPageMutation(ctx: OperationContext,
- input: { operation: string; params: Record<string, unknown>; waitMs?: number; managedFileImport?: true }): Promise<Record<string, unknown>> {
+ input: { operation: string; params: Record<string, unknown>; waitMs?: number; managedFileImport?: true; timelineSection?: TimelineSection }): Promise<Record<string, unknown>> {
assertPersistenceAccepting(ctx.engine);
// #6007: wait_ms is a reply deadline from arrival, never part of the write's identity.
const arrived = performance.now();
@@ -169,7 +170,7 @@ export async function submitPageMutation(ctx: OperationContext,
* the admission to submit. `put_pages` admits several of these together.
*/
export async function preparePageAdmission(ctx: OperationContext,
- input: { operation: string; params: Record<string, unknown>; managedFileImport?: true; batch?: PageBatchMember }
+ input: { operation: string; params: Record<string, unknown>; managedFileImport?: true; batch?: PageBatchMember; timelineSection?: TimelineSection }
): Promise<{ prior: WriteRequest; admission?: undefined; typeWarning?: undefined; slugAdvisory?: undefined } | { prior?: undefined; admission: WriteAdmission; typeWarning: PageTypeWarning | null; slugAdvisory: string | null }> {
if (input.operation === 'put_page' && ['kind', 'preview', 'backup_reference'].some(key => Object.hasOwn(input.params, key))) {
if (ctx.remote !== false || input.managedFileImport !== true || !OWNER_FILE_INTENTS.has(String(input.params.kind)) ||
@@ -178,7 +179,7 @@ export async function preparePageAdmission(ctx: OperationContext,
'Drop kind, preview and backup_reference from put_page; reconciling a canonical file runs through gbrain sources reconcile on the brain host.');
}
}
- const { page_batch: _forged, ...params } = input.params;
+ const { page_batch: _forged, timeline_section: _section, ...params } = input.params;
const p: Record<string, unknown> = { ...params, ...parseMutationPrecondition(params) };
if (input.batch) p.page_batch = { id: input.batch.id, index: input.batch.index, size: input.batch.size };
const requestId = input.batch ? input.batch.requestId : typeof p.request_id === 'string' ? p.request_id : randomUUID();
@@ -207,6 +208,10 @@ export async function preparePageAdmission(ctx: OperationContext,
const intent = ['takes_add','takes_update','takes_supersede','takes_resolve','takes_remove'].includes(input.operation)
? await (await import('./takes-prepare.ts')).normalizeTakesIntent(ctx,p) : { ...p };
delete intent.request_id;
+ // #5969 (D3): read before normalization; a replay carries the section its first admission read.
+ if (input.operation === 'put_page' && input.managedFileImport !== true && p.kind === undefined && typeof p.content === 'string') {
+ intent.timeline_section = isTimelineSection(input.timelineSection) ? input.timelineSection : timelineSectionOf(p.content, slug);
+ }
if (input.operation === 'put_page') await normalizeSubagentPageInput(ctx, intent);
const typeWarning = input.operation === 'put_page' && input.managedFileImport !== true
? await undeclaredPageTypeWarning(ctx, { ...intent, slug }, sourceId) : null;
@@ -247,6 +252,10 @@ export async function preparePageAdmission(ctx: OperationContext,
const authority = await submissionAuthority(ctx, input.operation, sourceId, source.incarnation, slug);
await assertKnowledgePublicationAllowed(ctx.engine, { source_id: sourceId, source_incarnation: source.incarnation, slug });
const snapshot = await ctx.engine.readPageSnapshot(slug, { sourceId, includeDeleted: true });
+ if (typeof intent.content === 'string' && (typeof p.expected_revision !== 'string' || p.expected_revision === snapshot?.revision)) {
+ await assertTimelineNotOmitted(ctx.engine, { intent, remote: ctx.remote !== false, writer: typeof p.expected_revision === 'string' ? 'editing' : 'preserving',
+ slug, sourceId, content: intent.content, prior: snapshot });
+ }
const slugAdvisory = input.operation === 'put_page' && input.managedFileImport !== true
? suffixedSlugAdmission(ctx, slug, !!snapshot && !snapshot.page.deleted_at) : null;
// #5616: typed edit refusals before admission; publication repeats them on the locked snapshot.
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index 902d396cdd..a176773581 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -31,12 +31,13 @@ import type { SqlEngine, WriteRequest } from './model.ts';
import { isUnboundSourcePage } from './unbound-source.ts';
import { sealPageTextProjection } from '../page-state/projections.ts';
import { overlayCanonicalBodies } from '../page-state/snapshot.ts';
-import { materializeTimeline, prepareCanonicalProjections } from './canonical-projections.ts';
+import { materializeTimeline, prepareCanonicalProjections, type TimelineRowsRemoved } from './canonical-projections.ts';
+import { assertTimelineNotOmitted, timelineWritePolicy } from './timeline-omission.ts';
import { preserveProtectedTakes } from './protected-takes.ts';
import { isAutoLinkEnabled } from '../link-extraction.ts';
import { prepareAutomaticLinks } from './links-preparation.ts';
import { loadActivePackForEngine } from '../schema-pack/engine-resolution.ts';
-import { preparePageAdvisories, remoteLinkHint, pageNoopAdvisories } from './page-advisories.ts';
+import { preparePageAdvisories, remoteLinkHint, pageNoopAdvisories, timelineRowsRemovedAdvisory } from './page-advisories.ts';
import { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-guard.ts';
import { colonSlugWindowsRefusal, isWindowsColonTarget, nativeFileTarget } from './native-file-target.ts';
import { isSourceDbOnlySlug } from './source-storage.ts';
@@ -334,11 +335,15 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequest
const projected = !(row.operation === 'remember' || row.operation.startsWith('takes_') || (row.operation === 'extract_facts' && p.kind === 'managed_facts_entity'));
const writer = (row.operation === 'put_page' || row.operation === 'edit_page') && p.kind !== 'managed_maintenance_page'
&& (preparedIntent !== undefined || typeof p.expected_revision === 'string') ? 'editing' : 'preserving';
+ // #5969 (D3): only an ordinary put_page intent carries a timeline section; every other writer keeps the shared policy.
+ const timelinePolicy = row.operation === 'put_page' ? timelineWritePolicy(p, row.authority.remote, writer) : undefined;
+ if (timelinePolicy && typeof content === 'string') await assertTimelineNotOmitted(engine, { intent: p, remote: row.authority.remote, writer,
+ slug: row.slug, sourceId: row.source_id, content, prior: snapshot });
// #5567: database-only timeline rows are written back into the page before
// the no-op check, digest, rendering and chunking see the body.
if (projected && snapshot && typeof content === 'string') {
const parsed = parseMarkdown(content,row.slug);
- const { timeline, materialized } = await materializeTimeline(engine,parsed,row.slug,snapshot,writer);
+ const { timeline, materialized } = await materializeTimeline(engine,parsed,row.slug,snapshot,writer,timelinePolicy);
if (materialized) content = serializePageToMarkdown({...snapshot.page,...parsed,timeline,type:parsed.typeExplicit ? parsed.type : snapshot.page.type},parsed.tags);
}
// Detect an exact canonical no-op before ingestion can invoke any provider.
@@ -405,7 +410,7 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequest
const rendered = serializePageToMarkdown(renderedPage, tags);
const logicalNoop = snapshot !== null && digest(canonical(snapshot.page, snapshot.tags)) === digest(canonical(ready.parsedPage, tags));
const noop = logicalNoop && (snapshot?.page.deleted_at != null) === targetDeleted;
- const project = projected ? await prepareCanonicalProjections(engine,ready.parsedPage,row.slug,row.source_id,snapshot,writer) : undefined;
+ const project = projected ? await prepareCanonicalProjections(engine,ready.parsedPage,row.slug,row.source_id,snapshot,writer,timelinePolicy) : undefined;
const ordinaryPage = ['put_page','capture','restore_page','revert_version','edit_page'].includes(row.operation);
const advisories = noop || targetDeleted ? pageNoopAdvisories(row) : !ordinaryPage ? remoteLinkHint(row) : await preparePageAdvisories(engine,row,ready.parsedPage,snapshot);
// A managed maintenance page (e.g. the dream write-back after grounding
@@ -430,6 +435,7 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequest
...(core ? { exclusiveSources: core.exclusiveSources } : {}),
validate: async tx => { await ready.validate(tx); await core?.validate(tx); }, apply: async tx => {
let autoLinks: Awaited<ReturnType<NonNullable<typeof links>['apply']>> | undefined;
+ let removedTimeline: TimelineRowsRemoved | null = null;
if (!noop) {
const applied = await ready.apply(tx);
// Mandatory metadata shares publication rollback; exact no-ops never heal it.
@@ -450,7 +456,7 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequest
for (const tag of versionTags) await tx.addTag(row.slug, tag, source);
}
// #6007: the page the import just wrote live is the page the projections describe; no re-read.
- await project?.(tx, row.operation === 'restore_page' ? undefined : applied?.pageId);
+ removedTimeline = (await project?.(tx, row.operation === 'restore_page' ? undefined : applied?.pageId))?.timelineRowsRemoved ?? null;
autoLinks = await links?.apply(tx);
if (targetDeleted) await tx.softDeletePage(row.slug, source);
// Index installation and terminal receipt share this transaction. The import sealed the projection
@@ -460,6 +466,7 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequest
}
const coreUsage = core?.usage();
return { ...advisories, ...(autoLinks ? {auto_links:autoLinks} : {}), ...(coreUsage ? { core: coreUsage } : {}),
+ ...(removedTimeline ? { timeline_rows_removed: timelineRowsRemovedAdvisory(row, removedTimeline) } : {}),
status: noop ? 'skipped' : row.operation === 'restore_page' ? 'restored' : row.operation === 'revert_version' ? 'reverted' : 'created_or_updated',
slug: row.slug, source_id: row.source_id, chunks: ready.result.chunks, noop,
...(ready.result.chunks === 0 ? {chunk_skip_reason: noop ? 'write_skipped'
diff --git a/src/core/persistence/timeline-omission.ts b/src/core/persistence/timeline-omission.ts
new file mode 100644
index 0000000000..70a6b24bd4
--- /dev/null
+++ b/src/core/persistence/timeline-omission.ts
@@ -0,0 +1,85 @@
+/**
+ * #5969 (D3): a put_page / put_pages body that leaves out the page's Timeline
+ * section. The section's presence is read from the content as the caller sent
+ * it, before any normalization: `splitBody` returns an empty timeline both for
+ * an omission and for a present-but-empty section, and the bare-heading
+ * recognizer needs a dated bullet, so the two are indistinguishable later.
+ *
+ * - `omitted`: no timeline sentinel and no `## Timeline` / `## History`
+ * heading outside code. A remote caller is refused when stored rows it saw
+ * would be deleted, unless it passes `drop_timeline: true`; a local
+ * preserving writer (no expected_revision) keeps them.
+ * - `emptied`: the section is there with no entries: a deliberate delete for
+ * every writer class, reported.
+ * - `present`: a normal diff, reported.
+ *
+ * Admission records the section on the intent (`timeline_section`), so
+ * failed-writes replay and put_pages batch children carry it unchanged.
+ * Maintenance, reconcile and file-import writers record none and keep the
+ * shared projection policy.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { findTimelineSplitIndex, frontmatterBodyOffset, parseMarkdown } from '../markdown.ts';
+import type { PageSnapshot } from '../page-state/types.ts';
+import { opError, type OperationError } from '../ops/contract.ts';
+import type { Action } from '../agent-output.ts';
+import { bodyHasTimelineEntries, timelineRowsToRemove, type ProjectionWriter, type TimelineRowsRemoved, type TimelineWritePolicy } from './canonical-projections.ts';
+
+export const TIMELINE_SECTIONS = ['present', 'emptied', 'omitted'] as const;
+export type TimelineSection = typeof TIMELINE_SECTIONS[number];
+export const TIMELINE_OMISSION_CODE = 'timeline_rows_would_be_removed';
+const DOCS = 'docs/guides/write-refusals.md#timeline_rows_would_be_removed';
+const TIMELINE_HEADING = /^##\s+(timeline|history)\b/i;
+
+function hasTimelineHeading(lines: string[]): boolean {
+ let fenced = false;
+ for (const line of lines) {
+ if (/^\s*(`{3,}|~{3,})/.test(line)) { fenced = !fenced; continue; }
+ if (!fenced && TIMELINE_HEADING.test(line.trim())) return true;
+ }
+ return false;
+}
+
+/** What the caller's raw content says about its Timeline section. */
+export function timelineSectionOf(content: string, slug: string): TimelineSection {
+ const lines = content.slice(frontmatterBodyOffset(content)).split('\n');
+ if (findTimelineSplitIndex(lines) === -1 && !hasTimelineHeading(lines)) return 'omitted';
+ return bodyHasTimelineEntries(parseMarkdown(content, slug), slug) ? 'present' : 'emptied';
+}
+
+export function isTimelineSection(value: unknown): value is TimelineSection {
+ return (TIMELINE_SECTIONS as readonly unknown[]).includes(value);
+}
+
+/** The policy an ordinary put_page intent carries; none for every other writer. */
+export function timelineWritePolicy(intent: Record<string, unknown>, remote: boolean, writer: ProjectionWriter): TimelineWritePolicy | undefined {
+ if (!isTimelineSection(intent.timeline_section)) return undefined;
+ return { section: intent.timeline_section, drop: intent.drop_timeline === true, preserveOmitted: !remote && writer === 'preserving' };
+}
+
+export function timelineOmissionRefusal(slug: string, sourceId: string, removed: TimelineRowsRemoved): OperationError {
+ const rows = `${removed.count} timeline row(s) dated ${removed.earliest}${removed.latest !== removed.earliest ? ` to ${removed.latest}` : ''}`;
+ const retry: Action = { mcp: { tool: 'put_page', arguments: { slug, source_id: sourceId, drop_timeline: true } }, consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'Only if removing every one of those dated entries is intended: the same complete content with drop_timeline: true and a new request_id deletes them and reports them in timeline_rows_removed.',
+ inputs: [{ name: 'content', how: 'the same complete page content' }, { name: 'request_id', how: 'a new UUID' }] };
+ return opError(TIMELINE_OMISSION_CODE, `This put_page has no Timeline section, so it would delete ${rows} from ${slug}; nothing was written.`,
+ `Read the page with get_page include_content:true, keep its Timeline section in your content and resubmit with a new request_id. To remove every dated entry on purpose, resubmit the same content with drop_timeline: true; to remove only some, send the section without those bullets.`,
+ { why: 'put_page content replaces the whole page, and a body without a Timeline section would delete dated entries other writers added (add_timeline_entry, imports); a remote write must say so explicitly.',
+ docs: DOCS,
+ fix: { mcp: { tool: 'get_page', arguments: { slug, source_id: sourceId, include_content: true } }, consent: [], actor: 'agent', requires_exclusive: false,
+ why: `Returns ${slug} with its current Timeline section, so the resubmitted content keeps those entries.`,
+ verify: { mcp: { tool: 'get_timeline', arguments: { slug } } }, then: retry } });
+}
+
+/**
+ * Refuse a remote omission that would delete rows. Runs before admission (the
+ * caller gets the full fix) and again during preparation against the pinned
+ * prior, so a row added in between is not deleted silently.
+ */
+export async function assertTimelineNotOmitted(engine: BrainEngine, input: { intent: Record<string, unknown>; remote: boolean; writer: ProjectionWriter;
+ slug: string; sourceId: string; content: string; prior: PageSnapshot | null }): Promise<void> {
+ const policy = timelineWritePolicy(input.intent, input.remote, input.writer);
+ if (!input.remote || policy?.section !== 'omitted' || policy.drop || !input.prior || input.prior.page.deleted_at) return;
+ const removed = await timelineRowsToRemove(engine, parseMarkdown(input.content, input.slug), input.prior, input.slug, input.writer, policy);
+ if (removed) throw timelineOmissionRefusal(input.slug, input.sourceId, removed);
+}
diff --git a/src/core/persistence/types.ts b/src/core/persistence/types.ts
index 6bbfa27df1..7378d7435b 100644
--- a/src/core/persistence/types.ts
+++ b/src/core/persistence/types.ts
@@ -18,6 +18,7 @@ export const WRITE_ERROR_CODES = [
'connector_account_changed', 'connector_intent_outdated', 'checkpoint_validation_timeout',
'invalid_connector_text', 'connector_holds_exhausted', 'connector_fence_below_timeline',
'core_budget_exceeded', 'core_mark_owner_only', 'core_remote_edit_refused', 'core_delete_owner_only',
+ 'timeline_rows_would_be_removed',
] as const;
export type WriteErrorCode = typeof WRITE_ERROR_CODES[number];
diff --git a/src/core/repair/failed-writes.ts b/src/core/repair/failed-writes.ts
index b4060f6337..3d2ec0b616 100644
--- a/src/core/repair/failed-writes.ts
+++ b/src/core/repair/failed-writes.ts
@@ -35,6 +35,7 @@
* from the failed request id. The failed receipt stays as history.
*/
import { OperationError } from '../ops/contract.ts';
+import { isTimelineSection } from '../persistence/timeline-omission.ts';
import type { OperationContext } from '../ops/contract.ts';
import type { BrainEngine } from '../engine.ts';
import { digest } from '../persistence/digest.ts';
@@ -246,8 +247,10 @@ async function replay(ctx: OperationContext, failed: ApprovedWrite): Promise<Rep
if ('refused' in prepared) return prepared.refused;
const { params } = prepared;
try {
+ // #5969 (D3): the Timeline section the first admission read from the caller's content, before normalization.
+ const { timeline_section: timelineSection, ...replayed } = params;
if (live.operation === 'remember') await submitRememberMutation(lane, params);
- else await submitPageMutation(lane, { operation: live.operation, params });
+ else await submitPageMutation(lane, { operation: live.operation, params: replayed, ...(isTimelineSection(timelineSection) ? { timelineSection } : {}) });
} catch (error) {
if (error instanceof OperationError && !['write_pending', 'owner_unavailable', 'writer_lock_unavailable', 'writer_busy'].includes(error.code)) {
return { applied: false, outcome: ['revision_conflict', 'revision_required'].includes(error.code) ? 'conflict' : 'refused', reason: `${error.code}: ${error.message}` };
diff --git a/test/e2e/timeline-omission.test.ts b/test/e2e/timeline-omission.test.ts
new file mode 100644
index 0000000000..704b20c7a5
--- /dev/null
+++ b/test/e2e/timeline-omission.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../timeline-omission.test.ts'));
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index c2dedcb432..d3c5afa11b 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -5748,7 +5748,7 @@
"kind": "type",
"name": "ErrorCode",
"signature": [
- "\"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"rate_limited\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | (string & {})"
+ "\"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"rate_limited\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | (string & {})"
]
},
{
@@ -5834,7 +5834,7 @@
{
"kind": "class",
"members": [
- "canonical?: \"unknown\" | \"projection_pending\" | \"timeout\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"rate_limited\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"cache_quota_exceeded\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"consent_timeout\" | \"content_rejected\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"dirty_tree\" | \"effect_not_failed\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"facts_absorb_write_refused\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"fix_not_writable\" | \"file_removed_during_scan\" | \"file_too_large\" | \"follow_approval_required\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"git_index_locked\" | \"git_index_stale\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"managed_pull_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"parse_error\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pending_writes\" | \"pglite_busy\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"publication_pending\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"revision_unavailable\" | \"scope_missing\" | \"serve_port_in_use\" | \"serve_status_only\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"source_binding_required\" | \"source_id_taken\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_parser_regression\" | \"target_escape\" | \"topology_change_required\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | undefined",
+ "canonical?: \"unknown\" | \"projection_pending\" | \"timeout\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"rate_limited\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"cache_quota_exceeded\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"consent_timeout\" | \"content_rejected\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"dirty_tree\" | \"effect_not_failed\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"facts_absorb_write_refused\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"fix_not_writable\" | \"file_removed_during_scan\" | \"file_too_large\" | \"follow_approval_required\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"git_index_locked\" | \"git_index_stale\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"managed_pull_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"parse_error\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pending_writes\" | \"pglite_busy\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"publication_pending\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"revision_unavailable\" | \"scope_missing\" | \"serve_port_in_use\" | \"serve_status_only\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"source_binding_required\" | \"source_id_taken\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_parser_regression\" | \"target_escape\" | \"topology_change_required\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | undefined",
"canonicalCode: string",
"cause?: unknown",
"code: ErrorCode",
@@ -5852,9 +5852,9 @@
"receiptFields?: { operation: string; source_id: string; slug: string | null; principal_kind: string; principal_id: string; } | undefined",
"stack?: string | undefined",
"suggestion?: string | undefined",
- "toJSON: () => { contract_version?: 1 | undefined; fence_issues?: Record<string, unknown>[] | undefined; fence?: Record<string, unknown> | undefined; notices?: unknown[] | undefined; fix?: unknown; why?: string | undefined; reason?: string | undefined; write_error?: \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | undefined; write_request?: WriteReceipt | undefined; error: ErrorCode; code: string; message: string; suggestion: string | undefined; docs: string | undefined; detail: string | undefined; protocol_version: number | undefined; }",
+ "toJSON: () => { contract_version?: 1 | undefined; fence_issues?: Record<string, unknown>[] | undefined; fence?: Record<string, unknown> | undefined; notices?: unknown[] | undefined; fix?: unknown; why?: string | undefined; reason?: string | undefined; write_error?: \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | undefined; write_request?: WriteReceipt | undefined; error: ErrorCode; code: string; message: string; suggestion: string | undefined; docs: string | undefined; detail: string | undefined; protocol_version: number | undefined; }",
"why?: string | undefined",
- "writeError?: \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | undefined",
+ "writeError?: \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | undefined",
"writeRequest?: WriteReceipt | undefined"
],
"name": "OperationError",
diff --git a/test/timeline-materialize.test.ts b/test/timeline-materialize.test.ts
index 2f69cc0c24..69baf37f77 100644
--- a/test/timeline-materialize.test.ts
+++ b/test/timeline-materialize.test.ts
@@ -177,8 +177,9 @@ describe('#5567 database-only rows are materialized as marked bullets', () => {
const edited = f.file(slug).replace('Kickoff held before write-through', 'Kickoff held in person');
await f.put(slug, edited, { expected_revision: await f.revision(slug) });
expect((await f.timeline(slug)).map(r => r.summary)).toEqual(['Kickoff held in person']);
- await f.put(slug, page('Draft.'), { force: true });
- expect(await f.timeline(slug)).toEqual([]);
+ // #5969 (D3): a preserving put that omits the section keeps every row, so the dropped bullet is dropped from a present section.
+ await f.put(slug, page('Draft.', '- **2026-08-02** | markdown — Next step'), { force: true });
+ expect((await f.timeline(slug)).map(r => r.summary)).toEqual(['Next step']);
});
});
@@ -283,9 +284,11 @@ describe('#5567 per-writer classes for marked rows', () => {
await f.put(slug, page('Draft.', '- **2026-08-01** | connector — Old item'));
await f.legacy(slug, legacy);
await f.put(slug, page('Draft.', '- **2026-08-01** | connector — Old item'), { force: true });
- for (const render of [page('Connector render.'), page('Connector render.')]) {
+ // #5969 (D3): each render carries its section (an omitted one keeps every row for a preserving put).
+ const current = '- **2026-08-02** | connector — Current item';
+ for (const render of [page('Connector render.', current), page('Connector render.', current)]) {
await f.put(slug, render, { force: true });
- expect(await f.timeline(slug)).toEqual([normalized]);
+ expect(await f.timeline(slug)).toEqual([normalized, { date: '2026-08-02', source: 'connector', summary: 'Current item', detail: '' }]);
expect(await f.body(slug)).toContain(bullet);
}
});
diff --git a/test/timeline-omission.test.ts b/test/timeline-omission.test.ts
new file mode 100644
index 0000000000..3eca5a3eb5
--- /dev/null
+++ b/test/timeline-omission.test.ts
@@ -0,0 +1,251 @@
+/**
+ * #5969 (D3): a put_page / put_pages body that leaves out the Timeline section.
+ * Remote callers are refused unless they pass drop_timeline; a local writer
+ * without a revision keeps the rows; an explicitly empty section and a partial
+ * edit are ordinary deletes; every write that deletes rows reports
+ * `timeline_rows_removed` (dates only). Runs on PGLite and, through test/e2e,
+ * Postgres.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { OperationContext } from '../src/core/operations.ts';
+import { operationsByName } from '../src/core/operations.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { OperationError } from '../src/core/ops/contract.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { installFaultHook } from '../src/core/persistence/fault-points.ts';
+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
+import { MANAGED_WRITER_GUARD_FUNCTION_SQL } from '../src/core/persistence/writer-guard-schema.ts';
+import { repairRunner } from '../src/core/repair/registry.ts';
+import { resolveRepairScope } from '../src/core/repair/core.ts';
+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
+import { installPre5983Guard } from './helpers/pre-5983-guard.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { testBackends } from './helpers/test-backends.ts';
+
+const backends = testBackends();
+const engines: BrainEngine[] = [];
+const dataDir = mkdtempSync(join(tmpdir(), 'gbrain-timeline-omission-'));
+let closePostgres: (() => Promise<void>) | undefined;
+const logger = { info() {}, warn() {}, error() {} };
+
+beforeAll(async () => {
+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });
+ if (backends.includes('pglite')) {
+ const engine = new PGLiteEngine();
+ await engine.connect({}); await engine.initSchema(); engines.push(engine);
+ }
+ if (backends.includes('postgres')) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ engines.push(pg.engine); closePostgres = pg.close;
+ }
+}, 120_000);
+afterAll(async () => {
+ for (const engine of engines) { await disposePersistenceConsumer(engine); if (engine.kind === 'pglite') await engine.disconnect(); }
+ await closePostgres?.(); resetGateway(); rmSync(dataDir, { recursive: true, force: true });
+});
+
+const slug = 'projects/example';
+const head = '---\ntype: note\ntitle: Example project\n---\n';
+const authored = '- **2026-08-01** | markdown — Launch review\n- **2026-08-03** | markdown — Pilot signed';
+const withTimeline = (body: string, timeline = authored) => `${head}${body}\n\n## Timeline\n\n${timeline}\n`;
+const withoutTimeline = (body: string) => `${head}${body}\n`;
+
+interface Fixture {
+ engine: BrainEngine; sourceId: string; local: OperationContext; remote: OperationContext;
+ revision(): Promise<string>; rows(): Promise<string[]>; body(): Promise<string>;
+ put(ctx: OperationContext, content: string, extra?: Record<string, unknown>): Promise<Record<string, unknown>>;
+}
+
+/** A page with two authored bullets plus one add_timeline_entry row: three stored rows, all with bullets in the body. */
+async function fixture(run: (f: Fixture) => Promise<void>, opts: { managed?: boolean } = {}) {
+ for (const engine of engines) {
+ const dir = mkdtempSync(join(dataDir, 'case-'));
+ const root = join(dir, 'brain'); mkdirSync(root);
+ const sourceId = `omission-${randomUUID().slice(0, 8)}`;
+ const local = { engine, sourceId, remote: false, config: { engine: engine.kind, embedding_disabled: true }, dryRun: false, logger } as unknown as OperationContext;
+ const remote = { ...local, remote: true } as OperationContext;
+ const f: Fixture = {
+ engine, sourceId, local, remote,
+ revision: async () => (await engine.readPageSnapshot(slug, { sourceId }))!.revision,
+ rows: async () => (await engine.executeRaw<{ d: string }>(`SELECT t.date::text || ' ' || t.summary AS d FROM timeline_entries t JOIN pages p ON p.id=t.page_id
+ WHERE p.source_id=$1 AND p.slug=$2 AND t.event_page_id IS NULL ORDER BY t.date, t.summary`, [sourceId, slug])).map(r => r.d),
+ body: async () => { const s = (await engine.readPageSnapshot(slug, { sourceId }))!; return `${s.page.compiled_truth}\n${s.page.timeline ?? ''}`; },
+ put: (ctx, content, extra = {}) => submitPageMutation(ctx, { operation: 'put_page', params: { slug, content, request_id: randomUUID(), ...extra } }),
+ };
+ try {
+ await withEnv({ GBRAIN_HOME: join(dir, 'home') }, async () => {
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);
+ await claimWorktree(engine, sourceId, root);
+ if (opts.managed) {
+ await engine.setConfig('sync.write_through', 'true');
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ }
+ await f.put(local, withTimeline('First draft.'));
+ await submitPageMutation(local, { operation: 'add_timeline_entry', params: { slug, date: '2026-08-05', summary: 'Customer call', source: 'operator', request_id: randomUUID() } });
+ expect(await f.rows()).toEqual(['2026-08-01 Launch review', '2026-08-03 Pilot signed', '2026-08-05 Customer call']);
+ await run(f);
+ });
+ } finally {
+ installFaultHook(undefined);
+ if (opts.managed) await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await disposePersistenceConsumer(engine);
+ }
+ }
+}
+
+const ALL = ['2026-08-01 Launch review', '2026-08-03 Pilot signed', '2026-08-05 Customer call'];
+async function refusal(run: () => Promise<unknown>): Promise<OperationError> {
+ try { await run(); } catch (error) { if (error instanceof OperationError) return error; throw error; }
+ throw new Error('expected a refusal');
+}
+
+describe('#5969 (D3) remote put_page that omits the Timeline section', () => {
+ for (const [label, extra] of [['with expected_revision', 'revision'], ['with force', 'force']] as const) {
+ test(`is refused ${label} and deletes nothing; the fix re-reads the page, then names drop_timeline`, async () => {
+ await fixture(async f => {
+ const params = extra === 'revision' ? { expected_revision: await f.revision() } : { force: true };
+ const error = await refusal(() => f.put(f.remote, withoutTimeline('Remote rewrite.'), params));
+ expect(error.code).toBe('timeline_rows_would_be_removed');
+ expect(error.message).toContain('3 timeline row(s) dated 2026-08-01 to 2026-08-05');
+ expect(error.message).not.toContain('Launch review');
+ const json = error.toJSON() as { fix?: { mcp?: unknown; then?: { mcp?: unknown } } };
+ expect(json.fix?.mcp).toEqual({ tool: 'get_page', arguments: { slug, source_id: f.sourceId, include_content: true } });
+ expect(json.fix?.then?.mcp).toEqual({ tool: 'put_page', arguments: { slug, source_id: f.sourceId, drop_timeline: true } });
+ expect(await f.rows()).toEqual(ALL);
+ expect(await f.body()).toContain('First draft.');
+ // A caller cannot declare its own section.
+ expect((await refusal(() => f.put(f.remote, withoutTimeline('Remote rewrite.'), { ...params, timeline_section: 'present' }))).code)
+ .toBe('timeline_rows_would_be_removed');
+ });
+ }, 120_000);
+ }
+
+ test('drop_timeline: true deletes and reports them (dates only); revert_version restores them', async () => {
+ await fixture(async f => {
+ const before = await f.revision();
+ const receipt = await f.put(f.remote, withoutTimeline('Remote rewrite.'), { expected_revision: before, drop_timeline: true });
+ expect(receipt.timeline_rows_removed).toMatchObject({ count: 3, earliest: '2026-08-01', latest: '2026-08-05',
+ fix: { mcp: { tool: 'get_versions', arguments: { slug, limit: 5, include_body: false } } } });
+ expect(JSON.stringify(receipt.timeline_rows_removed)).not.toContain('Launch review');
+ expect(await f.rows()).toEqual([]);
+ const versions = await operationsByName.get_versions.handler(f.local, { slug, include_body: false }) as Array<{ id: number }>;
+ const prior = versions[0]!;
+ await operationsByName.revert_version.handler(f.local, { slug, version_id: prior.id, expected_revision: await f.revision(), request_id: randomUUID() });
+ expect(await f.rows()).toEqual(ALL);
+ });
+ }, 120_000);
+
+ test('an explicitly empty section is a deliberate delete: not refused, reported', async () => {
+ await fixture(async f => {
+ const receipt = await f.put(f.remote, `${head}Remote rewrite.\n\n## Timeline\n`, { force: true });
+ expect(receipt.timeline_rows_removed).toMatchObject({ count: 3, earliest: '2026-08-01', latest: '2026-08-05' });
+ expect(await f.rows()).toEqual([]);
+ });
+ }, 120_000);
+
+ test('a partially edited section is a normal diff, reported; an unchanged section reports nothing', async () => {
+ await fixture(async f => {
+ const current = (await operationsByName.get_page.handler(f.remote, { slug, include_content: true })) as { content: string };
+ const kept = await f.put(f.remote, current.content.replace('First draft.', 'Second draft.'), { expected_revision: await f.revision() });
+ expect(kept.timeline_rows_removed).toBeUndefined();
+ expect(await f.rows()).toEqual(ALL);
+ const partial = await f.put(f.remote, current.content.replace('First draft.', 'Third draft.').replace(/^- \*\*2026-08-03\*\*.*\n/m, ''),
+ { expected_revision: await f.revision() });
+ expect(partial.timeline_rows_removed).toMatchObject({ count: 1, earliest: '2026-08-03', latest: '2026-08-03' });
+ expect(await f.rows()).toEqual(['2026-08-01 Launch review', '2026-08-05 Customer call']);
+ });
+ }, 120_000);
+});
+
+describe('#5969 (D3) local writers', () => {
+ test('a local put without a revision (the preserving writer) keeps the rows and renders them back', async () => {
+ await fixture(async f => {
+ const receipt = await f.put(f.local, withoutTimeline('Local rewrite.'), { force: true });
+ expect(receipt.timeline_rows_removed).toBeUndefined();
+ expect(await f.rows()).toEqual(ALL);
+ const body = await f.body();
+ expect(body).toContain('Local rewrite.');
+ for (const summary of ['Launch review', 'Pilot signed', 'Customer call']) expect(body).toContain(summary);
+ });
+ }, 120_000);
+
+ test('a local revision-bound put that omits the section deletes the rows and reports them', async () => {
+ await fixture(async f => {
+ const receipt = await f.put(f.local, withoutTimeline('Local rewrite.'), { expected_revision: await f.revision() });
+ expect(receipt.timeline_rows_removed).toMatchObject({ count: 3, earliest: '2026-08-01', latest: '2026-08-05' });
+ expect(await f.rows()).toEqual([]);
+ });
+ }, 120_000);
+
+ test('a local preserving put with an explicitly empty section deletes the rows', async () => {
+ await fixture(async f => {
+ const receipt = await f.put(f.local, `${head}Local rewrite.\n\n<!-- timeline -->\n`, { force: true });
+ expect(receipt.timeline_rows_removed).toMatchObject({ count: 3 });
+ expect(await f.rows()).toEqual([]);
+ });
+ }, 120_000);
+});
+
+describe('#5969 (D3) put_pages entries', () => {
+ test('an entry that omits the section is refused on its own; with drop_timeline it commits and reports', async () => {
+ await fixture(async f => {
+ const putPages = operationsByName.put_pages;
+ const refused = await putPages.handler(f.remote, { request_id: randomUUID(), source_id: f.sourceId,
+ pages: [{ slug, content: withoutTimeline('Batch rewrite.'), expected_revision: await f.revision() }, { slug: 'notes/other', content: withoutTimeline('Other page.') }] }) as any;
+ expect(refused.pages[0]).toMatchObject({ state: 'refused', error: { error: 'timeline_rows_would_be_removed' } });
+ expect(refused.pages[1]).toMatchObject({ state: 'committed' });
+ expect(await f.rows()).toEqual(ALL);
+ const dropped = await putPages.handler(f.remote, { request_id: randomUUID(), source_id: f.sourceId,
+ pages: [{ slug, content: withoutTimeline('Batch rewrite.'), expected_revision: await f.revision(), drop_timeline: true }] }) as any;
+ expect(dropped.pages[0]).toMatchObject({ state: 'committed', timeline_rows_removed: { count: 3, earliest: '2026-08-01', latest: '2026-08-05' } });
+ expect(await f.rows()).toEqual([]);
+ });
+ }, 120_000);
+});
+
+describe('#5969 (D3) concurrency and replay', () => {
+ test('a row added between preparation and publication is neither deleted nor counted', async () => {
+ await fixture(async f => {
+ installFaultHook(async (point, detail) => {
+ if (point !== 'consumer:prepared' || detail.operation !== 'put_page') return;
+ installFaultHook(undefined);
+ await f.engine.transaction(tx => withCoordinatedWrite(tx, [f.sourceId], () => tx.executeRaw(
+ `INSERT INTO timeline_entries(page_id,date,source,summary,detail) SELECT id,'2026-08-09','operator','Late addition','' FROM pages WHERE source_id=$1 AND slug=$2`,
+ [f.sourceId, slug]), TEST_WRITE_ATTRIBUTION));
+ });
+ const receipt = await f.put(f.remote, withoutTimeline('Remote rewrite.'), { force: true, drop_timeline: true });
+ expect(receipt.timeline_rows_removed).toMatchObject({ count: 3, latest: '2026-08-05' });
+ expect(await f.rows()).toEqual(['2026-08-09 Late addition']);
+ });
+ }, 120_000);
+
+ test('failed-writes replay keeps drop_timeline and the section the first admission read', async () => {
+ await fixture(async f => {
+ for (const table of ['tags', 'timeline_entries', 'takes']) await f.engine.executeRaw(`ALTER TABLE ${table} ADD COLUMN IF NOT EXISTS source_id TEXT`);
+ await installPre5983Guard(f.engine);
+ // A new tag makes the pre-#5983 guard refuse the publication, leaving a failed receipt to replay.
+ const tagged = `---\ntype: note\ntitle: Example project\ntags: [launched]\n---\nRemote rewrite.\n`;
+ await f.put(f.remote, tagged, { force: true, drop_timeline: true }).catch(() => undefined);
+ const [failed] = await f.engine.executeRaw<{ intent: Record<string, unknown> }>(
+ `SELECT intent FROM persistence_requests WHERE source_id=$1 AND slug=$2 AND state='failed' AND operation='put_page'`, [f.sourceId, slug]);
+ expect(failed.intent).toMatchObject({ timeline_section: 'omitted', drop_timeline: true });
+ await f.engine.executeRaw(MANAGED_WRITER_GUARD_FUNCTION_SQL);
+ const scope = await resolveRepairScope(f.engine, f.sourceId);
+ const preview = await (await repairRunner(f.engine, { apply: false, logger })).run('failed-writes', scope, { explicit: true, sourceFlag: f.sourceId });
+ const applied = await (await repairRunner(f.engine, { apply: true, logger })).run('failed-writes', scope,
+ { explicit: true, sourceFlag: f.sourceId, expect: preview.apply_command.split('--expect ')[1] });
+ expect(applied.outcomes).toEqual({ replayed: 1 });
+ expect(await f.rows()).toEqual([]);
+ expect(await f.engine.getTags(slug, { sourceId: f.sourceId })).toEqual(['launched']);
+ }, { managed: true });
+ }, 120_000);
+});
diff --git a/test/timeline-section.test.ts b/test/timeline-section.test.ts
new file mode 100644
index 0000000000..1d1d8b957d
--- /dev/null
+++ b/test/timeline-section.test.ts
@@ -0,0 +1,21 @@
+/** #5969 (D3): reading a put_page body's Timeline section before normalization. */
+import { describe, expect, test } from 'bun:test';
+import { timelineSectionOf } from '../src/core/persistence/timeline-omission.ts';
+
+const slug = 'projects/example';
+const head = '---\ntype: note\ntitle: Example project\n---\n';
+const withTimeline = (body: string) => `${head}${body}\n\n## Timeline\n\n- **2026-08-01** | markdown — Launch review\n`;
+const withoutTimeline = (body: string) => `${head}${body}\n`;
+
+describe('#5969 timeline section detection', () => {
+ test('sentinels and the headings the parser accepts count as a section; code blocks do not', () => {
+ expect(timelineSectionOf(withTimeline('Body.'), slug)).toBe('present');
+ expect(timelineSectionOf(withoutTimeline('Body.'), slug)).toBe('omitted');
+ expect(timelineSectionOf(`${head}Body.\n\n## Timeline\n`, slug)).toBe('emptied');
+ expect(timelineSectionOf(`${head}Body.\n\n<!-- timeline -->\n`, slug)).toBe('emptied');
+ expect(timelineSectionOf(`${head}Body.\n\n## History\n\n- **2026-01-02** | notes — Founded\n`, slug)).toBe('present');
+ expect(timelineSectionOf(`${head}Body.\n\n<!-- timeline -->\n\n- **2026-01-02** | notes — Founded\n`, slug)).toBe('present');
+ expect(timelineSectionOf(`${head}Body.\n\n\`\`\`\n## Timeline\n\`\`\`\n`, slug)).toBe('omitted');
+ });
+});
+