Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

attribution: route cycle and synthesis writers through maintenanceTransaction

garrytan17f2ffcd749f
diff --git a/docs/architecture/system-of-record.md b/docs/architecture/system-of-record.md
index a69c893fbd..4d042c89b4 100644
--- a/docs/architecture/system-of-record.md
+++ b/docs/architecture/system-of-record.md
@@ -212,9 +212,19 @@ or a physical projection that leaves attribution untouched):
- `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/dream-provenance.ts` (1): the dream provenance frontmatter stamp runs per page in `maintenanceTransaction` (unmanaged brains only; managed synthesis publishes through maintenance requests).
+- `src/core/cycle/drift.ts` (1): the unmanaged drift report page runs in `maintenanceTransaction`; managed brains publish it through a maintenance request.
+- `src/core/cycle/extract-atoms-page-state.ts` (1): the atom completion stamp runs in `maintenanceTransaction`.
+- `src/core/cycle/extract-atoms.ts` (1): stale atom retirement soft-deletes in 500-page `maintenanceTransaction` chunks.
+- `src/core/cycle/extract-facts.ts` (7): the unmanaged page reconcile and the expiry of fence facts whose page was soft-deleted run in `maintenanceTransaction`; managed brains write through `withDerivedFactsWrite`.
- `src/core/cycle/extract-takes.ts` (2): coordinated per page on managed brains; the unmanaged batch upsert runs in `maintenanceTransaction`.
+- `src/core/cycle/grade-takes.ts` (1): unmanaged take auto-resolution runs in `maintenanceTransaction`; managed brains publish a `takes_resolve` request.
+- `src/core/cycle/phantom-redirect.ts` (3): the unmanaged phantom fact move, canonical body refresh and phantom soft delete run in `maintenanceTransaction`; the managed redirect moves facts inside its coordinated write.
+- `src/core/cycle/phases/consolidate.ts` (4): unmanaged consolidation takes and fact updates run in `maintenanceTransaction` per cluster step; managed brains submit a maintenance consolidation request.
+- `src/core/cycle/synthesize.ts` (1): the unmanaged dream summary page runs in `maintenanceTransaction`; managed brains publish it through a maintenance request.
- `src/core/embed-facts.ts` (1): embedding columns only (physical projection).
- `src/core/embedding-dim-check.ts` (1): embedding columns only (physical projection).
+- `src/core/extract/receipt-writer.ts` (1): the extraction receipt page runs in `maintenanceTransaction`.
- `src/core/facts/backstop.ts` (3): the facts backstop's DB-only fallbacks insert each fact in `maintenanceTransaction`; managed brains publish through the facts request preparer.
- `src/core/facts/fence-write.ts` (2): the markdown-first fence reconcile insert and its page body mirror each run in `maintenanceTransaction`.
- `src/core/facts/forget.ts` (4): the legacy fence expiry, withdrawal and strike-through each run in `maintenanceTransaction` (nested inside a caller's coordinated write, they keep its actor).
@@ -223,6 +233,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/facts/write-single.ts` (2): the legacy single-fact insert and its supersession link each run in `maintenanceTransaction`; managed brains publish through the fact request.
- `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/output/writer.ts` (4): `BrainWriter.transaction` is a `maintenanceTransaction`, so its pages and timeline rows carry the maintenance principal.
- `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.
@@ -247,6 +258,7 @@ or a physical projection that leaves attribution untouched):
- `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/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-write-through.ts` (2): the timeline write-through's page row splice and entry insert run in one `maintenanceTransaction`.
<!-- write-attribution-covered:end -->
@@ -259,28 +271,16 @@ these write with `NULL` attribution):
- `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.
-- `src/core/cycle/dream-provenance.ts` (1): dream provenance frontmatter stamp.
-- `src/core/cycle/drift.ts` (1): drift report page.
-- `src/core/cycle/extract-atoms-page-state.ts` (1): atom extraction frontmatter stamp.
-- `src/core/cycle/extract-atoms.ts` (1): soft delete of stale atoms.
-- `src/core/cycle/extract-facts.ts` (7): remaining site: expiry of fence facts whose page was soft-deleted. The page reconcile is attributed.
-- `src/core/cycle/grade-takes.ts` (1): take resolution.
-- `src/core/cycle/phantom-redirect.ts` (3): fact move, phantom page body refresh and soft delete.
-- `src/core/cycle/phases/consolidate.ts` (4): consolidation takes and fact updates.
-- `src/core/cycle/synthesize.ts` (1): synthesis summary page.
- `src/core/enrichment-service.ts` (2): enrichment page and auto-timeline entry.
- `src/core/extract-timeline-from-meetings.ts` (1): meeting timeline batch.
-- `src/core/extract/receipt-writer.ts` (1): extraction receipt page.
- `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/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.
-- `src/core/think/index.ts` (1): saved `think` result page.
<!-- write-attribution-unattributed:end -->
## The privacy boundary
diff --git a/src/core/cycle/dream-provenance.ts b/src/core/cycle/dream-provenance.ts
index abfd51d763..c8cc4ab28a 100644
--- a/src/core/cycle/dream-provenance.ts
+++ b/src/core/cycle/dream-provenance.ts
@@ -1,5 +1,6 @@
import type { BrainEngine } from '../engine.ts';
import { throwIfAborted } from '../abort-check.ts';
+import { maintenanceTransaction } from '../persistence/attribution.ts';
/**
* Dream-provenance DB stamp (#2569): marks pages a dream child wrote with
@@ -20,8 +21,8 @@ export async function stampDreamProvenance(
// failures and must not swallow the cancellation unwind.
throwIfAborted(signal, '[dream] synthesize provenance');
try {
- await executeRawJsonb(
- engine,
+ await maintenanceTransaction(engine, tx => executeRawJsonb(
+ tx,
`UPDATE pages
SET frontmatter = COALESCE(frontmatter, '{}'::jsonb)
|| $5::jsonb
@@ -48,7 +49,7 @@ export async function stampDreamProvenance(
...(seat ? { seat } : {}),
...(raw_trace_exempt_reason ? { raw_trace_exempt: true, raw_trace_exempt_reason } : {}),
}],
- );
+ ));
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
process.stderr.write(`[dream] provenance stamp ${slug}@${source_id} failed: ${msg}\n`);
diff --git a/src/core/cycle/drift.ts b/src/core/cycle/drift.ts
index c9f729ecbf..9a8b5ee407 100644
--- a/src/core/cycle/drift.ts
+++ b/src/core/cycle/drift.ts
@@ -30,6 +30,7 @@ import { resolveModel } from '../model-config.ts';
import type { DreamPhaseResult } from './auto-think.ts';
import { maintenancePreflight, publishMaintenancePage } from '../persistence/prepared-maintenance.ts';
import { serializeMarkdown } from '../markdown.ts';
+import { maintenanceTransaction } from '../persistence/attribution.ts';
export interface DriftPhaseOpts {
brainDir?: string;
@@ -371,12 +372,12 @@ export async function runPhaseDrift(
await publishMaintenancePage(engine, maintenance, reportSlug, serializeMarkdown({ report_type: 'drift' }, buildReportBody(judged, config, modelId), '',
{ type: 'note', title: `Drift report ${cycleDate}`, tags: [] }), { expectedRevision: snapshot?.revision ?? null, file: false });
} else {
- await engine.putPage(reportSlug, {
+ await maintenanceTransaction(engine, tx => tx.putPage(reportSlug!, {
type: 'note',
frontmatter: { report_type: 'drift' },
title: `Drift report ${cycleDate}`,
compiled_truth: buildReportBody(judged, config, modelId),
- });
+ }));
}
}
diff --git a/src/core/cycle/extract-atoms-page-state.ts b/src/core/cycle/extract-atoms-page-state.ts
index 8fc00323d7..929365e7c8 100644
--- a/src/core/cycle/extract-atoms-page-state.ts
+++ b/src/core/cycle/extract-atoms-page-state.ts
@@ -2,6 +2,7 @@ import type { SqlEngine } from '../persistence/model.ts';
import type { PageSnapshot } from '../page-state/types.ts';
import { stableJson } from '../persistence/digest.ts';
import type { BrainEngine } from '../engine.ts';
+import { maintenanceTransaction } from '../persistence/attribution.ts';
export interface AtomPageIdentity {
pageId: number;
@@ -65,7 +66,7 @@ export async function writeAtomPageState(
export async function completeAtomReceipts(
engine: BrainEngine, sourceId: string, importedSlugs: string[], hash16: string, page?: AtomPageInput,
): Promise<void> {
- await engine.transaction(async tx => {
+ await maintenanceTransaction(engine, async tx => {
const completed = await tx.executeRaw(
`UPDATE pages
SET frontmatter = frontmatter || jsonb_build_object('source_hash', $1::text)
diff --git a/src/core/cycle/extract-atoms.ts b/src/core/cycle/extract-atoms.ts
index 17deeba6a0..a3ea434086 100644
--- a/src/core/cycle/extract-atoms.ts
+++ b/src/core/cycle/extract-atoms.ts
@@ -91,6 +91,7 @@ import { OperationError } from '../ops/contract.ts';
import type { WriteReceipt } from '../persistence/types.ts';
import { acceptedPendingReceipt } from '../persistence/accepted-pending.ts';
import { AtomPageStateError, completeAtomReceipts, readAtomPageIdentity, writeAtomPageState, type AtomPageInput } from './extract-atoms-page-state.ts';
+import { maintenanceTransaction } from '../persistence/attribution.ts';
import { ATOM_TYPES, ATOMS_RESPONSE_SCHEMA } from './extract-atoms-schema.ts';
const DEFAULT_BUDGET_USD = 0.3;
@@ -1670,7 +1671,7 @@ async function retireStaleAtoms(
[sourceId, origin.value, hash16, currentSlugs],
);
const stale = rows.map(r => r.slug);
- for (let i = 0; i < stale.length; i += 500) await engine.softDeletePages(stale.slice(i, i + 500), { sourceId });
+ for (let i = 0; i < stale.length; i += 500) await maintenanceTransaction(engine, tx => tx.softDeletePages(stale.slice(i, i + 500), { sourceId }));
} catch (err) {
console.error(`[extract_atoms] stale atom cleanup failed for ${origin.value} (non-fatal): ${err instanceof Error ? err.message : String(err)}`);
}
diff --git a/src/core/cycle/extract-facts.ts b/src/core/cycle/extract-facts.ts
index 1ca31c4d81..1db3abffed 100644
--- a/src/core/cycle/extract-facts.ts
+++ b/src/core/cycle/extract-facts.ts
@@ -618,7 +618,7 @@ export async function runExtractFacts(
);
// Managed: one page at a time under its key, so a concurrent restore is
// either seen as restored or waited for, never expired underneath it.
- const expired = managed ? await expireDeletedPagesManaged(engine, sourceId, transact) : await expireDeleted(engine);
+ const expired = managed ? await expireDeletedPagesManaged(engine, sourceId, transact) : await maintenanceTransaction(engine, expireDeleted);
result.factsExpiredForDeletedPages = expired.length;
}
diff --git a/src/core/cycle/grade-takes.ts b/src/core/cycle/grade-takes.ts
index a8dad3b615..37f2ef5e89 100644
--- a/src/core/cycle/grade-takes.ts
+++ b/src/core/cycle/grade-takes.ts
@@ -49,6 +49,7 @@ import type { PhaseStatus, CyclePhase } from '../cycle.ts';
import { managedPersistenceEnabled } from '../persistence/ownership.ts';
import { parseTakesFence } from '../takes-fence.ts';
import { submitPageMutation } from '../persistence/page-mutations.ts';
+import { maintenanceTransaction } from '../persistence/attribution.ts';
/**
* Bump when the judge prompt or the JSON output shape changes. Old verdicts
@@ -809,7 +810,7 @@ class GradeTakesPhase extends BaseCyclePhase {
evidence: resolution.source, resolved_by: resolution.resolvedBy,
request_id: createHash('sha256').update(`grade_takes:${take.id}:${recordedSig}:${snapshot.revision}`).digest('hex').replace(/^(.{8})(.{4}).(.{3}).(.{3})(.{12}).*/, '$1-$2-4$3-a$4-$5') } });
} else {
- await engine.resolveTake(take.page_id, take.row_num, resolution);
+ await maintenanceTransaction(engine, tx => tx.resolveTake(take.page_id, take.row_num, resolution));
}
result.auto_applied += 1;
diff --git a/src/core/cycle/phantom-redirect.ts b/src/core/cycle/phantom-redirect.ts
index 893b8f2c35..83bec4e054 100644
--- a/src/core/cycle/phantom-redirect.ts
+++ b/src/core/cycle/phantom-redirect.ts
@@ -58,6 +58,7 @@ import { logPhantomEvent, type PhantomOutcome } from '../facts/phantom-audit.ts'
import { MOVE_WITHDRAWAL_SUBJECT_SQL } from '../facts/withdrawal-schema.ts';
import { resolvePageWriteTarget } from '../write-through.ts';
import { recordRenameAlias } from '../page-state/rename-alias.ts';
+import { maintenanceTransaction } from '../persistence/attribution.ts';
import { managedPersistenceEnabled } from '../persistence/ownership.ts';
/** Tagged-union outcome of a single phantom-redirect attempt. */
@@ -302,7 +303,7 @@ async function migratePhantomFacts(
canonicalSlug: string,
rowMap: ReadonlyMap<number, number>,
): Promise<number> {
- return engine.transaction(tx => movePhantomFacts(tx, sourceId, phantomSlug, canonicalSlug, rowMap));
+ return maintenanceTransaction(engine, tx => movePhantomFacts(tx, sourceId, phantomSlug, canonicalSlug, rowMap));
}
/** The body of migratePhantomFacts inside the caller's transaction. */
@@ -578,13 +579,13 @@ export async function tryRedirectPhantom(
frontmatter: reparsed.frontmatter,
tags: canonicalTags,
});
- await engine.refreshPageBody(
+ await maintenanceTransaction(engine, tx => tx.refreshPageBody(
canonical,
sourceId,
reparsed.compiled_truth,
reparsed.timeline,
newContentHash,
- );
+ ));
// Withdrawals are scoped to the entity; the phantom was the canonical
// entity. Moved first, so the withdrawal trigger honors them as the
@@ -599,7 +600,7 @@ export async function tryRedirectPhantom(
// Round 19/20: soft-delete + unlink. Order matters — softDelete first
// so a concurrent sync that observes the phantom .md gone treats it as
// a normal deletion (not a regression).
- await engine.softDeletePage(page.slug, { sourceId });
+ await maintenanceTransaction(engine, tx => tx.softDeletePage(page.slug, { sourceId }));
const phantomPath = path.join(brainDir, `${page.slug}.md`);
if (fs.existsSync(phantomPath)) {
try {
diff --git a/src/core/cycle/phases/consolidate.ts b/src/core/cycle/phases/consolidate.ts
index c2bbbd5a91..7546f9a357 100644
--- a/src/core/cycle/phases/consolidate.ts
+++ b/src/core/cycle/phases/consolidate.ts
@@ -29,6 +29,7 @@ import { createHash } from 'node:crypto';
import { isAborted } from '../../abort-check.ts';
import { maintenancePreflight, submitMaintenanceConsolidation } from '../../persistence/prepared-maintenance.ts';
import { managedPersistenceEnabled } from '../../persistence/ownership.ts';
+import { maintenanceTransaction } from '../../persistence/attribution.ts';
export interface ConsolidatePhaseOpts {
dryRun?: boolean;
@@ -225,13 +226,13 @@ export async function runPhaseConsolidate(
// would bypass that guard. Reuse its id so the facts still consolidate
// into it, but leave the row untouched.
if (existing[0].resolved_at === null) {
- await engine.executeRaw(
+ await maintenanceTransaction(engine, tx => tx.executeRaw(
`UPDATE takes SET source = $1, updated_at = now() WHERE id = $2`,
[sources.slice(0, 200), takeId],
- );
+ ));
}
} else {
- const inserted = await engine.addTakesBatch([{
+ const inserted = await maintenanceTransaction(engine, tx => tx.addTakesBatch([{
page_id: pageId,
row_num: nextRowNum,
claim: best.fact,
@@ -241,7 +242,7 @@ export async function runPhaseConsolidate(
since_date: sinceISO,
source: sources.slice(0, 200),
active: true,
- }]);
+ }]));
if (inserted < 1) continue;
const idRows = await engine.executeRaw<{ id: number }>(
@@ -258,10 +259,10 @@ export async function runPhaseConsolidate(
}
// Mark all contributing facts consolidated.
- for (const f of cluster) {
- await engine.consolidateFact(f.id, takeId);
- factsConsolidated += 1;
- }
+ await maintenanceTransaction(engine, async tx => {
+ for (const f of cluster) await tx.consolidateFact(f.id, takeId);
+ });
+ factsConsolidated += cluster.length;
// v0.35.4 (D-CDX-4 part 2) — chronological valid_until writeback.
// Sort the cluster by (valid_from ASC, id ASC); walk consecutive
@@ -279,20 +280,22 @@ export async function runPhaseConsolidate(
if (t !== 0) return t;
return a.id - b.id;
});
- for (let i = 0; i < chronological.length - 1; i++) {
- const older = chronological[i];
- const newer = chronological[i + 1];
- await engine.executeRaw(
- // Only UPDATE when the new value would actually change. Avoids
- // touching updated_at on no-op rewrites and keeps idempotency
- // observable in the DB (zero affected rows on stable re-run).
- `UPDATE facts
- SET valid_until = $1
- WHERE id = $2
- AND (valid_until IS DISTINCT FROM $1)`,
- [newer.valid_from, older.id],
- );
- }
+ await maintenanceTransaction(engine, async tx => {
+ for (let i = 0; i < chronological.length - 1; i++) {
+ const older = chronological[i];
+ const newer = chronological[i + 1];
+ await tx.executeRaw(
+ // Only UPDATE when the new value would actually change. Avoids
+ // touching updated_at on no-op rewrites and keeps idempotency
+ // observable in the DB (zero affected rows on stable re-run).
+ `UPDATE facts
+ SET valid_until = $1
+ WHERE id = $2
+ AND (valid_until IS DISTINCT FROM $1)`,
+ [newer.valid_from, older.id],
+ );
+ }
+ });
}
}
diff --git a/src/core/cycle/synthesize.ts b/src/core/cycle/synthesize.ts
index 2d01adf66c..c6862ee928 100644
--- a/src/core/cycle/synthesize.ts
+++ b/src/core/cycle/synthesize.ts
@@ -75,6 +75,7 @@ import { buildManifestContext, buildLinkManifest, type ManifestContext } from '.
import { resolveCycleDate, utcDate } from './cycle-date.ts';
import { throwIfAborted } from '../abort-check.ts';
import { stampDreamProvenance } from './dream-provenance.ts';
+import { maintenanceTransaction } from '../persistence/attribution.ts';
// Re-exports: the drain was peeled to inline-drain.ts (dream-wave C7), the
// allow-list loader to filing-rules.ts (#2397); patterns.ts and the
@@ -3193,13 +3194,13 @@ async function writeSummaryPage(
const { parseMarkdown } = await import('../markdown.ts');
const parsed = parseMarkdown(fullMarkdown);
- if (!maintenance) await engine.putPage(summarySlug, {
+ if (!maintenance) await maintenanceTransaction(engine, tx => tx.putPage(summarySlug, {
type: parsed.type,
title: parsed.title,
compiled_truth: parsed.compiled_truth,
timeline: parsed.timeline,
frontmatter: parsed.frontmatter,
- }, { sourceId });
+ }, { sourceId }));
const fileWriteRaw = (await engine.getConfig('dream.synthesize.summary_file_write'))?.trim().toLowerCase();
const fileWriteEnabled = !(fileWriteRaw === 'false' || fileWriteRaw === '0' || fileWriteRaw === 'off');
diff --git a/src/core/extract/receipt-writer.ts b/src/core/extract/receipt-writer.ts
index 6b87efa681..2ed7105295 100644
--- a/src/core/extract/receipt-writer.ts
+++ b/src/core/extract/receipt-writer.ts
@@ -37,6 +37,7 @@
import type { BrainEngine } from '../engine.ts';
import type { Page } from '../types.ts';
+import { maintenanceTransaction } from '../persistence/attribution.ts';
/**
* Round identifier. Matches the progressive-batch primitive's Stage
@@ -208,7 +209,7 @@ export async function writeReceipt(
const frontmatter = buildReceiptFrontmatter(input);
const compiled_truth = buildReceiptBody(input);
- const page = await engine.putPage(
+ const page = await maintenanceTransaction(engine, tx => tx.putPage(
slug,
{
type: 'extract_receipt',
@@ -217,7 +218,7 @@ export async function writeReceipt(
frontmatter,
},
{ sourceId: input.source_id },
- );
+ ));
// #4009: receipts are audit artifacts — deliberately never run through
// the contextual-retrieval ladder. Born with a NULL
diff --git a/src/core/output/writer.ts b/src/core/output/writer.ts
index f3db30d93d..15f84e5960 100644
--- a/src/core/output/writer.ts
+++ b/src/core/output/writer.ts
@@ -21,6 +21,7 @@ import type { BrainEngine } from '../engine.ts';
import type { PageType, TimelineInput } from '../types.ts';
import type { ResolverContext } from '../resolvers/interface.ts';
import { SlugRegistry } from './slug-registry.ts';
+import { maintenanceTransaction } from '../persistence/attribution.ts';
// ---------------------------------------------------------------------------
// Types
@@ -301,7 +302,7 @@ export class BrainWriter {
let report: ValidationReport | null = null;
const strictSourceId = this.sourceId;
- const txResult = await this.engine.transaction(async (txEngine) => {
+ const txResult = await maintenanceTransaction(this.engine, async (txEngine) => {
const tx = new WriteTxImpl(txEngine, ctx, strictSourceId);
const result = await fn(tx);
diff --git a/src/core/think/index.ts b/src/core/think/index.ts
index 44541d92c9..11c5e1a15a 100644
--- a/src/core/think/index.ts
+++ b/src/core/think/index.ts
@@ -36,6 +36,7 @@ import { resolveExcludePrivatePages } from '../search/private-visibility.ts';
import { deliverEvidence, effectivePlan, resolveEvidencePlan, EVIDENCE_BLOCK_CHAR_CAP, THINK_RETURN_UNIT_CONFIG_KEY, type DeliveryMeta } from '../search/evidence-delivery.ts';
import { startThinkDecide, thinkAbstainResult, type ThinkAbstention } from './decide.ts';
import { classifyIntent } from './intent.ts';
+import { maintenanceTransaction } from '../persistence/attribution.ts';
/** Anthropic Messages client interface — same shape used by subagent.ts so test stubs can be shared. */
export interface ThinkLLMClient {
@@ -1039,7 +1040,7 @@ export async function persistSynthesis(
result.gaps.length > 0 ? '## Gaps\n\n' + result.gaps.map(g => `- ${g}`).join('\n') : '',
].filter(Boolean).join('\n');
- const page = await engine.putPage(slug, {
+ const page = await maintenanceTransaction(engine, tx => tx.putPage(slug, {
title: result.question.slice(0, 200),
type: 'synthesis',
compiled_truth: body,
@@ -1051,7 +1052,7 @@ export async function persistSynthesis(
pages_gathered: result.pagesGathered,
takes_gathered: result.takesGathered,
},
- }, scope.sourceId ? { sourceId: scope.sourceId } : undefined);
+ }, scope.sourceId ? { sourceId: scope.sourceId } : undefined));
const persisted = await persistCitations(engine, page.id, result.citations, scope);
return { slug, evidenceInserted: persisted.inserted, warnings: persisted.warnings };
diff --git a/test/cycle-synthesize-summary-page.test.ts b/test/cycle-synthesize-summary-page.test.ts
index 81dd84290a..36dcbbc230 100644
--- a/test/cycle-synthesize-summary-page.test.ts
+++ b/test/cycle-synthesize-summary-page.test.ts
@@ -41,6 +41,9 @@ async function renderSummary(writtenSlugs: string[]): Promise<{ body: string; ma
},
// #4506 dual-write suppressor reads this knob; default-on path.
getConfig: async (_key: string) => null,
+ // The summary write runs in a maintenance transaction; the stub is its own transaction engine.
+ executeRaw: async () => [],
+ transaction: async <T>(fn: (tx: BrainEngine) => Promise<T>) => fn(engine),
} as unknown as BrainEngine;
try {
await writeSummaryPage(
diff --git a/test/e2e/write-attribution-postgres.test.ts b/test/e2e/write-attribution-postgres.test.ts
index 2cdb1308c9..a5e2c1b506 100644
--- a/test/e2e/write-attribution-postgres.test.ts
+++ b/test/e2e/write-attribution-postgres.test.ts
@@ -14,6 +14,7 @@ if (hasDatabase()) {
await import('../write-attribution-timeline.test.ts');
await import('../write-attribution-timeline-10k.slow.test.ts');
await import('../write-attribution-facts-takes.test.ts');
+ await import('../write-attribution-cycle.test.ts');
} else {
test.skip('write attribution on Postgres requires DATABASE_URL', () => {});
}
diff --git a/test/extract-facts-guard-rollup.test.ts b/test/extract-facts-guard-rollup.test.ts
index 8fad6192ea..7a48e3b052 100644
--- a/test/extract-facts-guard-rollup.test.ts
+++ b/test/extract-facts-guard-rollup.test.ts
@@ -31,6 +31,8 @@ function mkEngine(legacyCount: number): { calls: CapturedCall[]; engine: BrainEn
async getPage() { return null; },
async deleteFactsForPage() { return { deleted: 0 }; },
async insertFacts() { return { inserted: 0, ids: [], warnings: [], deleted: 0 }; },
+ // Unmanaged fact expiry runs in a maintenance transaction; the stub is its own transaction engine.
+ async transaction<T>(fn: (tx: BrainEngine) => Promise<T>): Promise<T> { return fn(engine); },
} as unknown as BrainEngine;
return { calls, engine };
}
diff --git a/test/grade-takes-ensemble.test.ts b/test/grade-takes-ensemble.test.ts
index 147c807f05..bf0a3056b9 100644
--- a/test/grade-takes-ensemble.test.ts
+++ b/test/grade-takes-ensemble.test.ts
@@ -59,6 +59,10 @@ function buildMockEngine(opts: { takes: Take[] }): {
async resolveTake(pageId: number, rowNum: number, resolution: TakeResolution): Promise<void> {
resolves.push({ pageId, rowNum, resolution });
},
+ // The resolution runs in a maintenance transaction; the mock is its own transaction engine.
+ async transaction<T>(fn: (tx: BrainEngine) => Promise<T>): Promise<T> {
+ return fn(engine);
+ },
} as unknown as BrainEngine;
return { engine, captured, resolves };
}
diff --git a/test/grade-takes.test.ts b/test/grade-takes.test.ts
index 6f97761771..1a8d38b46e 100644
--- a/test/grade-takes.test.ts
+++ b/test/grade-takes.test.ts
@@ -71,6 +71,10 @@ function buildMockEngine(opts: {
async resolveTake(pageId: number, rowNum: number, resolution: TakeResolution): Promise<void> {
resolves.push({ pageId, rowNum, resolution });
},
+ // The resolution runs in a maintenance transaction; the mock is its own transaction engine.
+ async transaction<T>(fn: (tx: BrainEngine) => Promise<T>): Promise<T> {
+ return fn(engine);
+ },
} as unknown as BrainEngine;
return { engine, captured, resolves };
diff --git a/test/lock-keys.test.ts b/test/lock-keys.test.ts
index 9a2379b0ea..75f5b322fe 100644
--- a/test/lock-keys.test.ts
+++ b/test/lock-keys.test.ts
@@ -133,8 +133,10 @@ describe('createEntity advisory lock — transaction scope + key routing', () =>
// Every statement in the TOCTOU window (lock, registry getPage probe,
// putPage) flowed through the tx engine — the xact lock spans them all.
- expect(calls.length).toBeGreaterThanOrEqual(3);
- for (const c of calls) expect(c.onTx).toBe(true);
+ // The maintenance principal lookup runs before the transaction opens.
+ const inWindow = calls.filter((c) => !c.sql?.includes('FROM persistence_brain'));
+ expect(inWindow.length).toBeGreaterThanOrEqual(3);
+ for (const c of inWindow) expect(c.onTx).toBe(true);
expect(calls.map((c) => c.method)).toContain('putPage');
});
diff --git a/test/write-attribution-cycle.test.ts b/test/write-attribution-cycle.test.ts
new file mode 100644
index 0000000000..ac41fcaa42
--- /dev/null
+++ b/test/write-attribution-cycle.test.ts
@@ -0,0 +1,225 @@
+/**
+ * Foundations 2 (Lane C) cycle and synthesis attribution on an unmanaged
+ * brain: the unmanaged writes of the dream provenance stamp, extract_atoms
+ * (completion stamp and stale atom retirement), the drift report, grade_takes
+ * auto-resolution, phantom redirect, consolidate, the dream summary page,
+ * BrainWriter, saved `think` results, extraction receipts and the expiry of
+ * facts whose page was soft-deleted run in maintenanceTransaction. Pages they
+ * write or advance name the local maintenance principal; rows they change keep
+ * their creator and move their last writer.
+ *
+ * Protects the cycle writer family in docs/architecture/system-of-record.md.
+ * Fails if any of those writers runs 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 { stampDreamProvenance } from '../src/core/cycle/dream-provenance.ts';
+import { runPhaseExtractAtoms } from '../src/core/cycle/extract-atoms.ts';
+import { runPhaseDrift } from '../src/core/cycle/drift.ts';
+import { runPhaseGradeTakes } from '../src/core/cycle/grade-takes.ts';
+import { tryRedirectPhantom } from '../src/core/cycle/phantom-redirect.ts';
+import { runPhaseConsolidate } from '../src/core/cycle/phases/consolidate.ts';
+import { __testing as synthesizeTesting } from '../src/core/cycle/synthesize.ts';
+import { runExtractFacts } from '../src/core/cycle/extract-facts.ts';
+import { BrainWriter } from '../src/core/output/writer.ts';
+import { persistSynthesis, type ThinkResult } from '../src/core/think/index.ts';
+import { writeReceipt } from '../src/core/extract/receipt-writer.ts';
+import { renderFactsTable } from '../src/core/facts-fence.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { configureGateway, type ChatResult } 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 { CREATOR_ACTOR, asCreator, revisionActor, rowActors, unmanagedBrain, type Actor, type UnmanagedBrain } from './helpers/unmanaged-attribution.ts';
+
+const engines: BrainEngine[] = [];
+const scratch = mkdtempSync(join(tmpdir(), 'gbrain-write-attribution-cycle-'));
+let closePostgres: (() => Promise<void>) | undefined;
+const quiet = { info() {}, warn() {}, error() {} };
+const VECTOR_TEXT = `[${[1, ...new Array(1535).fill(0)].join(',')}]`;
+
+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 actors = (rows: Array<{ id: number; created: Actor; last: Actor }>) => rows.map(({ created, last }) => ({ created, last }));
+async function creatorPage(brain: UnmanagedBrain, slug: string, page: { type?: string; title?: string; compiled_truth?: string; frontmatter?: Record<string, unknown> } = {}) {
+ return asCreator(brain.engine, tx => tx.putPage(slug, { type: (page.type ?? 'note') as never, title: page.title ?? slug, compiled_truth: page.compiled_truth ?? 'A page.',
+ frontmatter: page.frontmatter ?? {} }, { sourceId: brain.sourceId }));
+}
+const ctx = (brain: UnmanagedBrain): OperationContext => ({ engine: brain.engine, config: { engine: brain.engine.kind } as never, logger: quiet as never,
+ dryRun: false, remote: false, sourceId: brain.sourceId });
+
+describe('cycle and synthesis writers on an unmanaged brain', () => {
+ test('the dream provenance stamp advances the page revision under the maintenance principal', async () => {
+ for (const engine of engines) {
+ const brain = await unmanagedBrain(engine);
+ await creatorPage(brain, 'wiki/dream-output-example');
+ await stampDreamProvenance(engine, [{ slug: 'wiki/dream-output-example', source_id: brain.sourceId }], '2026-09-01');
+ expect(await revisionActor(engine, brain.sourceId, 'wiki/dream-output-example')).toEqual(brain.maintenance);
+ }
+ }, 120_000);
+
+ test('extract_atoms stamps its completed atoms and retires stale atoms under the maintenance principal', async () => {
+ for (const engine of engines) {
+ const brain = await unmanagedBrain(engine);
+ const source = 'writings/essay-example';
+ await creatorPage(brain, source, { compiled_truth: 'A long essay with extractable claims.' });
+ const stale = 'atoms/2026-01-01/retired-example';
+ await creatorPage(brain, stale, { type: 'atom', compiled_truth: 'An older claim.', frontmatter: { type: 'atom', source_slug: source, source_hash: 'aaaaaaaaaaaaaaaa' } });
+ const chat = async (): Promise<ChatResult> => ({
+ text: '[{"title":"Prototypes beat renders","atom_type":"insight","body":"Buyers want tangible prototypes."}]',
+ blocks: [{ type: 'text', text: '' }], stopReason: 'end', model: 'anthropic:claude-haiku-4-5', providerId: 'anthropic',
+ usage: { input_tokens: 500, output_tokens: 200, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ });
+ const [stored] = await engine.executeRaw<{ content_hash: string }>('SELECT content_hash FROM pages WHERE source_id=$1 AND slug=$2', [brain.sourceId, source]);
+
+ const result = await runPhaseExtractAtoms(engine, { sourceId: brain.sourceId, _transcripts: [], _chat: chat as never,
+ _pages: [{ slug: source, content: 'A long essay with extractable claims.', contentHash: stored.content_hash }] });
+
+ expect(result.details?.atoms_extracted).toBe(1);
+ const atoms = await engine.executeRaw<{ slug: string; deleted: boolean }>(`SELECT slug, deleted_at IS NOT NULL AS deleted FROM pages
+ WHERE source_id=$1 AND type='atom' ORDER BY slug`, [brain.sourceId]);
+ expect(atoms.find(atom => atom.slug === stale)?.deleted).toBe(true);
+ for (const atom of atoms) expect(await revisionActor(engine, brain.sourceId, atom.slug)).toEqual(brain.maintenance);
+ }
+ }, 120_000);
+
+ test('the drift report page names the maintenance principal', async () => {
+ for (const engine of engines) {
+ const brain = await unmanagedBrain(engine);
+ const page = await creatorPage(brain, 'people/erin-example', { type: 'person' });
+ await asCreator(engine, async tx => {
+ await tx.addTakesBatch([{ page_id: page.id, row_num: 1, claim: 'Careful operator', kind: 'take', holder: 'world', weight: 0.6 }]);
+ await tx.executeRaw(`INSERT INTO timeline_entries (page_id, date, source, summary) VALUES ($1, '2030-01-15', 'meeting', 'Changed roles')`, [page.id]);
+ });
+ await engine.setConfig('dream.drift.enabled', 'true');
+ await engine.setConfig('models.drift', 'anthropic:claude-sonnet-4-6');
+ const result = await runPhaseDrift(engine, { dryRun: false, cycleDate: '2030-01-20', auditPath: join(scratch, `drift-${brain.sourceId}.jsonl`),
+ judge: async () => ({ drifted: true, confidence: 0.9, reasoning: 'moved' }) });
+ await engine.setConfig('dream.drift.enabled', 'false');
+ expect(result.status).toBe('complete');
+ expect(await revisionActor(engine, 'default', 'reports/drift-2030-01-20')).toEqual(brain.maintenance);
+ }
+ }, 120_000);
+
+ test('grade_takes auto-resolution keeps the take creator and moves its last writer', async () => {
+ for (const engine of engines) {
+ const brain = await unmanagedBrain(engine);
+ const page = await creatorPage(brain, 'people/frank-example', { type: 'person' });
+ await asCreator(engine, tx => tx.addTakesBatch([{ page_id: page.id, row_num: 1, claim: 'Will ship by spring', kind: 'bet', holder: 'world', weight: 0.7, since_date: '2023-01-01' }]));
+ const result = await runPhaseGradeTakes(ctx(brain), { autoResolve: true, autoResolveThreshold: 0.95,
+ judge: async () => ({ verdict: 'incorrect', confidence: 0.99, reasoning: 'contradicted' }), evidenceRetriever: async () => 'example evidence' });
+ expect((result.details as Record<string, unknown>).auto_applied).toBeGreaterThanOrEqual(1);
+ expect(actors(await rowActors(engine, 'takes', 'page_id=$1', [page.id]))).toEqual([{ created: CREATOR_ACTOR, last: brain.maintenance }]);
+ }
+ }, 120_000);
+
+ test('phantom redirect moves the phantom facts, refreshes the canonical body and retires the phantom under the maintenance principal', async () => {
+ for (const engine of engines) {
+ const brain = await unmanagedBrain(engine);
+ const brainDir = join(scratch, `${brain.sourceId}-phantom`);
+ mkdirSync(join(brainDir, 'people'), { recursive: true });
+ const fence = renderFactsTable([{ rowNum: 1, claim: 'Founded the example studio', kind: 'fact', confidence: 1, visibility: 'world', notability: 'high', active: true }] as never);
+ const phantomBody = `# gina\n\n${fence}\n`;
+ await creatorPage(brain, 'people/gina-example', { type: 'person', compiled_truth: '# gina-example\n' });
+ const phantom = await creatorPage(brain, 'gina', { type: 'person', compiled_truth: phantomBody });
+ writeFileSync(join(brainDir, 'gina.md'), phantomBody);
+ writeFileSync(join(brainDir, 'people/gina-example.md'), '# gina-example\n');
+ await asCreator(engine, tx => tx.executeRaw(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, source, row_num, source_markdown_slug)
+ VALUES ($1, 'gina', 'Founded the example studio', 'fact', 'world', 'test', 1, 'gina')`, [brain.sourceId]));
+
+ const stored = (await engine.getPage('gina', { sourceId: brain.sourceId }))!;
+ const result = await withEnv({ GBRAIN_AUDIT_DIR: join(brainDir, '.audit') }, () => tryRedirectPhantom(engine, stored, brain.sourceId, brainDir, false));
+
+ expect(result.outcome).toBe('redirected');
+ expect(actors(await rowActors(engine, 'facts', 'source_id=$1', [brain.sourceId]))).toEqual([{ created: CREATOR_ACTOR, last: brain.maintenance }]);
+ expect(await revisionActor(engine, brain.sourceId, 'people/gina-example')).toEqual(brain.maintenance);
+ const [retired] = await 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 id=$1 AND deleted_at IS NOT NULL`, [phantom.id]);
+ expect(retired).toEqual(brain.maintenance);
+ }
+ }, 120_000);
+
+ test('consolidate stamps the take it writes and the facts it consolidates', async () => {
+ for (const engine of engines) {
+ const brain = await unmanagedBrain(engine);
+ const page = await creatorPage(brain, 'people/hana-example', { type: 'person' });
+ const old = new Date(Date.now() - 30 * 60 * 60 * 1000).toISOString();
+ for (let i = 0; i < 4; i++) {
+ await asCreator(engine, tx => tx.executeRaw(`INSERT INTO facts (source_id, entity_slug, fact, kind, source, valid_from, confidence, embedding, embedded_at, embedding_model, embedded_text_hash)
+ VALUES ($1, 'people/hana-example', $2, 'fact', 'test', $3::timestamptz, 0.9, $4::vector, $3::timestamptz, 'openai:text-embedding-3-large', md5($2))`,
+ [brain.sourceId, `hana fact ${i}`, new Date(Date.parse(old) + i * 1000).toISOString(), VECTOR_TEXT]));
+ }
+ const result = await runPhaseConsolidate(engine, { sourceId: brain.sourceId });
+ expect(result.details.takes_written).toBe(1);
+ expect(actors(await rowActors(engine, 'takes', 'page_id=$1', [page.id]))).toEqual([{ created: brain.maintenance, last: brain.maintenance }]);
+ expect(actors(await rowActors(engine, 'facts', 'source_id=$1', [brain.sourceId])))
+ .toEqual(new Array(4).fill({ created: CREATOR_ACTOR, last: brain.maintenance }));
+ }
+ }, 120_000);
+
+ test('the dream summary page, BrainWriter pages and timeline, a saved think result and an extraction receipt name the maintenance principal', async () => {
+ for (const engine of engines) {
+ const brain = await unmanagedBrain(engine);
+ const brainDir = join(scratch, `${brain.sourceId}-summary`);
+ mkdirSync(brainDir, { recursive: true });
+ const writeSummaryPage = (synthesizeTesting as unknown as { writeSummaryPage: (engine: BrainEngine, brainDir: string, slug: string, date: string,
+ written: string[], children: Array<{ jobId: number; status: string }>, sourceId?: string) => Promise<void> }).writeSummaryPage;
+ await writeSummaryPage(engine, brainDir, 'dream-cycle-summaries/2026-09-02', '2026-09-02', [], [], brain.sourceId);
+ expect(await revisionActor(engine, brain.sourceId, 'dream-cycle-summaries/2026-09-02')).toEqual(brain.maintenance);
+
+ const writer = new BrainWriter(engine, { strictMode: 'off', sourceId: brain.sourceId });
+ const { result: slug } = await writer.transaction(async tx => {
+ const created = await tx.createEntity({ desiredSlug: 'people/ivan-example', displayName: 'Ivan', type: 'person', compiledTruth: 'A person.' });
+ await tx.appendTimeline(created, { date: '2026-09-02', source: 'test', summary: 'Joined the example team' } as never);
+ return created;
+ }, { config: {}, logger: { ...quiet, debug() {} }, requestId: 'lane-c', remote: false } as never);
+ expect(await revisionActor(engine, brain.sourceId, slug)).toEqual(brain.maintenance);
+ expect(actors(await rowActors(engine, 'timeline_entries', 'page_id=(SELECT id FROM pages WHERE source_id=$1 AND slug=$2)', [brain.sourceId, slug])))
+ .toEqual([{ created: brain.maintenance, last: brain.maintenance }]);
+
+ const saved = await persistSynthesis(engine, { question: 'What changed for the example team?', answer: 'The team grew.', citations: [], gaps: [],
+ pagesGathered: 0, takesGathered: 0, graphHits: 0, modelUsed: 'test:stub', rounds: 1, warnings: [], synthesisOk: true } as ThinkResult, { sourceId: brain.sourceId });
+ expect(await revisionActor(engine, brain.sourceId, saved.slug)).toEqual(brain.maintenance);
+
+ const receipt = await writeReceipt(engine, { kind: 'extract_facts', source_id: brain.sourceId, run_id: `run-${brain.sourceId}`, round: 'trial',
+ extracted_at: '2026-09-02T00:00:00.000Z', total_rows: 1, cost_usd: 0 });
+ expect(await revisionActor(engine, brain.sourceId, receipt.slug)).toEqual(brain.maintenance);
+ }
+ }, 120_000);
+
+ test('extract_facts expires the facts of a soft-deleted page, keeping their creator', async () => {
+ for (const engine of engines) {
+ const brain = await unmanagedBrain(engine);
+ const slug = 'people/jo-example';
+ const fence = renderFactsTable([{ rowNum: 1, claim: 'Runs the example lab', kind: 'fact', confidence: 1, visibility: 'world', notability: 'medium', active: true }] as never);
+ await creatorPage(brain, slug, { type: 'person', compiled_truth: `Profile\n\n${fence}` });
+ await asCreator(engine, tx => tx.executeRaw(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, source, row_num, source_markdown_slug)
+ VALUES ($1, $2, 'Runs the example lab', 'fact', 'world', 'test', 1, $2)`, [brain.sourceId, slug]));
+ await asCreator(engine, tx => tx.softDeletePage(slug, { sourceId: brain.sourceId }));
+
+ const result = await runExtractFacts(engine, { sourceId: brain.sourceId, slugs: [] });
+
+ expect(result.factsExpiredForDeletedPages).toBe(1);
+ expect(actors(await rowActors(engine, 'facts', 'source_id=$1', [brain.sourceId]))).toEqual([{ created: CREATOR_ACTOR, last: brain.maintenance }]);
+ }
+ }, 120_000);
+});