Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
attribution: route timeline extraction writers through maintenanceTransaction
garrytana841a93ee5e3
diff --git a/docs/architecture/system-of-record.md b/docs/architecture/system-of-record.mdindex b26c38f82f..734bed20b3 100644--- a/docs/architecture/system-of-record.md+++ b/docs/architecture/system-of-record.md@@ -207,6 +207,7 @@ Attributed (inside a request, a coordinated scope or `maintenanceTransaction`,or a physical projection that leaves attribution untouched):<!-- write-attribution-covered:start -->+- `src/commands/extract-timeline-db.ts` (2): `gbrain extract timeline --source db` commits one `maintenanceTransaction` per 100-row batch on unmanaged brains; managed brains publish per page through a maintenance request.- `src/commands/migrate-engine.ts` (5): engine copy keeps the source rows' attribution values verbatim.- `src/commands/sync/holds.ts` (1): a full sync's move of a held rename (`updateSlug` and its `source_path`) runs in one `maintenanceTransaction`; managed sources publish renames through the sync request preparer.- `src/commands/sync/renames.ts` (1): the legacy sync rename (`updateSlug`) runs in `maintenanceTransaction`; managed sources publish renames through the sync request preparer.@@ -239,6 +240,9 @@ or a physical projection that leaves attribution untouched):- `src/core/persistence/takes-prepare.ts` (3): takes request preparer.- `src/core/repair/frontmatter.ts` (1): a `managed_file_repair` request on managed sources; the unmanaged rename runs in `maintenanceTransaction`.- `src/core/repair/stale-atoms.ts` (3): a request on managed brains; the unmanaged retirement runs in `maintenanceTransaction`.+- `src/core/sweep.ts` (1): the maintenance sweep's bounded timeline batch runs in `maintenanceTransaction`.+- `src/core/timeline-dedup-repair.ts` (1): the legacy timeline source repair rewrites each page's rows in one `maintenanceTransaction`.+- `src/core/timeline-write-through.ts` (2): the timeline write-through's page row splice and entry insert run in one `maintenanceTransaction`.<!-- write-attribution-covered:end -->Unattributed until Foundations 2 mutation attribution (on unmanaged brains@@ -246,7 +250,6 @@ these write with `NULL` attribution):<!-- write-attribution-unattributed:start -->- `src/commands/extract-conversation-facts.ts` (3): the conversation fact index calls the engine directly through `writeDerivedFacts`.-- `src/commands/extract-timeline-db.ts` (2): `gbrain extract timeline --source db` batch insert.- `src/commands/extract.ts` (4): `gbrain extract` timeline walks (file, incremental, stale) and the per-entry fallback.- `src/core/calibration/undo-wave.ts` (1): calibration wave undo of take resolutions.- `src/core/company-brain/profile.ts` (1): company-brain sync soft deletes.@@ -276,11 +279,8 @@ these write with `NULL` attribution):- `src/core/schema-pack/page-to-link.ts` (1): page-to-link conversion soft delete.- `src/core/schema-pack/retype.ts` (1): schema-pack retype.- `src/core/schema-pack/sync.ts` (1): schema-pack type sync.-- `src/core/sweep.ts` (1): sweep timeline batch.- `src/core/takes-write.ts` (7): legacy takes file helper mirror rows and resolutions.- `src/core/think/index.ts` (1): saved `think` result page.-- `src/core/timeline-dedup-repair.ts` (1): timeline dedup repair.-- `src/core/timeline-write-through.ts` (2): timeline write-through entry and page timeline.<!-- write-attribution-unattributed:end -->## The privacy boundarydiff --git a/src/commands/extract-timeline-db.ts b/src/commands/extract-timeline-db.tsindex 1584d71c0a..d8d28f5165 100644--- a/src/commands/extract-timeline-db.ts+++ b/src/commands/extract-timeline-db.ts@@ -21,6 +21,7 @@ import type { Page, PageType } from '../core/types.ts';import { parseTimelineEntries, deriveTimelineAnchor } from '../core/link-extraction.ts';import { retractRemovedTimelineEntries } from '../core/timeline-extract.ts';import { managedPersistenceEnabled } from '../core/persistence/ownership.ts';+import { maintenanceTransaction } from '../core/persistence/attribution.ts';import { unrecordedCanonicalTimeline } from '../core/persistence/canonical-projections.ts';import { maintenancePreflight, submitDatabaseMaintenanceIntent, type MaintenanceAuthority } from '../core/persistence/prepared-maintenance.ts';import { authorizeWrite } from '../core/persistence/authority.ts';@@ -119,7 +120,7 @@ export async function extractTimelineFromDB(engine: BrainEngine, opts: TimelineDconst snapshot = batch.slice();batch.length = 0;try {- result.created += await engine.addTimelineEntriesBatch(snapshot, { auditSite: 'extract.timeline_db' });+ result.created += await maintenanceTransaction(engine, tx => tx.addTimelineEntriesBatch(snapshot, { auditSite: 'extract.timeline_db' }));} catch (e) {const code = refusalCode(e);codes.add(code);diff --git a/src/core/sweep.ts b/src/core/sweep.tsindex 01ebe4fee8..096eca31c8 100644--- a/src/core/sweep.ts+++ b/src/core/sweep.ts@@ -49,6 +49,7 @@ import { readdir, readFile, writeFile, rm, stat } from 'node:fs/promises';import type { BrainEngine, LinkBatchInput, TimelineBatchInput } from './engine.ts';import type { FactsBackstopCtx } from './facts/backstop.ts';import type { CapabilityReport } from './capability.ts';+import { maintenanceTransaction } from './persistence/attribution.ts';/** Delay before the serve-startup sweep fires (post-connect settle). */export const STARTUP_SWEEP_DELAY_MS = 3_000;@@ -470,7 +471,7 @@ async function runLinksTimelinePass(// Engine batch primitives self-retry; default auditSite labels apply// (BATCH_AUDIT_SITES is a closed enum owned by retry.ts).if (tlBatch.length > 0) {- report.timelineExtracted += await engine.addTimelineEntriesBatch(tlBatch); // gbrain-allow-direct-insert: same extract-path rationale as addLinksBatch above [CX-P0.3]+ report.timelineExtracted += await maintenanceTransaction(engine, tx => tx.addTimelineEntriesBatch(tlBatch)); // gbrain-allow-direct-insert: same extract-path rationale as addLinksBatch above [CX-P0.3]}// #4196: reconcile removals. The sweep is the ONLY link extraction remotediff --git a/src/core/timeline-dedup-repair.ts b/src/core/timeline-dedup-repair.tsindex 2946e39575..52582095ea 100644--- a/src/core/timeline-dedup-repair.ts+++ b/src/core/timeline-dedup-repair.ts@@ -18,6 +18,7 @@import type { BrainEngine } from './engine.ts';import { parseTimelineEntries, findTimelineSourceDelimiter } from './link-extraction.ts';+import { maintenanceTransaction } from './persistence/attribution.ts';const INDEX_NAME = 'idx_timeline_dedup';// #3737: the dedup tuple keys md5(summary) — the raw summary overflowed the@@ -236,54 +237,56 @@ export async function repairLegacyTimelineSourceRows(list.push({ source: c.source ?? '', summary: c.summary });byDate.set(c.date, list);}- const legacyRows = await engine.executeRaw<{- id: number; date: string; summary: string;- }>(- `SELECT id, to_char(date, 'YYYY-MM-DD') AS date, summary- FROM timeline_entries WHERE page_id = $1 AND source = ''- ORDER BY id`,- [page.id],- );- for (const row of legacyRows) {- const candidates = byDate.get(row.date) ?? [];- let target: { source: string; summary: string } | null = null;- // 1. Verbatim: the new parser emits the same summary under a real- // source label (dash bullets → 'markdown', citations → label).- target = candidates.find(c => c.source !== '' && c.summary === row.summary) ?? null;- // 2. Split: the legacy summary is the UNSPLIT `Source — Summary`- // text of a pipe bullet; the shared delimiter finder must yield- // exactly the candidate's (source, summary) pair.- if (!target) {- const at = findTimelineSourceDelimiter(row.summary);- if (at >= 0) {- const pre = row.summary.slice(0, at).trim();- const post = row.summary.slice(at + 1).trim();- target = candidates.find(c => c.source === pre && c.summary === post) ?? null;+ await maintenanceTransaction(engine, async tx => {+ const legacyRows = await tx.executeRaw<{+ id: number; date: string; summary: string;+ }>(+ `SELECT id, to_char(date, 'YYYY-MM-DD') AS date, summary+ FROM timeline_entries WHERE page_id = $1 AND source = ''+ ORDER BY id`,+ [page.id],+ );+ for (const row of legacyRows) {+ const candidates = byDate.get(row.date) ?? [];+ let target: { source: string; summary: string } | null = null;+ // 1. Verbatim: the new parser emits the same summary under a real+ // source label (dash bullets → 'markdown', citations → label).+ target = candidates.find(c => c.source !== '' && c.summary === row.summary) ?? null;+ // 2. Split: the legacy summary is the UNSPLIT `Source — Summary`+ // text of a pipe bullet; the shared delimiter finder must yield+ // exactly the candidate's (source, summary) pair.+ if (!target) {+ const at = findTimelineSourceDelimiter(row.summary);+ if (at >= 0) {+ const pre = row.summary.slice(0, at).trim();+ const post = row.summary.slice(at + 1).trim();+ target = candidates.find(c => c.source === pre && c.summary === post) ?? null;+ }}+ if (!target) { result.rowsSkipped++; continue; }+ // A new-shape duplicate may already exist (re-extract ran before this+ // repair): drop the legacy row instead of colliding with the unique+ // (page_id, date, md5(summary), source) index on UPDATE.+ const del = await tx.executeRaw<{ id: number }>(+ `DELETE FROM timeline_entries t+ WHERE t.id = $1+ AND EXISTS (+ SELECT 1 FROM timeline_entries x+ WHERE x.page_id = t.page_id AND x.date = t.date+ AND md5(x.summary) = md5($2) AND x.source = $3 AND x.id <> t.id+ )+ RETURNING t.id`,+ [row.id, target.summary, target.source],+ );+ if (del.length > 0) { result.rowsDeleted++; continue; }+ await tx.executeRaw(+ `UPDATE timeline_entries SET source = $2, summary = $3+ WHERE id = $1 AND source = ''`,+ [row.id, target.source, target.summary],+ );+ result.rowsRewritten++;}- if (!target) { result.rowsSkipped++; continue; }- // A new-shape duplicate may already exist (re-extract ran before this- // repair): drop the legacy row instead of colliding with the unique- // (page_id, date, md5(summary), source) index on UPDATE.- const del = await engine.executeRaw<{ id: number }>(- `DELETE FROM timeline_entries t- WHERE t.id = $1- AND EXISTS (- SELECT 1 FROM timeline_entries x- WHERE x.page_id = t.page_id AND x.date = t.date- AND md5(x.summary) = md5($2) AND x.source = $3 AND x.id <> t.id- )- RETURNING t.id`,- [row.id, target.summary, target.source],- );- if (del.length > 0) { result.rowsDeleted++; continue; }- await engine.executeRaw(- `UPDATE timeline_entries SET source = $2, summary = $3- WHERE id = $1 AND source = ''`,- [row.id, target.source, target.summary],- );- result.rowsRewritten++;- }+ });}}return result;diff --git a/src/core/timeline-write-through.ts b/src/core/timeline-write-through.tsindex ef6e034d0b..ff5ee7194b 100644--- a/src/core/timeline-write-through.ts+++ b/src/core/timeline-write-through.ts@@ -57,6 +57,7 @@ import {type WriteThroughResult,} from './write-through.ts';import { withPageLock } from './page-lock.ts';+import { maintenanceTransaction } from './persistence/attribution.ts';import { assertSourceFilesystemActive, hasSourceFilesystemLock, withSourceFilesystemLock } from './minions/source-filesystem.ts';import { findTimelineSplitIndex } from './markdown.ts';import { isMaterializedMarkerLine } from './timeline-marker.ts';@@ -389,22 +390,24 @@ export async function writeTimelineEntryThrough(const newTimeline = sanitizeForJsonb(spliceTimelineBlock(page.timeline ?? '', entry.date, rendered.block),);- await engine.executeRaw(- `UPDATE pages SET timeline = $1, chunker_version = ${bodyWriteChunkVersion('pages.compiled_truth', '$1')}, updated_at = now()- WHERE slug = $2 AND source_id = $3 AND deleted_at IS NULL`,- [newTimeline, slug, sourceId],- );+ await maintenanceTransaction(engine, async tx => {+ await tx.executeRaw(+ `UPDATE pages SET timeline = $1, chunker_version = ${bodyWriteChunkVersion('pages.compiled_truth', '$1')}, updated_at = now()+ WHERE slug = $2 AND source_id = $3 AND deleted_at IS NULL`,+ [newTimeline, slug, sourceId],+ );- // Store the tuple the FS extractor recovers from the bullet just- // spliced in, so every later sync/rebuild re-extraction- // conflicts-no-ops instead of duplicating (#1856's dedup-tuple- // divergence).- await engine.addTimelineEntry(slug, { // gbrain-allow-direct-insert: timeline write-through — the canonical markdown gains the same entry in this call, and the stored tuple is derived from the rendered bullet so sync/extract reconciliation dedups against it- date: rendered.canonical.date,- source: rendered.canonical.source,- summary: rendered.canonical.summary,- detail: entry.detail || '',- }, { sourceId, skipExistenceCheck: true });+ // Store the tuple the FS extractor recovers from the bullet just+ // spliced in, so every later sync/rebuild re-extraction+ // conflicts-no-ops instead of duplicating (#1856's dedup-tuple+ // divergence).+ await tx.addTimelineEntry(slug, { // gbrain-allow-direct-insert: timeline write-through — the canonical markdown gains the same entry in this call, and the stored tuple is derived from the rendered bullet so sync/extract reconciliation dedups against it+ date: rendered.canonical.date,+ source: rendered.canonical.source,+ summary: rendered.canonical.summary,+ detail: entry.detail || '',+ }, { sourceId, skipExistenceCheck: true });+ });// #2426 mirror (writePageThrough): on a durability-hardened repo,// commit the artifact so it reaches git. Best-effort — a commitdiff --git a/test/e2e/write-attribution-postgres.test.ts b/test/e2e/write-attribution-postgres.test.tsindex ed6101d00b..6f2976c122 100644--- a/test/e2e/write-attribution-postgres.test.ts+++ b/test/e2e/write-attribution-postgres.test.ts@@ -11,6 +11,8 @@ if (hasDatabase()) {await import('../write-attribution-legacy.test.ts');await import('../write-attribution-import.test.ts');await import('../write-attribution-sync.test.ts');+ await import('../write-attribution-timeline.test.ts');+ await import('../write-attribution-timeline-10k.slow.test.ts');} else {test.skip('write attribution on Postgres requires DATABASE_URL', () => {});}diff --git a/test/sweep.test.ts b/test/sweep.test.tsindex 7380c85826..82c2e725ec 100644--- a/test/sweep.test.ts+++ b/test/sweep.test.ts@@ -676,9 +676,10 @@ describe('runMaintenanceSweep — bounded link resolution (no listAllPageRefs)',});expect(r.timelineExtracted).toBe(1);expect(log).not.toContain('listAllPageRefs');- // Exactly two raw queries: the pass-1 fence scan and the pass-2 recency- // scan. No candidates ⇒ no third (ref-lookup) query.- expect(log.filter((m) => m === 'executeRaw').length).toBe(2);+ // Exactly three raw queries: the pass-1 fence scan, the pass-2 recency+ // scan and the maintenance principal lookup the attributed timeline batch+ // makes. No candidates ⇒ no ref-lookup query.+ expect(log.filter((m) => m === 'executeRaw').length).toBe(3);});});diff --git a/test/timeline-write-through.test.ts b/test/timeline-write-through.test.tsindex fbaa026184..525f0615ef 100644--- a/test/timeline-write-through.test.ts+++ b/test/timeline-write-through.test.ts@@ -562,15 +562,20 @@ describe('writeTimelineEntryThrough helper', () => {await engine.setConfig('sync.repo_path', brainDir);const slug = 'notes/helper-throw';await seedPage(slug);- const broken = new Proxy(engine, {+ // The row insert runs on the maintenance transaction's engine, so the fault is injected there too.+ const failing = <T extends object>(base: T): T => new Proxy(base, {get(target, prop, receiver) {if (prop === 'addTimelineEntry') {return async () => { throw new Error('boom'); };}+ if (prop === 'transaction') {+ return (fn: (tx: PGLiteEngine) => Promise<unknown>) => (target as PGLiteEngine).transaction(tx => fn(failing(tx as PGLiteEngine)));+ }const v = Reflect.get(target, prop, receiver);return typeof v === 'function' ? v.bind(target) : v;},- }) as unknown as PGLiteEngine;+ });+ const broken = failing(engine);const out = await writeTimelineEntryThrough(broken, slug, 'default', {date: '2026-07-15',summary: 'x',diff --git a/test/write-attribution-timeline-10k.slow.test.ts b/test/write-attribution-timeline-10k.slow.test.tsnew file mode 100644index 0000000000..1477f55250--- /dev/null+++ b/test/write-attribution-timeline-10k.slow.test.ts@@ -0,0 +1,63 @@+/**+ * Foundations 2 (Lane C) bounded maintenance transactions at scale: on an+ * unmanaged brain with 10k pages, `gbrain extract timeline --source db`+ * commits one maintenanceTransaction per 100-row batch (never one transaction+ * for the run, so no 10k-row transaction holds locks), and every row names+ * the local maintenance principal. Rows of one transaction share+ * `last_written_at` (now() is the transaction start), so grouping by it+ * counts the transactions.+ *+ * Fails if the extraction stops chunking or writes outside+ * maintenanceTransaction. Runs on PGLite (`bun run test:slow`), and on+ * Postgres through test/e2e/write-attribution-postgres.test.ts.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { extractTimelineFromDB } from '../src/commands/extract-timeline-db.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { configureGateway } from '../src/core/ai/gateway.ts';+import { LEGACY_EMBEDDING_CONFIG } from './helpers/legacy-embedding-config.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { unmanagedBrain } from './helpers/unmanaged-attribution.ts';++const engines: BrainEngine[] = [];+let closePostgres: (() => Promise<void>) | undefined;+const quiet = { quiet: true, jsonMode: false } as const;++beforeAll(async () => {+ configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: {} });+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);+ if (process.env.DATABASE_URL) {+ 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); await engine.disconnect(); }+ await closePostgres?.();+});++describe('bounded maintenance transactions at 10k pages', () => {+ test('extract timeline --source db commits 10k pages in bounded per-batch transactions', async () => {+ for (const engine of engines) {+ const brain = await unmanagedBrain(engine);+ const pages = 10_000;+ await engine.executeRaw(`INSERT INTO pages (source_id, slug, type, title, compiled_truth, timeline, frontmatter)+ SELECT $1, 'notes/bulk-' || g, 'note', 'Bulk ' || g, 'A bulk note.', '- **2026-01-01** | test — Bulk event ' || g, '{}'::jsonb+ FROM generate_series(1, $2::int) AS g`, [brain.sourceId, pages]);++ const result = await extractTimelineFromDB(engine, { sourceIdFilter: brain.sourceId, ...quiet });++ expect(result.created).toBe(pages);+ const [summary] = await engine.executeRaw<{ rows: number; attributed: number; transactions: number; largest: number }>(`+ SELECT sum(n)::int AS rows, sum(attributed)::int AS attributed, count(*)::int AS transactions, max(n)::int AS largest FROM (+ SELECT t.last_written_at, count(*) AS n,+ count(*) FILTER (WHERE t.write_principal_kind=$2 AND t.write_principal_id=$3+ AND t.last_write_principal_kind=$2 AND t.last_write_principal_id=$3) AS attributed+ FROM timeline_entries t JOIN pages p ON p.id=t.page_id WHERE p.source_id=$1 GROUP BY t.last_written_at) per_transaction`,+ [brain.sourceId, brain.maintenance.kind, brain.maintenance.id]);+ expect(summary).toEqual({ rows: pages, attributed: pages, transactions: pages / 100, largest: 100 });+ }+ }, 600_000);+});diff --git a/test/write-attribution-timeline.test.ts b/test/write-attribution-timeline.test.tsnew file mode 100644index 0000000000..43d5024dc8--- /dev/null+++ b/test/write-attribution-timeline.test.ts@@ -0,0 +1,128 @@+/**+ * Foundations 2 (Lane C) timeline attribution on an unmanaged brain: the DB+ * timeline extraction batches, the maintenance sweep's timeline batch, the+ * timeline write-through and the legacy timeline source repair write inside+ * maintenanceTransaction, so their rows (and the page revision the+ * write-through advances) name the local maintenance principal. A legacy row+ * the repair rewrites keeps its creator and moves its last writer.+ *+ * Protects the timeline extraction writer family in+ * docs/architecture/system-of-record.md. Fails if extract-timeline-db.ts,+ * sweep.ts, timeline-write-through.ts or timeline-dedup-repair.ts writes+ * outside maintenanceTransaction, Runs on+ * PGLite, and on Postgres (direct and transaction-mode PgBouncer) through+ * test/e2e/write-attribution-postgres.test.ts.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { extractTimelineFromDB } from '../src/commands/extract-timeline-db.ts';+import { runMaintenanceSweep } from '../src/core/sweep.ts';+import { writeTimelineEntryThrough } from '../src/core/timeline-write-through.ts';+import { repairLegacyTimelineSourceRows } from '../src/core/timeline-dedup-repair.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { writePageThrough, _resetWriteThroughCacheForTest } from '../src/core/write-through.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { configureGateway } from '../src/core/ai/gateway.ts';+import { LEGACY_EMBEDDING_CONFIG } from './helpers/legacy-embedding-config.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { CREATOR_ACTOR, asCreator, revisionActor, rowActors, unmanagedBrain, type UnmanagedBrain } from './helpers/unmanaged-attribution.ts';++const engines: BrainEngine[] = [];+const scratch = mkdtempSync(join(tmpdir(), 'gbrain-write-attribution-timeline-'));+let closePostgres: (() => Promise<void>) | undefined;+const TIMELINE = '## Timeline\n\n- **2026-01-02** | test — Met acme-example\n- **2026-02-03** | test — Joined acme-example';+const page = (title: string, body: string) => `---\ntype: note\ntitle: ${title}\n---\n${body}\n`;++beforeAll(async () => {+ configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: {} });+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);+ if (process.env.DATABASE_URL) {+ 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); await engine.disconnect(); }+ await closePostgres?.();+ rmSync(scratch, { recursive: true, force: true });+});++const timelineActors = (brain: UnmanagedBrain, slug: string) => rowActors(brain.engine, 'timeline_entries',+ 'page_id=(SELECT id FROM pages WHERE source_id=$1 AND slug=$2)', [brain.sourceId, slug]);+const both = (actor: UnmanagedBrain['maintenance']) => ({ created: actor, last: actor });+const quiet = { quiet: true, jsonMode: false } as const;++describe('timeline attribution on an unmanaged brain', () => {+ test('extract timeline --source db stamps the rows it inserts', async () => {+ for (const engine of engines) {+ const brain = await unmanagedBrain(engine);+ const slug = 'people/alice-example';+ await asCreator(engine, tx => tx.putPage(slug, { type: 'person', title: 'Alice', compiled_truth: `A person.\n\n${TIMELINE}` }, { sourceId: brain.sourceId }));+ await engine.executeRaw('DELETE FROM timeline_entries WHERE page_id=(SELECT id FROM pages WHERE source_id=$1 AND slug=$2)', [brain.sourceId, slug]);++ const result = await extractTimelineFromDB(engine, { sourceIdFilter: brain.sourceId, ...quiet });++ expect(result.created).toBe(2);+ expect((await timelineActors(brain, slug)).map(({ created, last }) => ({ created, last }))).toEqual([both(brain.maintenance), both(brain.maintenance)]);+ }+ }, 120_000);++ test('the maintenance sweep stamps its timeline batch', async () => {+ for (const engine of engines) {+ const brain = await unmanagedBrain(engine);+ await engine.setConfig('auto_link', 'false');+ const slug = 'people/bob-example';+ await asCreator(engine, tx => tx.putPage(slug, { type: 'person', title: 'Bob', compiled_truth: `A person.\n\n${TIMELINE}` }, { sourceId: brain.sourceId }));+ await engine.executeRaw('DELETE FROM timeline_entries WHERE page_id=(SELECT id FROM pages WHERE source_id=$1 AND slug=$2)', [brain.sourceId, slug]);++ const report = await runMaintenanceSweep(engine, { sourceId: brain.sourceId, budgetMs: 60_000 });++ expect(report.timelineExtracted).toBe(2);+ expect((await timelineActors(brain, slug)).map(({ created, last }) => ({ created, last }))).toEqual([both(brain.maintenance), both(brain.maintenance)]);+ await engine.setConfig('auto_link', 'true');+ }+ }, 120_000);++ test('a timeline write-through stamps the page revision it advances and the row it inserts', async () => {+ for (const engine of engines) {+ const brain = await unmanagedBrain(engine);+ const root = join(scratch, brain.sourceId);+ mkdirSync(root, { recursive: true });+ await engine.executeRaw('UPDATE sources SET local_path=$2 WHERE id=$1', [brain.sourceId, root]);+ _resetWriteThroughCacheForTest();+ const slug = 'notes/acme-example';+ await importFromContent(engine, slug, page('Acme', 'An example company.'), { sourceId: brain.sourceId, sourcePath: `${slug}.md`, noEmbed: true });+ const written = await writePageThrough(engine, slug, { sourceId: brain.sourceId });+ await engine.executeRaw(`UPDATE pages SET revision_principal_kind=NULL, revision_principal_id=NULL WHERE source_id=$1 AND slug=$2`, [brain.sourceId, slug]);++ const outcome = await writeTimelineEntryThrough(engine, slug, brain.sourceId, { date: '2026-07-15', summary: 'Signed the example contract' });++ expect(outcome.handled).toBe(true);+ expect(readFileSync(written.path!, 'utf8')).toContain('Signed the example contract');+ expect(await revisionActor(engine, brain.sourceId, slug)).toEqual(brain.maintenance);+ expect((await timelineActors(brain, slug)).map(({ created, last }) => ({ created, last }))).toEqual([both(brain.maintenance)]);+ }+ }, 120_000);++ test('the legacy timeline source repair keeps the creator of a row it rewrites and moves its last writer', async () => {+ for (const engine of engines) {+ const brain = await unmanagedBrain(engine);+ const slug = 'people/charlie-example';+ const stored = await asCreator(engine, tx => tx.putPage(slug, { type: 'person', title: 'Charlie',+ compiled_truth: 'A person.\n\n## Timeline\n\n- **2026-03-04** | Visited acme-example' }, { sourceId: brain.sourceId }));+ await engine.executeRaw('DELETE FROM timeline_entries WHERE page_id=$1', [stored.id]);+ await asCreator(engine, tx => tx.executeRaw(`INSERT INTO timeline_entries (page_id, date, source, summary, detail)+ VALUES ($1, '2026-03-04', '', 'Visited acme-example', '')`, [stored.id]));++ const result = await repairLegacyTimelineSourceRows(engine);++ expect(result.rowsRewritten).toBeGreaterThanOrEqual(1);+ expect((await timelineActors(brain, slug)).map(({ created, last }) => ({ created, last })))+ .toEqual([{ created: CREATOR_ACTOR, last: brain.maintenance }]);+ }+ }, 120_000);+});