Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
attribution: leave the v139 timeline source repair unrouted; inject the fence mirror fault inside the transaction
garrytan88f58f9d1539
diff --git a/docs/architecture/system-of-record.md b/docs/architecture/system-of-record.mdindex 70f0f17664..df222e3f37 100644--- a/docs/architecture/system-of-record.md+++ b/docs/architecture/system-of-record.md@@ -275,7 +275,7 @@ or a physical projection that leaves attribution untouched):- `src/core/sweep.ts` (1): the maintenance sweep's bounded timeline batch runs in `maintenanceTransaction`.- `src/core/takes-write.ts` (7): the takes file helpers' DB mirror (add, append, update, supersede, resolve and its self-heal) runs in `maintenanceTransaction`; managed brains publish through the takes request preparer.- `src/core/think/index.ts` (1): the saved `think` result page 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-dedup-repair.ts` (1): runs only from schema migration v139, before migration v193 adds the attribution columns, so it has no actor to record.- `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 -->diff --git a/src/core/timeline-dedup-repair.ts b/src/core/timeline-dedup-repair.tsindex 52582095ea..2946e39575 100644--- a/src/core/timeline-dedup-repair.ts+++ b/src/core/timeline-dedup-repair.ts@@ -18,7 +18,6 @@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@@ -237,56 +236,54 @@ export async function repairLegacyTimelineSourceRows(list.push({ source: c.source ?? '', summary: c.summary });byDate.set(c.date, list);}- 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;- }+ 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;}- 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/test/facts-write-path-failures.test.ts b/test/facts-write-path-failures.test.tsindex b599e41eb1..463c7286dc 100644--- a/test/facts-write-path-failures.test.ts+++ b/test/facts-write-path-failures.test.ts@@ -92,13 +92,16 @@ describe('facts write-path failures (B-21)', () => {test('a failed page-cache mirror after a fence write is reported', async () => {await importFromContent(engine, 'people/alice-example', '---\ntitle: Alice Example\ntype: person\n---\n# Alice Example\n', { noEmbed: true });- const broken = new Proxy(engine, {+ // The mirror runs on the maintenance transaction's engine, so the fault is injected there too.+ const failing = (base: BrainEngine): BrainEngine => new Proxy(base, {get(target, prop, receiver) {if (prop === 'refreshPageBody') return async () => { throw new Error('mirror write failed'); };+ if (prop === 'transaction') return <T>(fn: (tx: BrainEngine) => Promise<T>) => target.transaction(tx => fn(failing(tx)));const value = Reflect.get(target, prop, receiver);return typeof value === 'function' ? value.bind(target) : value;},- }) as unknown as BrainEngine;+ });+ const broken = failing(engine);const warn = spyOn(console, 'warn').mockImplementation(() => {});try {const result = await writeFactsToFence(broken, { sourceId: 'default', localPath: brainDir, slug: 'people/alice-example', resolutionSource: 'exact_page' }, [input]);diff --git a/test/write-attribution-timeline.test.ts b/test/write-attribution-timeline.test.tsindex 46583976f0..813cc3f2f8 100644--- a/test/write-attribution-timeline.test.ts+++ b/test/write-attribution-timeline.test.ts@@ -1,16 +1,14 @@/*** 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.+ * timeline extraction batches, the maintenance sweep's timeline batch and the+ * timeline write-through write inside maintenanceTransaction, so their rows+ * (and the page revision the write-through advances) name the local+ * maintenance principal.** 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+ * sweep.ts or timeline-write-through.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';@@ -22,14 +20,13 @@ 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';+import { asCreator, revisionActor, rowActors, unmanagedBrain, type UnmanagedBrain } from './helpers/unmanaged-attribution.ts';const engines: BrainEngine[] = [];const scratch = mkdtempSync(join(tmpdir(), 'gbrain-write-attribution-timeline-'));@@ -107,22 +104,4 @@ describe('timeline attribution on an unmanaged brain', () => {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);});