Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
attribution: route schema-pack conversion writers through maintenanceTransaction
garrytan8c6c3be420bf
diff --git a/docs/architecture/system-of-record.md b/docs/architecture/system-of-record.mdindex 4d042c89b4..b4a80e669d 100644--- a/docs/architecture/system-of-record.md+++ b/docs/architecture/system-of-record.md@@ -256,6 +256,10 @@ 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/schema-pack/page-to-alias.ts` (1): the page-to-alias conversion soft-deletes each converted page in `maintenanceTransaction`.+- `src/core/schema-pack/page-to-link.ts` (1): the page-to-link conversion soft-deletes each converted page in `maintenanceTransaction`.+- `src/core/schema-pack/retype.ts` (1): each bounded retype batch runs in `maintenanceTransaction`.+- `src/core/schema-pack/sync.ts` (1): each bounded pack type sync batch runs in `maintenanceTransaction`.- `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`.@@ -277,10 +281,6 @@ these write with `NULL` attribution):- `src/core/ops/extraction.ts` (2): extraction review promote (frontmatter) and reject (soft delete).- `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.-- `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.<!-- write-attribution-unattributed:end -->## The privacy boundarydiff --git a/src/core/schema-pack/page-to-alias.ts b/src/core/schema-pack/page-to-alias.tsindex 3a4df2bccd..a3971abc7b 100644--- a/src/core/schema-pack/page-to-alias.ts+++ b/src/core/schema-pack/page-to-alias.ts@@ -24,6 +24,7 @@ import type { OperationContext } from '../operations.ts';import { parseMarkdown } from '../markdown.ts';import { loadActivePackBestEffort } from './best-effort.ts';import type { PackResolverSpec } from './manifest-v1.ts';+import { maintenanceTransaction } from '../persistence/attribution.ts';export interface PageToAliasRule {from_type: string;@@ -224,7 +225,7 @@ export async function runPageToAliasCore(// D15: do NOT rewriteLinks. Alias table IS the resolver.// Soft-delete LAST so a crash between insert + delete leaves// alias present (idempotent on retry).- const sdResult = await ctx.engine.softDeletePage(r.slug, { sourceId: effectiveSourceId });+ const sdResult = await maintenanceTransaction(ctx.engine, tx => tx.softDeletePage(r.slug, { sourceId: effectiveSourceId }));if (sdResult) soft_deleted++;opts.onProgress?.({ rule_index: i, aliasedSoFar: aliased });}diff --git a/src/core/schema-pack/page-to-link.ts b/src/core/schema-pack/page-to-link.tsindex 98c9d155c7..5adb9c4944 100644--- a/src/core/schema-pack/page-to-link.ts+++ b/src/core/schema-pack/page-to-link.ts@@ -27,6 +27,7 @@ import type { OperationContext } from '../operations.ts';import { parseMarkdown } from '../markdown.ts';import { loadActivePackBestEffort } from './best-effort.ts';import type { PackResolverSpec } from './manifest-v1.ts';+import { maintenanceTransaction } from '../persistence/attribution.ts';export interface PageToLinkRule {from_type: string;@@ -208,7 +209,7 @@ export async function runPageToLinkCore(converted = linksBuffer.length;}for (const slug of pagesToSoftDelete) {- const result = await ctx.engine.softDeletePage(slug, { sourceId });+ const result = await maintenanceTransaction(ctx.engine, tx => tx.softDeletePage(slug, { sourceId }));if (result) soft_deleted++;}opts.onProgress?.({ rule_index: i, convertedSoFar: converted });diff --git a/src/core/schema-pack/retype.ts b/src/core/schema-pack/retype.tsindex db764099c3..feb0c17788 100644--- a/src/core/schema-pack/retype.ts+++ b/src/core/schema-pack/retype.ts@@ -28,6 +28,7 @@ import type { BrainEngine } from '../engine.ts';import type { OperationContext } from '../operations.ts';import { loadActivePackBestEffort } from './best-effort.ts';import { ALLOWED_SUBTYPE_FIELDS, type AllowedSubtypeField } from './manifest-v1.ts';+import { maintenanceTransaction } from '../persistence/attribution.ts';/** Sentinel: `from_type: '*unknown*'` matches every page whose type isn't* declared in the pack's page_types AND isn't the target of any prior@@ -248,7 +249,7 @@ async function applyRetypeRule(SELECT COUNT(*)::text AS updated FROM upd`;try {- const rows = await engine.executeRaw<{ updated: string }>(sqlText, allParams);+ const rows = await maintenanceTransaction(engine, tx => tx.executeRaw<{ updated: string }>(sqlText, allParams));const batchCount = parseInt(rows[0]?.updated ?? '0', 10) || 0;if (batchCount === 0) break;totalApplied += batchCount;diff --git a/src/core/schema-pack/sync.ts b/src/core/schema-pack/sync.tsindex 068d8dad5d..706442e055 100644--- a/src/core/schema-pack/sync.ts+++ b/src/core/schema-pack/sync.ts@@ -19,6 +19,7 @@import type { BrainEngine } from '../engine.ts';import { loadActivePackBestEffort } from './best-effort.ts';import type { OperationContext } from '../operations.ts';+import { maintenanceTransaction } from '../persistence/attribution.ts';export interface SyncOpts {/** Apply UPDATE statements. Default false (dry-run). */@@ -119,7 +120,7 @@ async function applyTypeAssignment(// Loop guard: max 10000 iterations protects against runaway.for (let i = 0; i < 10000; i++) {try {- const rows = await engine.executeRaw<{ updated: string }>(+ const rows = await maintenanceTransaction(engine, tx => tx.executeRaw<{ updated: string }>(`WITH win AS (SELECT id FROM pagesWHERE deleted_at IS NULL@@ -134,7 +135,7 @@ async function applyTypeAssignment()SELECT COUNT(*)::text AS updated FROM upd`,[type, `${prefix}%`, batchSize, ...sourceParams],- );+ ));const batchCount = parseInt(rows[0]?.updated ?? '0', 10) || 0;if (batchCount === 0) break;totalApplied += batchCount;diff --git a/test/write-attribution-schema-pack.test.ts b/test/write-attribution-schema-pack.test.tsnew file mode 100644index 0000000000..54e45e0b1b--- /dev/null+++ b/test/write-attribution-schema-pack.test.ts@@ -0,0 +1,122 @@+/**+ * Foundations 2 (Lane C) schema-pack conversion attribution on an unmanaged+ * brain: page-to-alias and page-to-link soft deletes and the retype and type+ * sync batches run in maintenanceTransaction, so every page they advance names+ * the local maintenance principal instead of `unrecorded`.+ *+ * Protects the schema-pack writer family in docs/architecture/system-of-record.md.+ * Fails if page-to-alias.ts, page-to-link.ts, retype.ts or schema-pack/sync.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, 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 type { OperationContext } from '../src/core/ops/contract.ts';+import { runPageToAliasCore } from '../src/core/schema-pack/page-to-alias.ts';+import { runPageToLinkCore } from '../src/core/schema-pack/page-to-link.ts';+import { runRetypeCore } from '../src/core/schema-pack/retype.ts';+import { runSyncCore } from '../src/core/schema-pack/sync.ts';+import { __setPackLocatorForTests, _resetPackLocatorForTests } from '../src/core/schema-pack/load-active.ts';+import { _resetPackCacheForTests } from '../src/core/schema-pack/registry.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 { withEnv } from './helpers/with-env.ts';+import { asCreator, revisionActor, unmanagedBrain, type UnmanagedBrain } from './helpers/unmanaged-attribution.ts';++const engines: BrainEngine[] = [];+const scratch = mkdtempSync(join(tmpdir(), 'gbrain-write-attribution-schema-pack-'));+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 () => {+ _resetPackLocatorForTests();+ _resetPackCacheForTests();+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }+ await closePostgres?.();+ rmSync(scratch, { recursive: true, force: true });+});++const ctx = (brain: UnmanagedBrain): OperationContext => ({ engine: brain.engine, config: {} as never, logger: { info() {}, warn() {}, error() {} } as never,+ dryRun: false, remote: false, sourceId: brain.sourceId });+async function seed(brain: UnmanagedBrain, slug: string, type: string, body = 'A page body.', frontmatter: Record<string, unknown> = {}) {+ await asCreator(brain.engine, tx => tx.putPage(slug, { title: slug, type: type as never, compiled_truth: body, timeline: '', frontmatter, source_path: `${slug}.md` } as never,+ { sourceId: brain.sourceId }));+}+const deletedRevisionActor = async (brain: UnmanagedBrain, slug: string) => (await brain.engine.executeRaw<{ request: string | null; kind: string | null; id: string | null }>(+ `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 AND deleted_at IS NOT NULL`, [brain.sourceId, slug]))[0];++describe('schema-pack conversions on an unmanaged brain', () => {+ test('page-to-alias soft-deletes the redirect page under the maintenance principal', async () => {+ for (const engine of engines) {+ const brain = await unmanagedBrain(engine);+ await seed(brain, 'wiki/concepts/canonical-example', 'concept', 'The canonical body, long enough for every guard in the converter.');+ await seed(brain, 'wiki/concepts/redirect-example', 'concept-redirect', '[[wiki/concepts/canonical-example]] redirects to the canonical page');+ const result = await runPageToAliasCore(ctx(brain), { rules: [{ from_type: 'concept-redirect', canonical_from: 'body_first_link', alias_slug_from: 'slug' }], apply: true, sourceId: brain.sourceId } as never);+ expect(result.per_rule[0].soft_deleted).toBe(1);+ expect(await deletedRevisionActor(brain, 'wiki/concepts/redirect-example')).toEqual(brain.maintenance);+ }+ }, 120_000);++ test('page-to-link soft-deletes the edge-shaped page under the maintenance principal', async () => {+ for (const engine of engines) {+ const brain = await unmanagedBrain(engine);+ await seed(brain, 'people/alice-example', 'person');+ await seed(brain, 'companies/acme-example', 'company');+ await seed(brain, 'atoms/partner-example', 'atom-partner-link', 'An edge.', { source: 'people/alice-example', target: 'companies/acme-example' });+ const result = await runPageToLinkCore(ctx(brain), { rules: [{ from_type: 'atom-partner-link', link_type: 'partner_of',+ source_slug_from: { frontmatter_field: 'source' }, target_slug_from: { frontmatter_field: 'target' } }], apply: true, sourceId: brain.sourceId } as never);+ expect(result.per_rule[0].converted).toBe(1);+ expect(await deletedRevisionActor(brain, 'atoms/partner-example')).toEqual(brain.maintenance);+ }+ }, 120_000);++ test('retype advances each retyped page under the maintenance principal', async () => {+ for (const engine of engines) {+ const brain = await unmanagedBrain(engine);+ await seed(brain, 'tweets/one-example', 'tweet-single');+ await seed(brain, 'tweets/two-example', 'tweet-single');+ const result = await runRetypeCore(ctx(brain), { rules: [{ from_type: 'tweet-single', to_type: 'tweet', subtype: 'single' }], apply: true, sourceId: brain.sourceId } as never);+ expect(result.total_applied).toBe(2);+ for (const slug of ['tweets/one-example', 'tweets/two-example']) expect(await revisionActor(engine, brain.sourceId, slug)).toEqual(brain.maintenance);+ }+ }, 120_000);++ test('the pack type sync advances each typed page under the maintenance principal', async () => {+ const pack = join(scratch, 'tiny', 'pack.yaml');+ mkdirSync(join(scratch, 'tiny'), { recursive: true });+ writeFileSync(pack, 'api_version: gbrain-schema-pack-v1\nname: tiny\nversion: 1.0.0\ndescription: ""\ngbrain_min_version: 0.38.0\nextends: null\nborrow_from: []\n'+ + 'page_types:\n - name: person\n primitive: entity\n path_prefixes:\n - people/\n aliases: []\n extractable: false\n expert_routing: false\n'+ + 'link_types: []\nfrontmatter_links: []\ntakes_kinds:\n - fact\n - take\n - bet\n - hunch\nenrichable_types: []\nfiling_rules: []\n');+ // The brains register their local writer before GBRAIN_HOME moves: the maintenance principal is that registration.+ const brains = [];+ for (const engine of engines) brains.push(await unmanagedBrain(engine));+ await withEnv({ GBRAIN_SCHEMA_PACK: 'tiny' }, async () => {+ for (const brain of brains) {+ const engine = brain.engine;+ _resetPackCacheForTests();+ __setPackLocatorForTests(name => (name === 'tiny' ? pack : null));+ await seed(brain, 'bea-example', 'note');+ await engine.executeRaw(`UPDATE pages SET type='', source_path='people/bea-example.md' WHERE source_id=$1 AND slug='bea-example'`, [brain.sourceId]);+ await engine.executeRaw('UPDATE pages SET revision_principal_kind=NULL, revision_principal_id=NULL WHERE source_id=$1', [brain.sourceId]);+ const result = await runSyncCore(ctx(brain), { apply: true });+ expect(result.total_applied).toBe(1);+ expect(await revisionActor(engine, brain.sourceId, 'bea-example')).toEqual(brain.maintenance);+ }+ });+ }, 120_000);+});