Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(timeline): one entry per dated source of a citation, no emphasis markers, old-reading rows retired (#6226)

time-attack6ef0cd862045
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.md
index 1cd94426fa..7a095bac8e 100644
--- a/docs/architecture/key-files/core-persistence.md
+++ b/docs/architecture/key-files/core-persistence.md
@@ -24,7 +24,7 @@ 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`. #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/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; #6226 rows the older citation reading filed for either body are `superseded` (deleted by every writer) or, carrying their own detail, `superseded_annotated` (kept, never materialized); 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/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.md
index b03961df48..7abc5af8c3 100644
--- a/docs/architecture/key-files/core-utilities-2.md
+++ b/docs/architecture/key-files/core-utilities-2.md
@@ -37,7 +37,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/surface-audit.ts` — `writeSurfaceChangeAudit(engine, audit)`: the surface-mutation audit trail. Every surface mutation (rescope CLI, `POST /admin/api/rescope-client`, `request_tools` persist) writes one typed `mcp_request_log` row — `operation='surface_change'`, params a RAW object `{actor, client_id, old, new, via}` via `executeRawJsonb` (never `JSON.stringify` into `::jsonb`). Zero new DDL; rides `idx_mcp_log_time_agent` + the retention TODO. Best-effort: a failed audit write warns to stderr, never fails the committed mutation (callers needing fail-closed semantics inspect the returned boolean). CLI-actor rows are written even though stdio ops don't otherwise log (documented exception — audit outranks the transport-logging convention). The usage reader excludes these rows from op-call stats.
- `src/core/timeline-marker.ts` — the `<!-- gbrain:materialized v1 <12-hex> -->` marker that precedes a materialized timeline bullet: `timelineKey` (the one normalization for prior-set membership, dedup, stored-row matching and marker hashes), `timelineTupleHash`, `materializedMarker`, marker-line detection and `stripMaterializedMarkers`. Both timeline extractors skip marker lines (a marker never becomes bullet or header detail) and `sanitizeRemoteBody` drops them from chunk text unless `keepMaterializedMarkers` is set (remote `get_page`/`fetch` keep them so an edit round-trips). A marker whose hash no longer matches the bullet below it marks nothing.
-- `src/core/timeline-citations.ts` — `parseInlineCitationTimelineEntries`: inline `[Source: <source>, YYYY-MM-DD]` citations become timeline candidates whose summary is the citing paragraph without the citation. #6184: a comment-only line is a paragraph boundary and `stripHtmlComments` removes `<!-- … -->` spans (and dangling `<!--`/`-->`) before the summary is built, so section and materialized-row markers are never filed as entries.
+- `src/core/timeline-citations.ts` — `parseInlineCitationTimelineEntries`: inline `[Source: <source>, YYYY-MM-DD]` citations become timeline candidates whose summary is the citing paragraph without the citation. #6184: a comment-only line is a paragraph boundary and `stripHtmlComments` removes `<!-- … -->` spans (and dangling `<!--`/`-->`) before the summary is built, so section and materialized-row markers are never filed as entries. #6226: a citation files one entry per dated `source, date` segment (a `;` splits sources only after a date), summaries unwrap paired emphasis, and `supersededInlineCitationEntries` returns what the older one-source reading filed and the current reading no longer does; `timeline-extract.ts:supersededCitationTimeline` runs it with both extractors' bullet skips and `retractRemovedTimelineEntries` retracts those rows when their detail is extractor-written (`hasExtractorDetail`: empty or `Source: <source>`). The dated-bullet regexes (`TIMELINE_LINE_RE`, `_CN`, `isDatedTimelineLine`) live here and `link-extraction.ts` imports them.
- `src/core/transcripts.ts` — `listRecentTranscripts(engine, opts)` library reused by both the `gbrain transcripts recent` CLI and the `get_recent_transcripts` MCP op. Reads `dream.synthesize.session_corpus_dir` + `dream.synthesize.meeting_transcripts_dir` config (same as `discoverTranscripts`); walks `.txt` files within `days`; applies the `isDreamOutput` guard from `transcript-discovery.ts` (skips dream-generated files); returns `{path, date, mtime, length, summary}[]` sorted newest-first. Summary mode (default true) = first non-empty line + ~250 trailing chars; full mode caps at 100KB/file. Missing/non-existent corpus dirs return `[]`, not error. Trust gate lives in the op handler, not here: the op throws `permission_denied` for `ctx.remote === true`; this is a trusted library function used by both the gated op and the local CLI.
- `src/core/types.ts` extension + `src/core/operations.ts:search` + `src/core/import-file.ts` + `src/cli.ts` + `src/core/search/telemetry.ts` — the wiring layer for the retrieval-quality stack. `SearchResult` carries `evidence`, `create_safety`, `title_match_boost`, `alias_hit` (all optional; evidence/create_safety reference the union types in `evidence.ts`). The `search` MCP op uses a cheap-hybrid path by default and accepts a per-call `mode` (conservative|balanced|tokenmax) honored ONLY for trusted/local callers (`resolvePerCallMode(ctx, ...)` — remote callers use the configured mode so a remote provider can't force tokenmax spend); every search path stamps evidence fail-soft. `importFromContent` projects frontmatter `aliases:` into `page_aliases` via `normalizeAliasList` + `engine.setPageAliases` so new + changed pages register aliases at ingest. `src/cli.ts` carries the `gbrain search diagnose` dispatch (lazy import) and reconciles the `search` CLI path with the cheap-hybrid op. `src/core/search/telemetry.ts` carries in its rollup the rank-1 base_score drift signal (sum/count + 3 coarse buckets, aggregate not per-query), surfaced via `gbrain search stats`, backed by migration v111's `search_telemetry` columns. Tests: `test/cli-search-dispatch.test.ts`, `test/search/per-call-mode.test.ts`, `test/search/telemetry-rank1.test.ts`, `test/search/title-boost-stage.test.ts`, `test/search/alias-hop.test.ts`, `test/search/evidence.test.ts`, `test/search/searchvector-maxpool.test.ts`, `test/search/pre-migration-failopen.test.ts`.
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 273df8fcbd..88fee6670a 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -290,6 +290,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.103.0', text: 'Filtered vector search on Postgres runs pgvector iterative scans in relaxed_order, which keeps closer in-filter matches strict order dropped; `gbrain config set search.hnsw_iterative_scan strict_order` and a restart of serve and autopilot restore the old mode.' },
{ since: '0.60.103.0', text: 'With retrieval feedback on, MCP search and query results carry one visible line with the answer id (`Rate after use: rate_answer { answer_id: "ans_…", rating: 1-5 }`), so hosts that hide `_meta` can still rate.' },
{ since: '0.60.103.0', text: 'Imported transcript pages now also redact a password typed after a credential label (`password: …`, `login alice / …`) as `<REDACTED:labeled_credential>`; pages imported earlier are not rewritten, so run `gbrain transcripts audit-secrets --json` to list them (doctor `transcript_secret_exposure`).' },
+ { since: 'WAVE12', text: 'An inline `[Source: A, date; B, date]` citation now files one timeline entry per dated source instead of one entry with the last date, and timeline summaries drop paired `**`, `__`, `*` and `_` emphasis markers. Rows stored under the older reading are deleted the next time their page is written or extracted, never written back into the page; a row someone gave its own detail stays. Pages nobody edits keep the old rows until `gbrain extract timeline --prune-orphans` runs.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/link-extraction.ts b/src/core/link-extraction.ts
index 7278ddfabd..7f5910c75b 100644
--- a/src/core/link-extraction.ts
+++ b/src/core/link-extraction.ts
@@ -19,7 +19,7 @@ import { targetTakesVerb } from './link-target-roles.ts';
import { inSuppressedRange, rolePriorSuppressedRanges } from './machine-sections.ts';
import { statedRelationTypes } from './line-grammar.ts';
import { isValidSourceId } from './source-id.ts';
-import { parseInlineCitationTimelineEntries } from './timeline-citations.ts';
+import { isDatedTimelineLine, parseInlineCitationTimelineEntries, TIMELINE_LINE_RE, TIMELINE_LINE_RE_CN } from './timeline-citations.ts';
import { isMaterializedMarkerLine } from './timeline-marker.ts';
import { slugifyPath, slugifySegment } from './sync.ts';
import { SLUG_WORD_CHARS, SLUG_VARIATION_SELECTORS_RE } from './cjk.ts';
@@ -1939,11 +1939,10 @@ export function findTimelineSourceDelimiter(text: string): number {
// `Source — Summary` split ONLY to pipe-separated bullets (the canonical
// shape the FS extractor matches); a dash-separated bullet's rest is one
// summary and must not be shattered on its first interior dash.
-const TIMELINE_LINE_RE = /^\s*(?:-\s*)?\*\*(\d{4}-\d{2}-\d{2})\*\*\s*([|\-–—]+)\s*(.+?)\s*$/;
-// Chinese date lines: `- 2020年1月2日 | summary` (bold optional). Requires the
-// 年/月 markers so plain ASCII `- 2020-01-02 - text` does NOT match — non-bold
-// ASCII dates were never timeline entries and must stay that way.
-const TIMELINE_LINE_RE_CN = /^\s*(?:-\s*)?(?:\*\*)?(\d{4})年(\d{1,2})月(\d{1,2})日?(?:\*\*)?\s*([|\-–—]+)\s*(.+?)\s*$/;
+// Chinese date lines (TIMELINE_LINE_RE_CN): `- 2020年1月2日 | summary` (bold
+// optional). Requires the 年/月 markers so plain ASCII `- 2020-01-02 - text`
+// does NOT match. Both live in timeline-citations.ts, whose inline-citation
+// pass skips the lines they read.
// `### YYYY-MM-DD — summary` headings, as the FS extractor (timeline-extract.ts Format 2) accepts.
const TIMELINE_HEADING_RE = /^\s*###\s+(\d{4}-\d{2}-\d{2})\s*[\-–—]+\s*(.+?)\s*$/;
@@ -2046,7 +2045,7 @@ export function parseTimelineEntries(content: string): TimelineCandidate[] {
// Format 3 (the fs-source path). Blocks already captured by the timeline
// bullet pass are skipped (a bullet often carries its own citation).
for (const entry of parseInlineCitationTimelineEntries(content, {
- skipLine: (line) => TIMELINE_LINE_RE.test(line) || TIMELINE_LINE_RE_CN.test(line),
+ skipLine: isDatedTimelineLine,
})) {
// #3957: carry the citation's source label in `source` (the dedup-key
// column) so the row shape matches the FS extractor's Format 3; the
diff --git a/src/core/persistence/canonical-projections.ts b/src/core/persistence/canonical-projections.ts
index fbc7bc689b..8160ded0bc 100644
--- a/src/core/persistence/canonical-projections.ts
+++ b/src/core/persistence/canonical-projections.ts
@@ -7,7 +7,7 @@ import { TAKES_FENCE_BEGIN, TAKES_FENCE_END, parseTakesFence } from '../takes-fe
import { extractFactsFromFenceText } from '../facts/extract-from-fence.ts';
import { takesPreparation } from '../takes-write.ts';
import { parseTimelineEntries } from '../link-extraction.ts';
-import { extractTimelineFromContent, type ExtractedTimelineEntry } from '../timeline-extract.ts';
+import { extractTimelineFromContent, hasExtractorDetail, supersededCitationTimeline, type ExtractedTimelineEntry } from '../timeline-extract.ts';
import { sanitizeRemoteBody } from '../remote-body.ts';
import { sanitizeForJsonb } from '../batch-rows.ts';
import { materializedMarker, materializedMarkerHash, timelineKey, timelineKeyHash } from '../timeline-marker.ts';
@@ -51,10 +51,13 @@ export type ProjectionWriter = 'editing' | 'preserving' | 'file' | 'immutable';
* How one stored timeline row relates to the write, judged at preparation:
* `in_body` exactly matches a new bullet, `drifted` matches one only after
* normalization, `removed` / `removed_marked` had an unmarked / materialized
- * bullet in the prior body that the new body dropped, and `database_only`
- * has no bullet in either body.
+ * bullet in the prior body that the new body dropped, `superseded` is what
+ * the citation reading before #6226 filed for a citation either body still
+ * or once carried (with no detail beyond what the extractor writes) and the
+ * current reading replaces, `superseded_annotated` is such a row someone gave
+ * its own detail, and `database_only` has no bullet in either body.
*/
-export type TimelineRowState = 'in_body' | 'drifted' | 'removed' | 'removed_marked' | 'database_only';
+export type TimelineRowState = 'in_body' | 'drifted' | 'removed' | 'removed_marked' | 'superseded' | 'superseded_annotated' | 'database_only';
export type TimelineRowAction = 'refresh_detail' | 'delete' | 'keep' | 'materialize';
/**
@@ -64,6 +67,8 @@ export type TimelineRowAction = 'refresh_detail' | 'delete' | 'keep' | 'material
* drifted | delete | delete | delete | delete
* removed | delete | delete | delete | delete
* removed_marked | delete | materialize | delete | keep
+ * superseded | delete | delete | delete | delete
+ * superseded_ann.| keep | keep | keep | keep
* database_only | materialize | materialize | keep | keep
*
* A coordinated write deletes only rows whose bullet the writer can see in the
@@ -71,16 +76,18 @@ export type TimelineRowAction = 'refresh_detail' | 'delete' | 'keep' | 'material
* a revision or file preimage that contained it; a preserving writer renders it
* again. Writers that render from the database write bullet-less rows back into
* the page (`materialize`); rows that fail the render round trip, and every
- * `materialize` row a caller did not render, are kept. `put_page` with the
+ * `materialize` row a caller did not render, are kept. A superseded row is
+ * never written back (it would re-file the older, misdated reading); one
+ * carrying its own detail stays in the database only (#6226, taste T3). `put_page` with the
* current revision is the supported way to delete a materialized row. Deletes
* and detail refreshes also require the row id and detail pinned at
* preparation, so rows that change afterwards are left alone.
*/
const TIMELINE_DECISIONS: Record<ProjectionWriter, Record<TimelineRowState, TimelineRowAction>> = {
- editing: { in_body: 'refresh_detail', drifted: 'delete', removed: 'delete', removed_marked: 'delete', database_only: 'materialize' },
- preserving: { in_body: 'refresh_detail', drifted: 'delete', removed: 'delete', removed_marked: 'materialize', database_only: 'materialize' },
- file: { in_body: 'refresh_detail', drifted: 'delete', removed: 'delete', removed_marked: 'delete', database_only: 'keep' },
- immutable: { in_body: 'refresh_detail', drifted: 'delete', removed: 'delete', removed_marked: 'keep', database_only: 'keep' },
+ editing: { in_body: 'refresh_detail', drifted: 'delete', removed: 'delete', removed_marked: 'delete', superseded: 'delete', superseded_annotated: 'keep', database_only: 'materialize' },
+ preserving: { in_body: 'refresh_detail', drifted: 'delete', removed: 'delete', removed_marked: 'materialize', superseded: 'delete', superseded_annotated: 'keep', database_only: 'materialize' },
+ file: { in_body: 'refresh_detail', drifted: 'delete', removed: 'delete', removed_marked: 'delete', superseded: 'delete', superseded_annotated: 'keep', database_only: 'keep' },
+ immutable: { in_body: 'refresh_detail', drifted: 'delete', removed: 'delete', removed_marked: 'keep', superseded: 'delete', superseded_annotated: 'keep', database_only: 'keep' },
};
/**
@@ -178,10 +185,12 @@ function classifyTimeline(rows: StoredTimelineRow[], body: CanonicalBody, prior:
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>();
const priorMarked = prior ? markedTimeline(prior, slug) : new Set<string>();
+ const superseded = new Set([body, ...(prior ? [prior] : [])].flatMap(b => supersededCitationTimeline(safeBody(b)).map(t => timelineKey(t))));
const pinned = rows.map(row => {
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';
+ : priorMarked.has(key) ? 'removed_marked' : priorTimeline.has(key) ? 'removed'
+ : superseded.has(key) ? (hasExtractorDetail(row) ? 'superseded' : 'superseded_annotated') : 'database_only';
return { ...row, key, state, action: timelineRowAction(writer, state, policy) };
});
return { timeline, exactIncoming, pinned };
diff --git a/src/core/timeline-citations.ts b/src/core/timeline-citations.ts
index 23c7f21643..15732da72a 100644
--- a/src/core/timeline-citations.ts
+++ b/src/core/timeline-citations.ts
@@ -1,6 +1,45 @@
import { stripCodeBlocks } from './markdown-code.ts';
-const CITATION_TIMELINE_RE = /\[Source:\s*([^\]]+?),\s*(\d{4}-\d{2}-\d{2})\s*\]/g;
+const CITATION_TIMELINE_RE = /\[Source:\s*([^\]]+?,\s*\d{4}-\d{2}-\d{2})\s*\]/g;
+/**
+ * #6226: one `source, YYYY-MM-DD` of a citation body. A `;` separates two
+ * sources only right after a date, so `[Source: call; follow-up email,
+ * 2026-05-10]` keeps the one source `call; follow-up email`.
+ */
+const CITATION_SEGMENT_RE = /[\s;]*(.*?),\s*(\d{4}-\d{2}-\d{2})\s*(?:;|$)/gs;
+/** The reading before #6226: the whole body is one source, dated by its final date. */
+const LEGACY_CITATION_RE = /^(.+?),\s*(\d{4}-\d{2}-\d{2})$/s;
+
+/**
+ * Dated timeline bullets (`- **YYYY-MM-DD** | …`, and the `YYYY年M月D日` form)
+ * the database-side bullet parser reads; its inline-citation pass skips them.
+ */
+export const TIMELINE_LINE_RE = /^\s*(?:-\s*)?\*\*(\d{4}-\d{2}-\d{2})\*\*\s*([|\-–—]+)\s*(.+?)\s*$/;
+export const TIMELINE_LINE_RE_CN = /^\s*(?:-\s*)?(?:\*\*)?(\d{4})年(\d{1,2})月(\d{1,2})日?(?:\*\*)?\s*([|\-–—]+)\s*(.+?)\s*$/;
+export const isDatedTimelineLine = (line: string): boolean => TIMELINE_LINE_RE.test(line) || TIMELINE_LINE_RE_CN.test(line);
+
+/**
+ * #6226: paired Markdown emphasis (`**x**`, `__x__`, `*x*`, `_x_`) unwraps to
+ * its text. A marker needs a non-space next to it on the inside and no letter
+ * or digit on the outside, so `snake_case`, `a*b*c` and `2 * 3` stay as they
+ * are. A pair never spans a marker of its own kind, which keeps each pass
+ * linear; nested emphasis unwraps over up to three passes.
+ */
+const EMPHASIS_RES = [
+ /\*\*(?=\S)([^*]*?\S)\*\*/g,
+ /(?<![\p{L}\p{N}_])__(?=\S)([^_]*?\S)__(?![\p{L}\p{N}_])/gu,
+ /(?<![\p{L}\p{N}*])\*(?=[^\s*])([^*]*?[^\s*])\*(?![\p{L}\p{N}*])/gu,
+ /(?<![\p{L}\p{N}_])_(?=[^\s_])([^_]*?[^\s_])_(?![\p{L}\p{N}_])/gu,
+];
+
+function unwrapEmphasis(text: string): string {
+ for (let pass = 0; pass < 3; pass++) {
+ const next = EMPHASIS_RES.reduce((acc, re) => acc.replace(re, '$1'), text);
+ if (next === text) break;
+ text = next;
+ }
+ return text;
+}
export interface InlineCitationTimelineCandidate {
date: string;
@@ -80,33 +119,58 @@ function citationParagraphs(
return paragraphs;
}
-export function parseInlineCitationTimelineEntries(
- content: string,
- opts: { skipLine?: (line: string) => boolean } = {},
-): InlineCitationTimelineCandidate[] {
+type CitationOpts = { skipLine?: (line: string) => boolean };
+
+function readCitations(content: string, opts: CitationOpts, legacy: boolean): InlineCitationTimelineCandidate[] {
const result: InlineCitationTimelineCandidate[] = [];
for (const paragraph of citationParagraphs(content, opts)) {
const matches = [...paragraph.text.matchAll(CITATION_TIMELINE_RE)];
if (matches.length === 0) continue;
- const summary = stripHtmlComments(paragraph.text)
- .replace(/\[Source:[^\]]*\](?:\((?:[^()]|\([^()]*\))*\))?/g, '')
+ const text = stripHtmlComments(paragraph.text)
+ .replace(/\[Source:[^\]]*\](?:\((?:[^()]|\([^()]*\))*\))?/g, '');
+ const summary = (legacy ? text : unwrapEmphasis(text))
.replace(/^[-*>#\s]+/, '')
.replace(/\s+/g, ' ')
.trim()
.slice(0, 300);
if (!summary) continue;
+ const seen = new Set<string>();
for (const m of matches) {
- if (!isValidDate(m[2])) continue;
- result.push({
- date: m[2],
- source: m[1].trim().slice(0, 200),
- summary,
- });
+ const segments = legacy ? [LEGACY_CITATION_RE.exec(m[1])].filter(x => x !== null) : [...m[1].matchAll(CITATION_SEGMENT_RE)];
+ for (const segment of segments) {
+ const source = segment[1].trim().slice(0, 200);
+ const date = segment[2];
+ if (!isValidDate(date) || (!legacy && !source) || seen.has(`${date}\0${source}`)) continue;
+ seen.add(`${date}\0${source}`);
+ result.push({ date, source, summary });
+ }
}
}
return result;
}
+/**
+ * One entry per dated source of each `[Source: …, YYYY-MM-DD]` citation
+ * (#6226: `[Source: A, 2026-10-06; B, 2026-09-28]` files A on 2026-10-06 and
+ * B on 2026-09-28), summarized by the paragraph it annotates with citations,
+ * HTML comments (#6184) and paired emphasis removed.
+ */
+export function parseInlineCitationTimelineEntries(content: string, opts: CitationOpts = {}): InlineCitationTimelineCandidate[] {
+ return readCitations(content, opts, false);
+}
+
+/**
+ * The entries the reading before #6226 filed for `content` (a multi-source
+ * citation as one source with its final date, emphasis kept) that the
+ * current reading no longer produces. Stored rows equal to one of them are
+ * that older reading's output, so projection and retraction can retire them
+ * instead of writing them back into the page.
+ */
+export function supersededInlineCitationEntries(content: string, opts: CitationOpts = {}): InlineCitationTimelineCandidate[] {
+ const current = new Set(readCitations(content, opts, false).map(e => JSON.stringify([e.date, e.source, e.summary])));
+ return readCitations(content, opts, true).filter(e => !current.has(JSON.stringify([e.date, e.source, e.summary])));
+}
+
function isValidDate(s: string): boolean {
if (!/^\d{4}-\d{2}-\d{2}$/.test(s)) return false;
const [y, mo, d] = s.split('-').map(Number);
diff --git a/src/core/timeline-extract.ts b/src/core/timeline-extract.ts
index 930b160317..7ed1280637 100644
--- a/src/core/timeline-extract.ts
+++ b/src/core/timeline-extract.ts
@@ -12,6 +12,7 @@
*/
import { parseInlineCitationTimelineEntries, findTimelineSourceDelimiter, parseTimelineEntries } from './link-extraction.ts';
+import { isDatedTimelineLine, supersededInlineCitationEntries } from './timeline-citations.ts';
import type { BrainEngine } from './engine.ts';
import { firstMaterializedMarkerIndex } from './timeline-marker.ts';
@@ -30,6 +31,9 @@ export interface ExtractedTimelineEntry {
// duplicates every bullet extracted through both paths.
const findDelimiterOutsideLinks = findTimelineSourceDelimiter;
+// A Format 1 bullet line; this extractor's inline-citation pass (Format 3) skips it.
+const bulletLinePattern = /^-\s+\*\*\d{4}-\d{2}-\d{2}\*\*\s*\|/;
+
/** Extract timeline entries from markdown content */
export function extractTimelineFromContent(content: string, slug: string): ExtractedTimelineEntry[] {
const entries: ExtractedTimelineEntry[] = [];
@@ -87,7 +91,6 @@ export function extractTimelineFromContent(content: string, slug: string): Extra
// carries its own [Source: ...] citation, and re-extracting it would file
// a duplicate entry under a different (source, summary) shape that the
// DB-level uniqueness cannot collapse.
- const bulletLinePattern = /^-\s+\*\*\d{4}-\d{2}-\d{2}\*\*\s*\|/;
for (const entry of parseInlineCitationTimelineEntries(content, {
skipLine: (line) => bulletLinePattern.test(line),
})) {
@@ -100,6 +103,29 @@ export function extractTimelineFromContent(content: string, slug: string): Extra
type TimelineTuple = Pick<ExtractedTimelineEntry, 'date' | 'source' | 'summary'>;
const tupleKey = (e: TimelineTuple) => JSON.stringify([e.date, e.source, e.summary]);
+/**
+ * #6226: the tuples the inline-citation pass of either parser filed for this
+ * text before one citation could name several dated sources, and that the
+ * current reading no longer produces (supersededInlineCitationEntries).
+ */
+export function supersededCitationTimeline(content: string): TimelineTuple[] {
+ return [
+ ...supersededInlineCitationEntries(content, { skipLine: (line) => bulletLinePattern.test(line) }),
+ ...supersededInlineCitationEntries(content, { skipLine: isDatedTimelineLine }),
+ ];
+}
+
+/**
+ * The detail an extractor itself writes for a citation row: none (file
+ * extraction) or `Source: <source>` (database extraction). Any other detail
+ * was added by someone, so a row carrying it is never retired as an older
+ * reading (#6226, taste T3): timelineKey ignores detail.
+ */
+export function hasExtractorDetail(row: { source: string; detail?: string | null }): boolean {
+ const detail = (row.detail ?? '').replace(/\s+/g, ' ').trim();
+ return detail === '' || detail === `Source: ${row.source}`.replace(/\s+/g, ' ').trim();
+}
+
/**
* Every (date, source, summary) tuple a page text yields under either timeline
* parser: the file-walk parser above and the DB-side parseTimelineEntries.
@@ -129,8 +155,8 @@ export async function retractRemovedTimelineEntries(
opts: { dryRun?: boolean } = {},
): Promise<Array<TimelineTuple & { id: number }>> {
const kept = markdownTimelineKeys(currentText, slug);
- const rows = await engine.executeRaw<TimelineTuple & { id: number }>(
- `SELECT t.id, to_char(t.date, 'YYYY-MM-DD') AS date, t.source, t.summary FROM timeline_entries t
+ const rows = await engine.executeRaw<TimelineTuple & { id: number; detail: string | null }>(
+ `SELECT t.id, to_char(t.date, 'YYYY-MM-DD') AS date, t.source, t.summary, t.detail 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`, [sourceId, slug]);
const extra = rows.filter(row => !kept.has(tupleKey(row)));
@@ -139,10 +165,15 @@ export async function retractRemovedTimelineEntries(
`SELECT DISTINCT v.compiled_truth, v.timeline FROM page_versions v JOIN pages p ON p.id = v.page_id
WHERE p.source_id = $1 AND p.slug = $2`, [sourceId, slug]);
const produced = new Set<string>();
+ // #6226: rows the older citation reading filed for this text or a stored version.
+ const superseded = new Set(supersededCitationTimeline(currentText).map(tupleKey));
for (const version of versions) {
- for (const key of markdownTimelineKeys(`${version.compiled_truth}\n${version.timeline ?? ''}`, slug)) produced.add(key);
+ const text = `${version.compiled_truth}\n${version.timeline ?? ''}`;
+ for (const key of markdownTimelineKeys(text, slug)) produced.add(key);
+ for (const entry of supersededCitationTimeline(text)) superseded.add(tupleKey(entry));
}
- const orphans = extra.filter(row => produced.has(tupleKey(row)));
+ const orphans = extra.filter(row => produced.has(tupleKey(row)) || (superseded.has(tupleKey(row)) && hasExtractorDetail(row)))
+ .map(({ detail: _detail, ...row }) => row);
if (!orphans.length || opts.dryRun) return orphans;
await engine.executeRaw(
`DELETE FROM timeline_entries WHERE id IN (SELECT jsonb_array_elements_text($1::text::jsonb)::int)`,
diff --git a/test/canonical-projection-history.test.ts b/test/canonical-projection-history.test.ts
index 37bc4ef511..c27fb1e1e5 100644
--- a/test/canonical-projection-history.test.ts
+++ b/test/canonical-projection-history.test.ts
@@ -275,10 +275,10 @@ describe('#5567 coordinated writes keep database-only takes', () => {
describe('#5567 writer decision table', () => {
const table: Record<ProjectionWriter, Record<Parameters<typeof timelineRowAction>[1], ReturnType<typeof timelineRowAction>>> = {
- editing: { in_body: 'refresh_detail', drifted: 'delete', removed: 'delete', removed_marked: 'delete', database_only: 'materialize' },
- preserving: { in_body: 'refresh_detail', drifted: 'delete', removed: 'delete', removed_marked: 'materialize', database_only: 'materialize' },
- file: { in_body: 'refresh_detail', drifted: 'delete', removed: 'delete', removed_marked: 'delete', database_only: 'keep' },
- immutable: { in_body: 'refresh_detail', drifted: 'delete', removed: 'delete', removed_marked: 'keep', database_only: 'keep' },
+ editing: { in_body: 'refresh_detail', drifted: 'delete', removed: 'delete', removed_marked: 'delete', superseded: 'delete', superseded_annotated: 'keep', database_only: 'materialize' },
+ preserving: { in_body: 'refresh_detail', drifted: 'delete', removed: 'delete', removed_marked: 'materialize', superseded: 'delete', superseded_annotated: 'keep', database_only: 'materialize' },
+ file: { in_body: 'refresh_detail', drifted: 'delete', removed: 'delete', removed_marked: 'delete', superseded: 'delete', superseded_annotated: 'keep', database_only: 'keep' },
+ immutable: { in_body: 'refresh_detail', drifted: 'delete', removed: 'delete', removed_marked: 'keep', superseded: 'delete', superseded_annotated: 'keep', database_only: 'keep' },
};
for (const [writer, rows] of Object.entries(table) as Array<[ProjectionWriter, (typeof table)[ProjectionWriter]]>) {
for (const [state, action] of Object.entries(rows) as Array<[Parameters<typeof timelineRowAction>[1], ReturnType<typeof timelineRowAction>]>) {
diff --git a/test/timeline-citations.test.ts b/test/timeline-citations.test.ts
index 2102d510cd..f7496dea2a 100644
--- a/test/timeline-citations.test.ts
+++ b/test/timeline-citations.test.ts
@@ -1,6 +1,9 @@
/** #6184: an HTML comment next to an inline citation is markup, never a timeline summary. */
import { describe, expect, test } from 'bun:test';
-import { parseInlineCitationTimelineEntries, stripHtmlComments } from '../src/core/timeline-citations.ts';
+import { parseInlineCitationTimelineEntries, stripHtmlComments, supersededInlineCitationEntries } from '../src/core/timeline-citations.ts';
+import { parseTimelineEntries } from '../src/core/link-extraction.ts';
+import { extractTimelineFromContent, hasExtractorDetail, retractRemovedTimelineEntries } from '../src/core/timeline-extract.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { renderMaterializedBullet } from '../src/core/persistence/canonical-projections.ts';
describe('#6184 inline-citation timeline parsing', () => {
@@ -61,3 +64,78 @@ describe('#6184 comment handling stays linear (security review: a remote put_pag
.toEqual([{ date: '2026-10-04', source: 'Slack import', summary: 'Met alice-example.' }]);
});
});
+
+describe('#6226 multi-source citations and emphasis', () => {
+ const cases: Array<[string, string, Array<{ date: string; source: string; summary: string }>]> = [
+ ['two sources, two dates', '- **Widget-co:** per Alice, builds widgets. [Source: meeting transcript, 2026-10-06; Gmail "Intro", 2026-09-28]', [
+ { date: '2026-10-06', source: 'meeting transcript', summary: 'Widget-co: per Alice, builds widgets.' },
+ { date: '2026-09-28', source: 'Gmail "Intro"', summary: 'Widget-co: per Alice, builds widgets.' }]],
+ ['a ; before any date stays inside one source', 'Agreed terms. [Source: call; follow-up email, 2026-05-10]', [
+ { date: '2026-05-10', source: 'call; follow-up email', summary: 'Agreed terms.' }]],
+ ['an invalid date drops only its own source', 'Signed. [Source: memo, 2026-02-30; board deck, 2026-03-01]', [
+ { date: '2026-03-01', source: 'board deck', summary: 'Signed.' }]],
+ ['an empty source is dropped, its siblings kept', 'Met. [Source: , 2026-04-01; notes, 2026-04-02]', [
+ { date: '2026-04-02', source: 'notes', summary: 'Met.' }]],
+ ['the same source and date twice files once', 'Met. [Source: notes, 2026-04-02; notes, 2026-04-02]', [
+ { date: '2026-04-02', source: 'notes', summary: 'Met.' }]],
+ ['underscore, star and nested emphasis unwrap', '__Label:__ an *important* **note (*really*)** here [Source: call, 2026-01-02]', [
+ { date: '2026-01-02', source: 'call', summary: 'Label: an important note (really) here' }]],
+ ['snake_case, a*b*c and spaced stars are not emphasis', 'Set max_retry_count and a*b*c; 2 * 3 * 4 [Source: call, 2026-01-02]', [
+ { date: '2026-01-02', source: 'call', summary: 'Set max_retry_count and a*b*c; 2 * 3 * 4' }]],
+ ['a single-source citation is unchanged', 'Shipped the beta. [Source: Slack import, 2026-10-05]', [
+ { date: '2026-10-05', source: 'Slack import', summary: 'Shipped the beta.' }]],
+ ];
+ for (const [name, text, expected] of cases) {
+ test(name, () => {
+ expect(parseInlineCitationTimelineEntries(text)).toEqual(expected);
+ expect(parseTimelineEntries(text).map(e => ({ date: e.date, source: e.source, summary: e.summary }))).toEqual(expected);
+ expect(extractTimelineFromContent(text, 'notes/x').map(e => ({ date: e.date, source: e.source, summary: e.summary }))).toEqual(expected);
+ });
+ }
+
+ test('emphasis unwrapping stays linear on adversarial input', () => {
+ const inputs = ['**a'.repeat(50_000), '*x '.repeat(50_000), '__a_'.repeat(50_000), '_'.repeat(150_000)];
+ for (const input of inputs) {
+ const started = performance.now();
+ parseInlineCitationTimelineEntries(`${input} [Source: s, 2026-01-02]`);
+ expect(performance.now() - started).toBeLessThan(1_000);
+ }
+ });
+
+ test('the older reading of a citation is reported only where the current reading replaces it', () => {
+ expect(supersededInlineCitationEntries('- **Widget-co:** per Alice. [Source: meeting transcript, 2026-10-06; Gmail "Intro", 2026-09-28]'))
+ .toEqual([{ date: '2026-09-28', source: 'meeting transcript, 2026-10-06; Gmail "Intro"', summary: 'Widget-co:** per Alice.' }]);
+ expect(supersededInlineCitationEntries('Shipped the beta. [Source: Slack import, 2026-10-05]')).toEqual([]);
+ });
+
+ test('extractor-written detail is empty or names the source; anything else is someone\'s own', () => {
+ expect(hasExtractorDetail({ source: 'call', detail: '' })).toBe(true);
+ expect(hasExtractorDetail({ source: 'call', detail: 'Source: call' })).toBe(true);
+ expect(hasExtractorDetail({ source: 'call', detail: 'confirmed by phone' })).toBe(false);
+ });
+});
+
+describe('#6226 timeline retraction retires the older reading on unmanaged brains', () => {
+ const text = '- **Widget-co:** per Alice. [Source: meeting transcript, 2026-10-06; Gmail "Intro", 2026-09-28]';
+ const old = { date: '2026-09-28', source: 'meeting transcript, 2026-10-06; Gmail "Intro"', summary: 'Widget-co:** per Alice.' };
+ const retract = async (detail: string) => {
+ const engine = new PGLiteEngine();
+ await engine.connect({}); await engine.initSchema();
+ try {
+ await engine.putPage('people/alice-example', { type: 'person', title: 'Alice', compiled_truth: text, timeline: '' });
+ await engine.addTimelineEntry('people/alice-example', { ...old, detail });
+ await engine.addTimelineEntry('people/alice-example', { date: '2026-10-06', source: 'meeting transcript', summary: 'Widget-co: per Alice.', detail: 'Source: meeting transcript' });
+ const retired = await retractRemovedTimelineEntries(engine, 'people/alice-example', 'default', text);
+ const left = await engine.executeRaw<{ source: string }>('SELECT source FROM timeline_entries ORDER BY source');
+ return { retired: retired.map(r => r.source), left: left.map(r => r.source) };
+ } finally { await engine.disconnect(); }
+ };
+
+ test('an old row with extractor detail is retracted; the current row stays', async () => {
+ expect(await retract(`Source: ${old.source}`)).toEqual({ retired: [old.source], left: ['meeting transcript'] });
+ }, 60_000);
+
+ test('an old row someone gave its own detail stays (T3)', async () => {
+ expect(await retract('confirmed by phone')).toEqual({ retired: [], left: ['meeting transcript', old.source] });
+ }, 60_000);
+});
diff --git a/test/timeline-materialize.test.ts b/test/timeline-materialize.test.ts
index 69baf37f77..b6dcdb96fc 100644
--- a/test/timeline-materialize.test.ts
+++ b/test/timeline-materialize.test.ts
@@ -321,3 +321,63 @@ describe('#5567 marker parsing', () => {
expect(renderMaterializedBullet({ date: '2026-07-01', source: 'notes', summary: 'x', detail: '**2026-07-02** | nested' }, slug)).toBeNull();
});
});
+
+describe('#6226 rows the older citation reading stored', () => {
+ const cited = '- **Widget-co:** per Alice, builds widgets. [Source: meeting transcript, 2026-10-06; Gmail "Intro", 2026-09-28]';
+ const oldSource = 'meeting transcript, 2026-10-06; Gmail "Intro"';
+ const oldRow = { date: '2026-09-28', source: oldSource, summary: 'Widget-co:** per Alice, builds widgets.' };
+ const current = [
+ { date: '2026-09-28', source: 'Gmail "Intro"', summary: 'Widget-co: per Alice, builds widgets.', detail: 'Source: Gmail "Intro"' },
+ { date: '2026-10-06', source: 'meeting transcript', summary: 'Widget-co: per Alice, builds widgets.', detail: 'Source: meeting transcript' },
+ ];
+
+ test('an editing write retires the old multi-source row instead of writing it back into the page', async () => {
+ await fixture(async f => {
+ await f.put(slug, page(cited));
+ await f.legacy(slug, { ...oldRow, detail: `Source: ${oldSource}` });
+ await f.put(slug, page(`${cited}\n\nA later edit.`), { expected_revision: await f.revision(slug) });
+ expect(await f.body(slug)).not.toContain('gbrain:materialized');
+ expect(f.file(slug)).not.toContain(`| ${oldSource} —`);
+ expect(await f.timeline(slug)).toEqual(current);
+ });
+ });
+
+ test('a file-extracted old row (no detail) is retired too', async () => {
+ await fixture(async f => {
+ await f.put(slug, page(cited));
+ await f.legacy(slug, oldRow);
+ await f.put(slug, page(`${cited}\n\nA later edit.`), { expected_revision: await f.revision(slug) });
+ expect(await f.timeline(slug)).toEqual(current);
+ });
+ });
+
+ test('a row sharing the old tuple but carrying its own detail stays in the database and is never materialized (T3)', async () => {
+ await fixture(async f => {
+ await f.put(slug, page(cited));
+ await f.legacy(slug, { ...oldRow, detail: 'confirmed by phone' });
+ await f.put(slug, page(`${cited}\n\nA later edit.`), { expected_revision: await f.revision(slug) });
+ expect(await f.body(slug)).not.toContain('gbrain:materialized');
+ expect(await f.timeline(slug)).toEqual([{ ...oldRow, detail: 'confirmed by phone' }, ...current]
+ .sort((a, b) => a.date.localeCompare(b.date) || a.summary.localeCompare(b.summary)));
+ });
+ });
+
+ test('a preserving write that omits the Timeline section still retires the old row and never renders it', async () => {
+ await fixture(async f => {
+ await f.put(slug, page(cited, '- **2026-08-01** | markdown — Launch review'));
+ await f.legacy(slug, { ...oldRow, detail: `Source: ${oldSource}` });
+ await f.put(slug, page(`${cited}\n\nA later edit.`), { force: true });
+ expect(await f.body(slug)).not.toContain(`| ${oldSource} —`);
+ expect((await f.timeline(slug)).some(row => row.source === oldSource)).toBe(false);
+ });
+ });
+
+ test('a database-only row the citation text never produced is still materialized', async () => {
+ await fixture(async f => {
+ await f.put(slug, page(cited));
+ await f.legacy(slug, { date: '2026-10-06', source: 'meeting transcript', summary: 'Signed the pilot' });
+ await f.put(slug, page(`${cited}\n\nA later edit.`), { expected_revision: await f.revision(slug) });
+ expect(await f.body(slug)).toContain('- **2026-10-06** | meeting transcript — Signed the pilot');
+ });
+ });
+});