Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
attribution: route sync rename writers through maintenanceTransaction
garrytan09a517731326
diff --git a/docs/architecture/system-of-record.md b/docs/architecture/system-of-record.mdindex 712bcfb655..b26c38f82f 100644--- a/docs/architecture/system-of-record.md+++ b/docs/architecture/system-of-record.md@@ -208,6 +208,8 @@ or a physical projection that leaves attribution untouched):<!-- write-attribution-covered:start -->- `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.- `src/core/chronicle/publish.ts` (3): Life Chronicle event generations: maintenance requests on managed brains; the unmanaged event write, retirement soft delete and retired stamp run in `maintenanceTransaction`.- `src/core/cycle/extract-takes.ts` (2): coordinated per page on managed brains; the unmanaged batch upsert runs in `maintenanceTransaction`.- `src/core/embed-facts.ts` (1): embedding columns only (physical projection).@@ -216,6 +218,7 @@ or a physical projection that leaves attribution untouched):- `src/core/facts/withdrawal.ts` (1): runs inside the `forget` request's coordinated write.- `src/core/import-file.ts` (11): direct markdown, code and image imports, the moved-file rename (`updateSlug`) and the #3694 legacy-hash re-stamp run in `maintenanceTransaction`; managed imports go through the page request preparer.- `src/core/page-state/materialize.ts` (1): coordinated maintenance.+- `src/core/page-state/rename-alias.ts` (2): the fact slug rewrite runs inside its caller's `updateSlug` transaction, and every caller is attributed.- `src/core/page-state/versions.ts` (1): `createVersion` itself; the caller's scope supplies the actor.- `src/core/persistence/atom-maintenance.ts` (1): request preparer.- `src/core/persistence/canonical-projections.ts` (7): fence projection inside the request's publication.@@ -245,8 +248,6 @@ these write with `NULL` attribution):- `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/commands/sync/holds.ts` (1): legacy full sync moves a held rename's page once its file screens clean (`updateSlug`).-- `src/commands/sync/renames.ts` (1): legacy sync rename (`updateSlug`).- `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.- `src/core/cycle/dream-provenance.ts` (1): dream provenance frontmatter stamp.@@ -269,7 +270,6 @@ these write with `NULL` attribution):- `src/core/minions/handlers/ingest-capture.ts` (1): capture ingest soft delete.- `src/core/ops/extraction.ts` (2): extraction review promote (frontmatter) and reject (soft delete).- `src/core/output/writer.ts` (4): synthesize-phase BrainWriter pages and timeline.-- `src/core/page-state/rename-alias.ts` (2): fact slug rewrite on rename.- `src/core/repair/captured-facts.ts` (1): unmanaged captured-facts expiry.- `src/core/repair/extractor-facts.ts` (1): extractor-facts repair update.- `src/core/schema-pack/page-to-alias.ts` (1): page-to-alias conversion soft delete.diff --git a/src/commands/sync/holds.ts b/src/commands/sync/holds.tsindex ab565a7fcf..261f75cf5e 100644--- a/src/commands/sync/holds.ts+++ b/src/commands/sync/holds.ts@@ -20,6 +20,7 @@ import { MAX_FILE_SIZE, contentRefusalFromReceipt, isContentRefusal, type Contenimport { slugConflictHoldMessage, type ImportResult } from '../../core/import-file.ts';import { classifyImportHold, parseMarkdown } from '../../core/markdown.ts';import { readSourceFileSync } from '../../core/minions/source-filesystem.ts';+import { maintenanceTransaction } from '../../core/persistence/attribution.ts';import type { SyncRename } from '../../core/persistence/sync-discovery.ts';import {addRecovered, buildHoldReport, clearGitHold, clearGitHoldRetryPaths, gitHoldItem, readGitHoldRetryPaths, readGitSourceHolds,@@ -339,8 +340,10 @@ export async function moveHeldRenames(engine: BrainEngine, holds: LegacyHolds |continue;}try {- if (await engine.updateSlug(origin.slug, resolveSlugForPath(record.path), { sourceId: holds.sourceId }) === 0) continue;- await engine.executeRaw('UPDATE pages SET source_path=$1 WHERE id=$2 AND source_id=$3', [record.path, origin.pageId, holds.sourceId]);+ await maintenanceTransaction(engine, async tx => {+ if (await tx.updateSlug(origin.slug, resolveSlugForPath(record.path), { sourceId: holds.sourceId }) === 0) return;+ await tx.executeRaw('UPDATE pages SET source_path=$1 WHERE id=$2 AND source_id=$3', [record.path, origin.pageId, holds.sourceId]);+ });} catch { /* the walk imports the file as an ordinary add; the old page stays until a full walk proves it gone */ }}}diff --git a/src/commands/sync/renames.ts b/src/commands/sync/renames.tsindex cd52251c2c..a24e568cb6 100644--- a/src/commands/sync/renames.ts+++ b/src/commands/sync/renames.ts@@ -9,6 +9,7 @@ import { softDeleteSyncPages } from '../../core/company-brain/profile.ts';import { serr } from '../../core/console-prefix.ts';import { DELETE_BATCH_SIZE } from '../../core/engine-constants.ts';import { importFile, isImageFilePath as isImageImportPath, importImageFile } from '../../core/import-file.ts';+import { maintenanceTransaction } from '../../core/persistence/attribution.ts';import {resolveSlugsForRemovedPaths,refusedRemovedPathMessage,@@ -245,7 +246,7 @@ async function applyRename(let renameApplied = false;if (oldSlug !== undefined) {try {- renameApplied = (await engine.updateSlug(oldSlug, newSlug, renameOpts)) > 0;+ renameApplied = (await maintenanceTransaction(engine, tx => tx.updateSlug(oldSlug, newSlug, renameOpts))) > 0;} catch {// Destination slug occupied or invalid — treat as add; the// reconcile below removes the stale old row once the destinationdiff --git a/test/e2e/write-attribution-postgres.test.ts b/test/e2e/write-attribution-postgres.test.tsindex 78e02eec2f..ed6101d00b 100644--- a/test/e2e/write-attribution-postgres.test.ts+++ b/test/e2e/write-attribution-postgres.test.ts@@ -10,6 +10,7 @@ if (hasDatabase()) {await import('../write-attribution.test.ts');await import('../write-attribution-legacy.test.ts');await import('../write-attribution-import.test.ts');+ await import('../write-attribution-sync.test.ts');} else {test.skip('write attribution on Postgres requires DATABASE_URL', () => {});}diff --git a/test/write-attribution-sync.test.ts b/test/write-attribution-sync.test.tsnew file mode 100644index 0000000000..92fe9c3699--- /dev/null+++ b/test/write-attribution-sync.test.ts@@ -0,0 +1,111 @@+/**+ * Foundations 2 (Lane C) sync rename attribution on an unmanaged brain: the+ * legacy sync's cheap rename and a full sync's move of a held rename advance+ * the page revision (the slug changes) inside maintenanceTransaction, so the+ * moved page names the local maintenance principal instead of `unrecorded`.+ * The facts that follow the page (`moveSlugBindings`) keep their creator and+ * move their last writer.+ *+ * Protects the sync rename writer family in docs/architecture/system-of-record.md.+ * Fails if `src/commands/sync/renames.ts` or `src/commands/sync/holds.ts`+ * renames 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 { execFileSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } 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 { performSync } from '../src/commands/sync.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 { makeGitFixture } from './helpers/git-fixture.ts';+import { withEnv } from './helpers/with-env.ts';+import { CREATOR_ACTOR, asCreator, revisionActor, rowActors, unmanagedBrain, type UnmanagedBrain } from './helpers/unmanaged-attribution.ts';++const engines: BrainEngine[] = [];+const home = mkdtempSync(join(tmpdir(), 'gbrain-write-attribution-sync-'));+const env = { GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home };+let closePostgres: (() => Promise<void>) | undefined;+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8' }).trim();+const BODY = Array.from({ length: 30 }, (_, i) => `Line ${i} of a synthetic note that keeps the rename detectable.`).join('\n');+const NOTE = `---\ntitle: Renamed example\n---\n${BODY}\n`;+const BROKEN = `---\ntitle: alice-example first line\nalice-example second line\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(home, { recursive: true, force: true });+});++async function gitSource(engine: BrainEngine): Promise<UnmanagedBrain & { root: string }> {+ const brain = await unmanagedBrain(engine);+ const root = join(home, brain.sourceId);+ mkdirSync(join(root, 'notes'), { recursive: true }); await makeGitFixture(root);+ await engine.executeRaw("UPDATE sources SET local_path=$2, config='{}' WHERE id=$1", [brain.sourceId, root]);+ return { ...brain, root };+}+function commit(root: string, files: Record<string, string>, message: string): void {+ for (const [path, content] of Object.entries(files)) writeFileSync(join(root, path), content);+ git(root, 'add', '-A'); git(root, 'commit', '-qm', message);+}+// concurrency 1: parallel full-sync workers would connect to the configured database, not this isolated one.+const sync = (brain: UnmanagedBrain & { root: string }, extra: Record<string, unknown> = {}) => performSync(brain.engine,+ { repoPath: brain.root, sourceId: brain.sourceId, noPull: true, noEmbed: true, noExtract: true, concurrency: 1, ...extra });+const pageId = async (engine: BrainEngine, sourceId: string, slug: string) =>+ (await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL', [sourceId, slug]))[0]?.id;++describe('sync rename attribution on an unmanaged brain', () => {+ test('an incremental sync rename moves the page and its facts under the maintenance principal', () => withEnv(env, async () => {+ for (const engine of engines) {+ const brain = await gitSource(engine);+ commit(brain.root, { 'notes/old-example.md': NOTE }, 'add');+ await sync(brain);+ const id = await pageId(engine, brain.sourceId, 'notes/old-example');+ await asCreator(engine, tx => tx.executeRaw(`INSERT INTO facts (source_id, entity_slug, fact, kind, source)+ VALUES ($1, 'notes/old-example', 'Keeps its creator through a rename', 'fact', 'test')`, [brain.sourceId]));++ git(brain.root, 'mv', 'notes/old-example.md', 'notes/new-example.md');+ git(brain.root, 'commit', '-qm', 'rename');+ await sync(brain);++ expect(await pageId(engine, brain.sourceId, 'notes/new-example')).toBe(id);+ expect(await revisionActor(engine, brain.sourceId, 'notes/new-example')).toEqual(brain.maintenance);+ expect((await rowActors(engine, 'facts', 'source_id=$1', [brain.sourceId])).map(({ created, last }) => ({ created, last })))+ .toEqual([{ created: CREATOR_ACTOR, last: brain.maintenance }]);+ }+ }), 120_000);++ test('a full sync moves a held rename once its file screens clean under the maintenance principal', () => withEnv(env, async () => {+ for (const engine of engines) {+ const brain = await gitSource(engine);+ commit(brain.root, { 'notes/held-old.md': NOTE }, 'add');+ await sync(brain);+ const id = await pageId(engine, brain.sourceId, 'notes/held-old');+ git(brain.root, 'mv', 'notes/held-old.md', 'notes/held-new.md');+ commit(brain.root, { 'notes/held-new.md': BROKEN }, 'rename onto a broken file');+ await sync(brain);+ expect(await pageId(engine, brain.sourceId, 'notes/held-new')).toBeUndefined();++ writeFileSync(join(brain.root, 'notes/held-new.md'), NOTE);+ git(brain.root, 'add', '-A'); git(brain.root, 'commit', '-qm', 'fix the renamed file');+ await sync(brain, { full: true });++ expect(await pageId(engine, brain.sourceId, 'notes/held-new')).toBe(id);+ expect(await revisionActor(engine, brain.sourceId, 'notes/held-new')).toEqual(brain.maintenance);+ }+ }), 120_000);+});