Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

attribution: route the moved-file rename and legacy-hash re-stamp in import through maintenanceTransaction

garrytane72fe4af3d1f
diff --git a/docs/architecture/system-of-record.md b/docs/architecture/system-of-record.md
index 3750c6d9c7..712bcfb655 100644
--- a/docs/architecture/system-of-record.md
+++ b/docs/architecture/system-of-record.md
@@ -214,6 +214,7 @@ or a physical projection that leaves attribution untouched):
- `src/core/embedding-dim-check.ts` (1): embedding columns only (physical projection).
- `src/core/facts/relink-publish.ts` (2): `relink_facts` request preparer.
- `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/versions.ts` (1): `createVersion` itself; the caller's scope supplies the actor.
- `src/core/persistence/atom-maintenance.ts` (1): request preparer.
@@ -265,7 +266,6 @@ these write with `NULL` attribution):
- `src/core/facts/forget.ts` (4): legacy forget expiry and fence strike-through.
- `src/core/facts/proposal-supersede.ts` (4): unmanaged `decide` proposal accept and undo (facts and page body).
- `src/core/facts/write-single.ts` (2): legacy single-fact insert and supersession.
-- `src/core/import-file.ts` (11): remaining sites: the moved-file rename (`updateSlug`) and the #3694 legacy-hash re-stamp of an unchanged body. Direct import writes are attributed.
- `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.
diff --git a/src/core/import-file.ts b/src/core/import-file.ts
index b15c1ac1be..f098f3864e 100644
--- a/src/core/import-file.ts
+++ b/src/core/import-file.ts
@@ -629,7 +629,7 @@ export async function importFromContent(
const originUri = fileOriginUri(existing?.source_uri, opts.sourceRoot, opts.sourcePath);
const persistUnchanged = async (refreshBody = false) => {
- await engine.transaction(async tx => {
+ await maintenanceTransaction(engine, async tx => {
await assertImportBase(tx, slug, sourceId ?? 'default', existing);
if (refreshBody) await tx.refreshPageBody(slug, sourceId ?? 'default', parsed.compiled_truth, parsed.timeline || '', hash);
await refreshSourcePath(tx, slug, sourceId, opts.sourcePath, existing, originUri);
@@ -686,7 +686,7 @@ export async function importFromContent(
body: { title: parsed.title, compiled_truth: parsed.compiled_truth, timeline: parsed.timeline || '' },
});
if (identity.kind === 'move' && !existing && !opts.prepare
- && await engine.updateSlug(identity.dupSlug, slug, { sourceId: sourceId ?? 'default' }) > 0) {
+ && await maintenanceTransaction(engine, tx => tx.updateSlug(identity.dupSlug, slug, { sourceId: sourceId ?? 'default' })) > 0) {
process.stderr.write(
`[import] ${opts.sourcePath} carries frontmatter.id=${fmIdStr} from moved file ${identity.dupSourcePath}; ` +
`renamed ${identity.dupSlug} -> ${slug} in source ${sourceId ?? 'default'}.\n`
diff --git a/test/e2e/write-attribution-postgres.test.ts b/test/e2e/write-attribution-postgres.test.ts
index 410fcc32ef..78e02eec2f 100644
--- a/test/e2e/write-attribution-postgres.test.ts
+++ b/test/e2e/write-attribution-postgres.test.ts
@@ -4,10 +4,12 @@ import { hasDatabase } from './helpers.ts';
// Foundations 1 write attribution on Postgres: the transaction-local actor
// settings and BEFORE ROW triggers, run direct and through transaction-mode
// PgBouncer (scripts/e2e-backend-matrix.txt). The legacy file covers the
-// unmanaged transactional writers (F1c).
+// unmanaged transactional writers (F1c); the write-attribution-<family> files
+// cover the writers Foundations 2 routed (Lane C).
if (hasDatabase()) {
await import('../write-attribution.test.ts');
await import('../write-attribution-legacy.test.ts');
+ await import('../write-attribution-import.test.ts');
} else {
test.skip('write attribution on Postgres requires DATABASE_URL', () => {});
}
diff --git a/test/helpers/unmanaged-attribution.ts b/test/helpers/unmanaged-attribution.ts
new file mode 100644
index 0000000000..82af106eae
--- /dev/null
+++ b/test/helpers/unmanaged-attribution.ts
@@ -0,0 +1,50 @@
+import { randomUUID } from 'node:crypto';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { principalAttribution, withWriteAttribution, type WriteAttribution } from '../../src/core/persistence/attribution.ts';
+import { readLocalWriter, registerLocalWriter } from '../../src/core/persistence/identity.ts';
+
+/** Who a row or page revision names: the journal request (null for maintenance) and the principal. */
+export type Actor = { request: string | null; kind: string | null; id: string | null };
+export interface UnmanagedBrain { engine: BrainEngine; sourceId: string; maintenance: Actor }
+
+/** The writer of rows that exist before the routed writer runs, so creation and last-write attribution differ. */
+export const CREATOR: WriteAttribution = principalAttribution({ kind: 'application', id: 'creator-example' });
+export const CREATOR_ACTOR: Actor = { request: null, kind: 'application', id: 'creator-example' };
+export const UNRECORDED: Actor = { request: null, kind: null, id: null };
+
+/**
+ * An unmanaged brain (persistence_brain.enabled=false) with a fresh source and
+ * a local CLI registration: routed legacy writers stamp that registration.
+ */
+export async function unmanagedBrain(engine: BrainEngine, sourceId = `legacy-${randomUUID().slice(0, 8)}`): Promise<UnmanagedBrain> {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1) ON CONFLICT (id) DO NOTHING', [sourceId]);
+ await registerLocalWriter(engine, 'cli');
+ return { engine, sourceId, maintenance: { request: null, kind: 'local_cli', id: (await readLocalWriter(engine, 'cli')).id } };
+}
+
+/** Runs fixture writes as CREATOR, so a later routed write shows up as last-write only. */
+export function asCreator<T>(engine: BrainEngine, fn: (tx: BrainEngine) => Promise<T>): Promise<T> {
+ return engine.transaction(tx => withWriteAttribution(tx, CREATOR, () => fn(tx)));
+}
+
+export async function revisionActor(engine: BrainEngine, sourceId: string, slug: string): Promise<Actor | undefined> {
+ return (await engine.executeRaw<Actor>(`SELECT revision_write_request_id::text AS request,revision_principal_kind AS kind,revision_principal_id AS id
+ FROM pages WHERE source_id=$1 AND slug=$2`, [sourceId, slug]))[0];
+}
+
+export async function versionActors(engine: BrainEngine, sourceId: string, slug: string): Promise<Array<{ write: Actor; archived: Actor }>> {
+ return engine.executeRaw<{ write: Actor; archived: Actor }>(`SELECT
+ jsonb_build_object('request',v.write_request_id::text,'kind',v.write_principal_kind,'id',v.write_principal_id) AS write,
+ jsonb_build_object('request',v.archived_write_request_id::text,'kind',v.archived_principal_kind,'id',v.archived_principal_id) AS archived
+ FROM page_versions v JOIN pages p ON p.id=v.page_id WHERE p.source_id=$1 AND p.slug=$2 ORDER BY v.id`, [sourceId, slug]);
+}
+
+/** created = write_* (immutable once set), last = last_write_* (moves on every content change). */
+export async function rowActors(engine: BrainEngine, table: 'facts' | 'takes' | 'timeline_entries', where: string, params: unknown[]):
+ Promise<Array<{ id: number; created: Actor; last: Actor }>> {
+ return engine.executeRaw<{ id: number; created: Actor; last: Actor }>(`SELECT id::int AS id,
+ jsonb_build_object('request',write_request_id::text,'kind',write_principal_kind,'id',write_principal_id) AS created,
+ jsonb_build_object('request',last_write_request_id::text,'kind',last_write_principal_kind,'id',last_write_principal_id) AS last
+ FROM ${table} WHERE ${where} ORDER BY id`, params);
+}
diff --git a/test/write-attribution-import.test.ts b/test/write-attribution-import.test.ts
new file mode 100644
index 0000000000..1b3bcd36ba
--- /dev/null
+++ b/test/write-attribution-import.test.ts
@@ -0,0 +1,66 @@
+/**
+ * Foundations 2 (Lane C) import attribution on an unmanaged brain: the
+ * moved-file rename importFromContent applies (frontmatter.id move evidence)
+ * runs in maintenanceTransaction, so the page revision it advances names the
+ * local maintenance principal instead of reading `unrecorded`.
+ *
+ * Protects the import writer family in docs/architecture/system-of-record.md.
+ * Fails if the moved-file `updateSlug` leaves 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, renameSync, 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 { importFromFile } from '../src/core/import-file.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 { revisionActor, unmanagedBrain } from './helpers/unmanaged-attribution.ts';
+
+const engines: BrainEngine[] = [];
+const scratch = mkdtempSync(join(tmpdir(), 'gbrain-write-attribution-import-'));
+let closePostgres: (() => Promise<void>) | undefined;
+
+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 });
+});
+
+describe('import attribution on an unmanaged brain', () => {
+ test('a moved file renames its page in place and the advanced revision names the maintenance principal', async () => {
+ for (const engine of engines) {
+ const brain = await unmanagedBrain(engine);
+ const root = join(scratch, brain.sourceId);
+ mkdirSync(join(root, 'notes'), { recursive: true });
+ mkdirSync(join(root, 'archive'), { recursive: true });
+ const body = '---\ntype: note\ntitle: Moved example\nid: moved-example-id\n---\nThe body travels with the file.\n';
+ writeFileSync(join(root, 'notes/moved-example.md'), body);
+ const first = await importFromFile(engine, join(root, 'notes/moved-example.md'), 'notes/moved-example.md',
+ { sourceId: brain.sourceId, noEmbed: true, sourceRoot: root });
+ const [{ id }] = await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id=$1 AND slug=$2', [brain.sourceId, first.slug]);
+
+ renameSync(join(root, 'notes/moved-example.md'), join(root, 'archive/moved-example.md'));
+ const moved = await importFromFile(engine, join(root, 'archive/moved-example.md'), 'archive/moved-example.md',
+ { sourceId: brain.sourceId, noEmbed: true, sourceRoot: root });
+
+ expect(moved.slug).not.toBe(first.slug);
+ const [renamed] = await engine.executeRaw<{ id: number; slug: string }>('SELECT id,slug FROM pages WHERE source_id=$1 AND id=$2', [brain.sourceId, id]);
+ expect(renamed.slug).toBe(moved.slug);
+ expect(await revisionActor(engine, brain.sourceId, moved.slug)).toEqual(brain.maintenance);
+ }
+ }, 120_000);
+});