Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(f1a): withCoordinatedWrite names the writing actor at every call site
garrytan5a10097ca1b9
diff --git a/scripts/shared-skills/lifecycle-fixture.ts b/scripts/shared-skills/lifecycle-fixture.tsindex ba5a4133fe..98337c4efb 100644--- a/scripts/shared-skills/lifecycle-fixture.ts+++ b/scripts/shared-skills/lifecycle-fixture.ts@@ -10,6 +10,7 @@ import { claimWorktree } from '../../src/core/persistence/ownership.ts';import { activateSharedSkillPersistence } from '../../src/core/persistence/skill-activation.ts';import { declarePersistenceProtocol } from '../../src/core/persistence/protocol.ts';import { withCoordinatedWrite } from '../../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from '../../test/helpers/write-attribution.ts';import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';import { sha256 } from '../../src/core/persistence/digest.ts';import { normalizeSkillFiles, skillMetadata } from '../../src/core/shared-skills/manifest.ts';@@ -114,7 +115,7 @@ export async function createLifecycleFixture(options: { root: string; size: numb}await tx.executeRaw(`INSERT INTO shared_skill_packs(source_id,source_incarnation,pack_id,revision,manifest,manifest_hash)VALUES('default',$1::uuid,$2,$3::uuid,$4::text::jsonb,$5)`, [source.incarnation, PACK_ID, randomUUID(), JSON.stringify(manifest), sha256(manifestContent)]);- });+ }, TEST_WRITE_ATTRIBUTION);});const seed = { count: seeded.length, elapsed_ms: performance.now() - started, canonical_fixture_bytes: canonicalBytes,manifest_bytes: Buffer.byteLength(manifestContent), mode: 'matching filesystem and sealed projection fixtures seeded directly; NOT a measured canonical publication' };diff --git a/src/core/bootstrap/verify.ts b/src/core/bootstrap/verify.tsindex 82e6869ca8..8bcd4cb20b 100644--- a/src/core/bootstrap/verify.ts+++ b/src/core/bootstrap/verify.ts@@ -30,6 +30,7 @@import { managedPersistenceEnabled } from '../persistence/ownership.ts';import { submitPageMutation } from '../persistence/page-mutations.ts';import { withCoordinatedWrite } from '../persistence/context.ts';+import { maintenanceAttribution } from '../persistence/attribution.ts';import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';import { createHash, randomUUID } from 'node:crypto';import { execFileSync } from 'node:child_process';@@ -221,7 +222,10 @@ async function removeProbes(engine: BrainEngine, ws: string, sourceId: string):// must survive verify's cleanup [G13].const sql = `DELETE FROM facts WHERE source_id = $1 AND source_markdown_slug IN ($2, $3)`;const params = [sourceId, VERIFY_PROBE_SLUG, VERIFY_PROBE_ENTITY_SLUG];- if (managed) await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => tx.executeRaw(sql, params)));+ if (managed) {+ const attribution = await maintenanceAttribution(engine);+ await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => tx.executeRaw(sql, params), attribution));+ }else await engine.executeRaw(sql, params);} catch {/* facts table may not exist on a pre-migration brain — doctor_green names that */diff --git a/src/core/cycle/concept-publication.ts b/src/core/cycle/concept-publication.tsindex 70d02fdef6..0d939b7f2b 100644--- a/src/core/cycle/concept-publication.ts+++ b/src/core/cycle/concept-publication.ts@@ -14,6 +14,7 @@ import { TAKES_FENCE_BEGIN, TAKES_FENCE_END, parseTakesFence, stripTakesFence }import { isDbOnly, loadStorageConfig } from '../storage-config.ts';import { publishMaintenancePage, type MaintenanceAuthority } from '../persistence/prepared-maintenance.ts';import { withCoordinatedWrite } from '../persistence/context.ts';+import { maintenanceAttribution } from '../persistence/attribution.ts';/** Error code for a concept held because republication could lose canonical material. */export const CONCEPT_PRESERVATION_CODE = 'concept_preservation_hold';@@ -60,8 +61,9 @@ export async function publishManagedConcept(engine: BrainEngine, authority: Main/** Provenance edges inside a coordinated transaction scoped to the concept's source. */export async function addManagedProvenanceLinks(engine: BrainEngine, sourceId: string, links: LinkBatchInput[]): Promise<number> {+ const attribution = await maintenanceAttribution(engine);return engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () =>- tx.addLinksBatch(links, { auditSite: 'cycle.synthesize_concepts.provenance' }))); // gbrain-allow-direct-insert: concept-provenance edges derived from the synthesis itself, inside the coordinated transaction+ tx.addLinksBatch(links, { auditSite: 'cycle.synthesize_concepts.provenance' }), attribution)); // gbrain-allow-direct-insert: concept-provenance edges derived from the synthesis itself, inside the coordinated transaction}/**diff --git a/src/core/cycle/extract-takes.ts b/src/core/cycle/extract-takes.tsindex 1a2cc4670d..5590dd5365 100644--- a/src/core/cycle/extract-takes.ts+++ b/src/core/cycle/extract-takes.ts@@ -28,6 +28,7 @@ import { parseTakesFence, TAKES_FENCE_BEGIN, type ParsedTake } from '../takes-feimport { walkMarkdownFiles } from '../../commands/extract.ts';import { takesPreparation } from '../takes-write.ts';import { withCoordinatedWrite } from '../persistence/context.ts';+import { maintenanceAttribution } from '../persistence/attribution.ts';import { managedPersistenceEnabled } from '../persistence/ownership.ts';export interface ExtractTakesOpts {@@ -297,6 +298,7 @@ async function reextractCoordinated(rebuild: boolean,result: ExtractTakesResult,): Promise<void> {+ const attribution = await maintenanceAttribution(engine);await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], async () => {await tx.lockPageKeys([{ sourceId, slug }]);const [page] = await tx.executeRaw<{ id: number; compiled_truth: string | null; timeline: string | null }>(@@ -306,7 +308,7 @@ async function reextractCoordinated(const takes = await reconcilePageTakes(tx, page, slug, rebuild, false, result);if (takes.length === 0) return;result.takesUpserted += await tx.addTakesBatch(takes.map(t => takesPreparation.toCanonicalBatchInput(page.id, t)));- }));+ }, attribution));}/** Single-entry dispatch for `gbrain extract takes` and the v0_28_0 orchestrator. */diff --git a/src/core/page-state/materialize.ts b/src/core/page-state/materialize.tsindex ce7e7d541f..9584498bf8 100644--- a/src/core/page-state/materialize.ts+++ b/src/core/page-state/materialize.ts@@ -2,11 +2,13 @@ import type { BrainEngine } from '../engine.ts';import { contentHash } from '../utils.ts';import { assertPageRevision, type PageSnapshot } from './types.ts';import { withCoordinatedWrite } from '../persistence/context.ts';+import { maintenanceAttribution } from '../persistence/attribution.ts';/** Persist an effective withdrawal overlay without inventing a second logical edit. */export async function materializePageSnapshot(engine: BrainEngine, snapshot: PageSnapshot): Promise<void> {const sourceId = snapshot.page.source_id;const slug = snapshot.page.slug;+ const attribution = await maintenanceAttribution(engine);await engine.transaction(async tx => {await tx.lockPageKeys([{ sourceId, slug }]);const current = await tx.readPageSnapshot(slug, { sourceId, includeDeleted: true });@@ -19,7 +21,7 @@ export async function materializePageSnapshot(engine: BrainEngine, snapshot: Pagconst page = current.page;await withCoordinatedWrite(tx, [sourceId], () => tx.executeRaw(`UPDATE pages SET compiled_truth=$1,timeline=$2,content_hash=$3WHERE id=$4 AND knowledge_revision=$5::uuid`,- [page.compiled_truth, page.timeline, contentHash({ ...page, tags: current.tags }), page.id, current.revision]));+ [page.compiled_truth, page.timeline, contentHash({ ...page, tags: current.tags }), page.id, current.revision]), attribution);await tx.executeRaw("SELECT set_config('gbrain.materializing_revision',$1,true)", [previous[0]?.revision ?? '']);});}diff --git a/src/core/persistence/attribution.ts b/src/core/persistence/attribution.tsnew file mode 100644index 0000000000..3952508b65--- /dev/null+++ b/src/core/persistence/attribution.ts@@ -0,0 +1,38 @@+import { OperationError } from '../ops/contract.ts';+import { currentVerifiedLocalWriter, localHostId, readLocalWriter } from './identity.ts';+import type { Principal, SqlEngine, WriteRequest } from './model.ts';++/**+ * The actor the database stamps on rows written inside withCoordinatedWrite+ * or withWriteAttribution. `requestId` is persistence_requests.id (globally+ * unique), or null for a maintenance write with no journal request.+ */+export interface WriteAttribution { requestId: string | null; principal: Principal; }++export { withWriteAttribution } from './context.ts';++/** A journaled request publishes as itself. */+export function requestAttribution(row: Pick<WriteRequest, 'id' | 'principal_kind' | 'principal_id'>): WriteAttribution {+ return { requestId: row.id, principal: { kind: row.principal_kind, id: row.principal_id } };+}++/** A write by a known principal that has no journal request (manual links, source lifecycle). */+export function principalAttribution(principal: Principal): WriteAttribution {+ return { requestId: null, principal };+}++/**+ * The executing maintenance principal: the verified local writer of this call+ * (server-side owner work), else this installation's local CLI registration,+ * else the host itself when the installation has no usable registration.+ */+export async function maintenanceAttribution(engine: SqlEngine): Promise<WriteAttribution> {+ const verified = currentVerifiedLocalWriter();+ if (verified) return principalAttribution(verified.principal);+ try {+ return principalAttribution({ kind: 'local_cli', id: (await readLocalWriter(engine, 'cli')).id });+ } catch (error) {+ if (!(error instanceof OperationError) || !['writer_registration_required', 'permission_denied'].includes(error.code)) throw error;+ return principalAttribution({ kind: 'application', id: `host:${localHostId()}` });+ }+}diff --git a/src/core/persistence/connector-path.ts b/src/core/persistence/connector-path.tsindex 689d3d65e2..a9308b3481 100644--- a/src/core/persistence/connector-path.ts+++ b/src/core/persistence/connector-path.ts@@ -2,6 +2,7 @@ import type { BrainEngine } from '../engine.ts';import { OperationError } from '../ops/contract.ts';import { isConnectorSourceKind } from './connector-identity.ts';import { withCoordinatedWrite } from './context.ts';+import { maintenanceAttribution } from './attribution.ts';/*** `gbrain sources set-path <id> --clear` (#5673): clear a connector source's@@ -29,7 +30,7 @@ export async function clearConnectorLocalPath(engine: BrainEngine, sourceId: strif (source.local_path === null) return { prior: null };const [brain] = await tx.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton=1');const clear = () => tx.executeRaw('UPDATE sources SET local_path=NULL WHERE id=$1 AND incarnation=$2::uuid', [sourceId, source.incarnation]);- if (brain?.enabled) await withCoordinatedWrite(tx, [sourceId], clear);+ if (brain?.enabled) await withCoordinatedWrite(tx, [sourceId], clear, await maintenanceAttribution(tx));else await clear();return { prior: source.local_path };});diff --git a/src/core/persistence/connector-sync.ts b/src/core/persistence/connector-sync.tsindex c2c58b3e50..4cc793b20d 100644--- a/src/core/persistence/connector-sync.ts+++ b/src/core/persistence/connector-sync.ts@@ -38,6 +38,7 @@ import { FACTS_FENCE_BEGIN } from '../facts-fence.ts';import { TAKES_FENCE_BEGIN } from '../takes-fence.ts';import { readJournalLimits } from './limits.ts';import { withCoordinatedWrite } from './context.ts';+import { maintenanceAttribution } from './attribution.ts';import { readConnectorV2Cutoff } from './connector-checkpoint-migration.ts';import type { GoogleSourceConfig } from '../google/types.ts';@@ -524,11 +525,12 @@ export class ManagedConnectorSync {}/** E-D4: the freshness a skipped checkpoint save would have stamped, guarded by the lease and the source incarnation. */private async stampFreshness(newestContentAt?: string): Promise<void> {+ const attribution = await maintenanceAttribution(this.engine);await this.engine.transaction(async tx => {await this.assertLease(tx);await withCoordinatedWrite(tx, [this.sourceId], () => tx.executeRaw('UPDATE sources SET last_sync_at=now(),newest_content_at=COALESCE($3::timestamptz,newest_content_at) WHERE id=$1 AND incarnation=$2::uuid',- [this.sourceId, this.source.incarnation, newestContentAt ?? null]));+ [this.sourceId, this.source.incarnation, newestContentAt ?? null]), attribution);});}/** The run's remaining wait allowance; the caller's own deadline arrives through the lease signal. */diff --git a/src/core/persistence/context.ts b/src/core/persistence/context.tsindex d8763f7722..1a3b6d4a8b 100644--- a/src/core/persistence/context.ts+++ b/src/core/persistence/context.ts@@ -1,28 +1,56 @@import { AsyncLocalStorage } from 'node:async_hooks';import type { BrainEngine } from '../engine.ts';import { OperationError } from '../ops/contract.ts';+import type { WriteAttribution } from './attribution.ts';interface PublicationContext { brainId: string; sourceIds: ReadonlySet<string>; active: boolean; }const publication = new AsyncLocalStorage<PublicationContext>();-/** Only the coordinator and guarded projection workers establish this execution capability. */-export async function withCoordinatedWrite<T>(engine: BrainEngine, sourceIds: string[], fn: () => Promise<T>): Promise<T> {+const ATTRIBUTION_SETTINGS = ['gbrain.write_request', 'gbrain.write_principal_kind', 'gbrain.write_principal_id'] as const;++/**+ * Sets transaction-local settings around `fn` in one round trip each way. An+ * aborted transaction cannot accept statements; its rollback clears SET LOCAL+ * automatically. A success restores the enclosing values.+ */+async function withTransactionSettings<T>(engine: Pick<BrainEngine, 'executeRaw'>, names: readonly string[],+ next: (previous: string[]) => string[], fn: () => Promise<T>): Promise<T> {+ const [row] = await engine.executeRaw<Record<string, string | null>>(+ `SELECT ${names.map((name, index) => `current_setting('${name}',true) AS s${index}`).join(',')}`);+ const previous = names.map((_, index) => row?.[`s${index}`] ?? '');+ const apply = (values: string[]) => engine.executeRaw(+ `SELECT ${names.map((name, index) => `set_config('${name}',$${index + 1},true)`).join(',')}`, values);+ await apply(next(previous));+ let failed = false;+ try { return await fn(); }+ catch (error) { failed = true; throw error; }+ finally {+ try { await apply(previous); }+ catch (error) { if (!failed) throw error; }+ }+}+/** A nested scope keeps the outer actor: a request publication that calls a derived writer stays attributed to the request. */+const attributionValues = (outer: string[], attribution: WriteAttribution) => outer[1]+ ? outer : [attribution.requestId ?? '', attribution.principal.kind, attribution.principal.id];++/**+ * Only the coordinator and guarded projection workers establish this execution+ * capability. `attribution` names the actor the database stamps on every+ * content row and page revision written inside (persistence/attribution-schema.ts).+ */+export async function withCoordinatedWrite<T>(engine: BrainEngine, sourceIds: string[], fn: () => Promise<T>, attribution: WriteAttribution): Promise<T> {const [brain] = await engine.executeRaw<{ brain_id: string }>('SELECT brain_id FROM persistence_brain WHERE singleton=1');if (!brain) throw new OperationError('writer_not_initialized', 'Persistence identity is missing.');const context: PublicationContext = { brainId: brain.brain_id, sourceIds: new Set(sourceIds), active: true };- const [previous] = await engine.executeRaw<{ value: string | null }>("SELECT current_setting('gbrain.write_sources',true) AS value");- await engine.executeRaw("SELECT set_config('gbrain.write_sources',$1,true)", [JSON.stringify(sourceIds)]);- return publication.run(context, async () => {- let failed = false;- try { return await fn(); }- catch (error) { failed = true; throw error; }- finally {- context.active = false;- // An aborted transaction cannot accept statements; its rollback clears- // SET LOCAL automatically. A success restores the enclosing capability.- try { await engine.executeRaw("SELECT set_config('gbrain.write_sources',$1,true)", [previous?.value ?? '']); }- catch (error) { if (!failed) throw error; }- }- });+ return withTransactionSettings(engine, ['gbrain.write_sources', ...ATTRIBUTION_SETTINGS],+ ([, ...outer]) => [JSON.stringify(sourceIds), ...attributionValues(outer, attribution)],+ () => publication.run(context, async () => {+ try { return await fn(); }+ finally { context.active = false; }+ }));+}+/** Attribution without coordinator capability, for unmanaged legacy transactions. */+export function withWriteAttribution<T>(engine: Pick<BrainEngine, 'executeRaw'>, attribution: WriteAttribution, fn: () => Promise<T>): Promise<T> {+ return withTransactionSettings(engine, ATTRIBUTION_SETTINGS, outer => attributionValues(outer, attribution), fn);}export async function assertCoordinatedWrite(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string): Promise<void> {const [brain] = await engine.executeRaw<{ brain_id: string; enabled: boolean }>('SELECT brain_id,enabled FROM persistence_brain WHERE singleton=1');diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.tsindex d116634461..cc6b8f2606 100644--- a/src/core/persistence/coordinator.ts+++ b/src/core/persistence/coordinator.ts@@ -13,6 +13,7 @@ import { clearResolvedRecovery, completeWrite, getWriteRequestById, lockCountersimport { isTerminal, principalKey, requestPrincipal, recoveryFiles, type RecoveryRecord, type WriteRequest } from './model.ts';import type { NativeLockHandle } from './native-lock.ts';import { withCoordinatedWrite } from './context.ts';+import { requestAttribution } from './attribution.ts';import { withFilesystemPublication } from './filesystem-guard.ts';import { mayReprepare } from './semantic.ts';import { tryAcquirePublicationCapacity } from './pool-capacity.ts';@@ -238,7 +239,7 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, pr});await hooks.boundary?.('after_publication', row);}- const outcome = await withCoordinatedWrite(tx, [row.source_id], () => prepared.apply(tx));+ const outcome = await withCoordinatedWrite(tx, [row.source_id], () => prepared.apply(tx), requestAttribution(row));if (!skill) await classifyUnboundPage(tx, row);if (prepared.databaseOnlyReason === 'mirror_read_only') await classifyMirrorPage(tx, row);const final = skill ? null : await tx.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });diff --git a/src/core/persistence/database-write.ts b/src/core/persistence/database-write.tsindex b9af502fde..19d301e516 100644--- a/src/core/persistence/database-write.ts+++ b/src/core/persistence/database-write.ts@@ -5,6 +5,7 @@ import { authorizeWrite, submissionAuthority } from './authority.ts';import { managedPersistenceEnabled } from './ownership.ts';import { initializeLocalPersistence } from './page-mutations.ts';import { withCoordinatedWrite } from './context.ts';+import { principalAttribution } from './attribution.ts';/*** A coordinated, database-only write on a managed brain: rows with no@@ -34,6 +35,6 @@ export async function coordinatedDatabaseWrite<T>(ctx: OperationContext, operatiawait authorizeWrite(tx, authority, operation, authoritySlug, true);await tx.lockPageKeys(lockSlugs.map(slug => ({ sourceId, slug })));return write(tx, sourceId);- }));+ }, principalAttribution(authority.principal)));return { value };}diff --git a/src/core/persistence/derived-facts.ts b/src/core/persistence/derived-facts.tsindex 450a730391..f742fb1090 100644--- a/src/core/persistence/derived-facts.ts+++ b/src/core/persistence/derived-facts.ts@@ -2,6 +2,7 @@ import type { BrainEngine, NewFact } from '../engine.ts';import { OperationError } from '../ops/contract.ts';import { currentSubmissionAuthority } from '../minions/submission-authority.ts';import { withCoordinatedWrite } from './context.ts';+import { maintenanceAttribution } from './attribution.ts';import { currentVerifiedLocalWriter } from './identity.ts';import { managedPersistenceEnabled } from './ownership.ts';import { assertPersistenceAccepting } from './service.ts';@@ -32,12 +33,13 @@ export async function managedDerivedFactsPreflight(engine: BrainEngine, sourceId*/export async function withDerivedFactsWrite<T>(engine: BrainEngine, sourceId: string, slugs: readonly string[],fn: (tx: BrainEngine) => Promise<T>): Promise<T> {+ const attribution = await maintenanceAttribution(engine);return engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], async () => {const [source] = await tx.executeRaw<{ archived: boolean }>('SELECT archived FROM sources WHERE id=$1 FOR SHARE', [sourceId]);if (!source || source.archived) throw new OperationError('source_changed', 'The fact maintenance source changed during extraction; nothing was written.');await tx.lockPageKeys(slugs.map(slug => ({ sourceId, slug })));return fn(tx);- }));+ }, attribution));}/**diff --git a/src/core/persistence/links-maintenance.ts b/src/core/persistence/links-maintenance.tsindex dd1aa3423e..60c6e6fb78 100644--- a/src/core/persistence/links-maintenance.ts+++ b/src/core/persistence/links-maintenance.ts@@ -2,6 +2,7 @@ import type { BrainEngine } from '../engine.ts';import { LINK_EXTRACTOR_VERSION_TS } from '../link-extraction.ts';import { prepareAutomaticLinks } from './links-preparation.ts';import { withCoordinatedWrite } from './context.ts';+import { maintenanceAttribution } from './attribution.ts';import { unrecordedCanonicalTimeline } from './canonical-projections.ts';export interface ManagedLinkExtraction { pages: number; created: number; removed: number; timeline: number; skipped: number; remaining: number; }@@ -51,6 +52,7 @@ export async function extractManagedStaleLinks(engine: BrainEngine,const versionTs = LINK_EXTRACTOR_VERSION_TS;const maxPages = opts.maxPages ?? Infinity;const done = new Set<string>();+ const attribution = await maintenanceAttribution(engine);const derive = async (slug: string, sourceId: string, stamp?: string) => {opts.signal?.throwIfAborted();done.add(`${sourceId}\0${slug}`);@@ -73,7 +75,7 @@ export async function extractManagedStaleLinks(engine: BrainEngine,const at = stamp ?? new Date().toISOString();await tx.markPagesExtractedBatch([{ slug, source_id: sourceId, extractedAt: at }], at);return { ...written, timeline: added };- }));+ }, attribution));if (!outcome) { result.skipped++; return; }result.pages++;result.created += outcome.created;diff --git a/src/core/persistence/memory-mutations.ts b/src/core/persistence/memory-mutations.tsindex 2f9a1ead01..e19d0924ae 100644--- a/src/core/persistence/memory-mutations.ts+++ b/src/core/persistence/memory-mutations.ts@@ -17,6 +17,7 @@ import { resolveFactWriteTarget } from './fact-write-target.ts';import { WRITER_INSPECTION_HINT } from './admin-intent.ts';import { parseMutationPrecondition } from './preconditions.ts';import { withCoordinatedWrite } from './context.ts';+import { requestAttribution } from './attribution.ts';import { isTerminal, type WriteRequest } from './model.ts';import { prepareMemoryMutation } from './memory-prepare.ts';import { retryWriteAdmission } from './admission-retry.ts';@@ -212,7 +213,7 @@ export async function submitForgetMutation(ctx: OperationContext, operation: 'fo? { id: rawId, expired: fact.expired_at === null, reason, protocol_version: 1 }: { id, expired: true, path: 'legacy_db', reason: reason ?? 'forgotten' };return completeWrite(tx, row, 'committed', { ...outcome, persistence: { mode: 'database' } });- });+ }, requestAttribution(row));}));// The commit removed the withdrawn pages' chunks. Rebuild them before// acknowledging: a CLI process exits without a resident projection worker.diff --git a/src/core/persistence/source-lifecycle.ts b/src/core/persistence/source-lifecycle.tsindex 710f374d3f..7dc459bdda 100644--- a/src/core/persistence/source-lifecycle.ts+++ b/src/core/persistence/source-lifecycle.ts@@ -17,6 +17,7 @@ import { advanceTopology, lockTopologyPrincipal, lockTopologyRows, settleTopologimport { priorTopologyChange, recordTopologyChange, topologyReceipt } from './topology-receipts.ts';import { isWriteRequestId } from './types.ts';import { withCoordinatedWrite } from './context.ts';+import { principalAttribution } from './attribution.ts';import { managedFilesystemDatastorePath, refreshManagedFilesystemRoots } from './filesystem-guard.ts';import { canonicalFilesystemPath, nativeFilesystemPath } from './root-registry.ts';import { flushTopologyDirectory } from './topology-filesystem.ts';@@ -214,7 +215,7 @@ export async function runManagedSourceLifecycle(engine:BrainEngine,input:SourceL...(missingCheckout?{retired_without_checkout:missingCheckout}:{}),...(root?{local_path:root.source}:{}),...(['remove','purge'].includes(input.operation)?{storage_retained:true,local_path:ownedSourcePath??null,pages_deleted:pagesDeleted}:{}),...(input.operation==='add'?{name:input.name??source?.name??input.sourceId,config:redactSourceConfig({...source?.config,...input.config}),id:input.sourceId}: {})};- });+ },principalAttribution({kind:'local_cli',id:principal}));if(admission) await admission.after(tx,String(result.source_incarnation));const row=await recordTopologyChange(tx,{principal,requestId,intent,operation:input.operation,sourceId:input.sourceId,incarnation:source?.incarnation??String(result.source_incarnation),worktrees},result);return topologyReceipt(row);diff --git a/src/core/persistence/topology-recovery.ts b/src/core/persistence/topology-recovery.tsindex f9a17ed68f..428652753f 100644--- a/src/core/persistence/topology-recovery.ts+++ b/src/core/persistence/topology-recovery.ts@@ -10,6 +10,7 @@ import { localHostId } from './identity.ts';import { compactStoredManifest, worktreeManifest } from './ownership.ts';import { advanceTopology, lockTopologyPrincipal, settleTopologyRequests, topologyCanonicalStamp, withTopologyLocks } from './topology-locks.ts';import { withCoordinatedWrite } from './context.ts';+import { principalAttribution } from './attribution.ts';import { releaseTopologyReservation, type TopologyChange } from './topology-receipts.ts';import type { TopologyCloneRecovery } from './topology-clone-model.ts';import type { CloneLifecycleHooks } from './topology-clone.ts';@@ -146,7 +147,7 @@ export async function finishTopologyClone(engine:BrainEngine,id:string,hooks:Cloif(record.operation==='add')await tx.executeRaw('INSERT INTO sources(id,name,local_path,config,incarnation) VALUES($1,$2,$3,$4::text::jsonb,$5::uuid)',[record.sourceId,record.input.name??record.sourceId,record.target,JSON.stringify({...record.input.config,remote_url:record.input.remoteUrl,managed_clone:true}),record.incarnation]);else await tx.executeRaw('UPDATE sources SET last_commit=NULL,last_sync_at=NULL WHERE id=$1 AND incarnation=$2::uuid',[record.sourceId,record.incarnation]);- });+ },principalAttribution({kind:'local_cli',id:row.principal_id}));await advanceTopology(tx,[record.worktreeId]);await tx.executeRaw('UPDATE persistence_worktrees SET manifest=$2::text::jsonb WHERE id=$1::uuid',[record.worktreeId,JSON.stringify({...(record.manifest?compactStoredManifest(record.manifest):null),canonical_stamp:await topologyCanonicalStamp(tx,record.worktreeId)})]);await refreshManagedFilesystemRoots(tx,managedFilesystemDatastorePath(engine));diff --git a/src/core/shared-skills/publication.ts b/src/core/shared-skills/publication.tsindex e5686ee761..2563fb0ba8 100644--- a/src/core/shared-skills/publication.ts+++ b/src/core/shared-skills/publication.ts@@ -16,6 +16,7 @@ import type { PreparedMutation } from '../persistence/coordinator.ts';import type { WriteAuthority, WriteRequest } from '../persistence/model.ts';import { localHostId } from '../persistence/identity.ts';import { withCoordinatedWrite } from '../persistence/context.ts';+import { requestAttribution } from '../persistence/attribution.ts';import { normalizeSkillFiles, skillMetadata, skillName, skillPath } from './manifest.ts';import { assertSkillCapability, assertStoredSkillCapability, publicationEnabled, readSharedSkillPolicy, setSharedSkillPolicy } from './policy.ts';import { SHARED_SKILL_LIMITS, type SharedSkillFile, type SharedSkillPolicy, type SharedSkillPutInput, type SkillMetadata, type StoredSkillFile, type StoredSkillRevision } from './model.ts';@@ -364,7 +365,7 @@ export async function prepareSharedSkillMutation(engine: BrainEngine, row: WriteWHERE source_id=$1 AND source_incarnation=$2::uuid AND pack_id=$3 AND name=$4 FOR UPDATE`, [row.source_id, row.source_incarnation, intent.pack_id, target.name]);if ((head?.revision ?? null) !== target.revision) throw new OperationError('revision_conflict', 'A skill in the dependency closure changed.');}- prunedRevisions = await withCoordinatedWrite(tx, [row.source_id], () => pruneSharedSkillRevisionsInTransaction(tx, row.source_id, row.source_incarnation));+ prunedRevisions = await withCoordinatedWrite(tx, [row.source_id], () => pruneSharedSkillRevisionsInTransaction(tx, row.source_id, row.source_incarnation), requestAttribution(row));const capacity = await sharedSkillRetentionCapacity(tx, row.source_id, row.source_incarnation);const [incoming] = await tx.executeRaw<{ bytes: number | string }>(`SELECT COALESCE(SUM(octet_length(r.metadata::text)+octet_length(r.files::text)),0) AS bytesFROM jsonb_to_recordset($1::text::jsonb) AS r(metadata jsonb,files jsonb)`, [JSON.stringify(revisions)]);diff --git a/src/core/shared-skills/retention.ts b/src/core/shared-skills/retention.tsindex dca079d5be..a7129b74e4 100644--- a/src/core/shared-skills/retention.ts+++ b/src/core/shared-skills/retention.ts@@ -3,6 +3,7 @@ import type { BrainEngine } from '../engine.ts';import { OperationError, type OperationContext } from '../ops/contract.ts';import { declarePersistenceProtocol } from '../persistence/protocol.ts';import { withCoordinatedWrite } from '../persistence/context.ts';+import { maintenanceAttribution } from '../persistence/attribution.ts';import { initializeLocalPersistence, requestPrincipalForContext } from '../persistence/page-mutations.ts';import { requireUuid } from '../persistence/digest.ts';import { skillName } from './manifest.ts';@@ -128,6 +129,7 @@ export async function getSharedSkillRetention(ctx: OperationContext, sourceId =}export async function pruneSharedSkillRevisions(ctx: OperationContext, sourceId = ctx.sourceId) {const incarnation = await operatorSource(ctx, sourceId);+ const attribution = await maintenanceAttribution(ctx.engine);return ctx.engine.transaction(async tx => {await declarePersistenceProtocol(tx);const [source] = await tx.executeRaw<{ incarnation: string }>('SELECT incarnation FROM sources WHERE id=$1 FOR UPDATE', [sourceId]);@@ -135,7 +137,7 @@ export async function pruneSharedSkillRevisions(ctx: OperationContext, sourceIdreturn withCoordinatedWrite(tx, [sourceId], async () => {const count = await pruneSharedSkillRevisionsInTransaction(tx, sourceId, incarnation);return { ...await sharedSkillRetentionStatus(tx, sourceId, incarnation), pruned_revisions: count };- });+ }, attribution);});}export async function retainSharedSkillRevision(ctx: OperationContext, params: { source_id?: string; source_incarnation: string; pack_id: string; name: string; revision: string; hours?: number }) {diff --git a/src/core/timeline-extract.ts b/src/core/timeline-extract.tsindex d4c359c8f5..930b160317 100644--- a/src/core/timeline-extract.ts+++ b/src/core/timeline-extract.ts@@ -163,12 +163,14 @@ export interface TimelineOrphanPruneResult {*/async function retractCoordinated(engine: BrainEngine, pageId: number, slug: string, sourceId: string) {const { withCoordinatedWrite } = await import('./persistence/context.ts');+ const { maintenanceAttribution } = await import('./persistence/attribution.ts');+ const attribution = await maintenanceAttribution(engine);return engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], async () => {await tx.lockPageKeys([{ sourceId, slug }]);const [page] = await tx.executeRaw<{ compiled_truth: string; timeline: string | null }>('SELECT compiled_truth, timeline FROM pages WHERE id = $1 AND deleted_at IS NULL', [pageId]);return page ? retractRemovedTimelineEntries(tx, slug, sourceId, `${page.compiled_truth}\n${page.timeline ?? ''}`) : [];- }));+ }, attribution));}/**diff --git a/test/agent-install-backup.serial.test.ts b/test/agent-install-backup.serial.test.tsindex 6d0020f36a..86a41aa9e3 100644--- a/test/agent-install-backup.serial.test.ts+++ b/test/agent-install-backup.serial.test.ts@@ -13,6 +13,7 @@ import { writeBackupArchive } from '../src/core/backup/archive.ts';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import type { BrainEngine } from '../src/core/engine.ts';import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';import { MinionQueue } from '../src/core/minions/queue.ts';import { acquireLock, releaseLock, PgliteBusyError } from '../src/core/pglite-lock.ts';import { withEnv } from './helpers/with-env.ts';@@ -31,7 +32,7 @@ async function withBrain<T>(at: string, fn: (engine: PGLiteEngine) => Promise<T>}async function withFixtureWrite<T>(at: string, sourceIds: string[], fn: (engine: BrainEngine) => Promise<T>): Promise<T> {- return withBrain(at, engine => engine.transaction(tx => withCoordinatedWrite(tx, sourceIds, () => fn(tx))));+ return withBrain(at, engine => engine.transaction(tx => withCoordinatedWrite(tx, sourceIds, () => fn(tx), TEST_WRITE_ATTRIBUTION)));}async function launched(args: string[], at = root): Promise<string> {diff --git a/test/backup-portability-native.serial.test.ts b/test/backup-portability-native.serial.test.tsindex 24ac2ad5fc..97e31a2514 100644--- a/test/backup-portability-native.serial.test.ts+++ b/test/backup-portability-native.serial.test.ts@@ -13,6 +13,7 @@ import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { getEmbeddingDimensions } from '../src/core/ai/gateway.ts';import { MinionQueue } from '../src/core/minions/queue.ts';import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';import { acquireLock, releaseLock } from '../src/core/pglite-lock.ts';import * as privacy from '../src/core/backup/private-path.ts';@@ -169,7 +170,7 @@ beforeAll(async () => {await tx.setConfig('sync.repo_path', join(root, 'memory', 'nested'));await tx.setConfig('mcp.skills_dir', join(root, 'instructions', 'nested'));await tx.setConfig('connectors.chatgpt.auto_sync', 'true');- }));+ }, TEST_WRITE_ATTRIBUTION));const queue = new MinionQueue(engine);await queue.add('subagent', { fixture: 'unfinished' }, {}, { allowProtectedSubmit: true });const completed = await queue.add('subagent', { fixture: 'completed' }, {}, { allowProtectedSubmit: true });diff --git a/test/canonical-projection-history.test.ts b/test/canonical-projection-history.test.tsindex 6080762be3..37bc4ef511 100644--- a/test/canonical-projection-history.test.ts+++ b/test/canonical-projection-history.test.ts@@ -9,6 +9,7 @@ import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { parseMarkdown } from '../src/core/markdown.ts';import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';import { claimWorktree } from '../src/core/persistence/ownership.ts';import { performManagedSync } from '../src/core/persistence/sync-run.ts';@@ -54,7 +55,7 @@ async function fixture(run: (f: Fixture) => Promise<void>) {const ctx = { engine, sourceId, remote: false as const, config: { engine: engine.kind, embedding_disabled: true },dryRun: false, logger: { info() {}, warn() {}, error() {} } };const coordinated = (sql: string, params: unknown[]) =>- engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => tx.executeRaw(sql, params)));+ engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => tx.executeRaw(sql, params), TEST_WRITE_ATTRIBUTION));const f: Fixture = {engine, sourceId,put: (slug, content, extra = {}) => submitPageMutation(ctx, { operation: 'put_page', params: { slug, content, request_id: randomUUID(), ...extra } }),@@ -124,7 +125,7 @@ describe('#5567 coordinated writes keep database-only timeline history', () => {await f.put('projects/example', page('Draft.', '- **2026-08-01** | markdown — Launch review'));const pageId = await f.pageId('projects/example');await f.engine.transaction(tx => withCoordinatedWrite(tx, [f.sourceId], () => tx.executeRaw(- `UPDATE timeline_entries SET summary='Launch review ' WHERE page_id=$1`, [pageId])));+ `UPDATE timeline_entries SET summary='Launch review ' WHERE page_id=$1`, [pageId]), TEST_WRITE_ATTRIBUTION));await f.put('projects/example', page('Draft without the bullet.'), { expected_revision: await f.revision('projects/example') });expect(await f.timeline('projects/example')).toEqual([]);});@@ -135,7 +136,7 @@ describe('#5567 coordinated writes keep database-only timeline history', () => {await f.put('projects/example', page('Draft.', '- **2026-08-01** | markdown — Launch review'));const pageId = await f.pageId('projects/example');await f.engine.transaction(tx => withCoordinatedWrite(tx, [f.sourceId], () => tx.executeRaw(- `UPDATE timeline_entries SET summary='Launch review ' WHERE page_id=$1`, [pageId])));+ `UPDATE timeline_entries SET summary='Launch review ' WHERE page_id=$1`, [pageId]), TEST_WRITE_ATTRIBUTION));await f.put('projects/example', page('Edited draft.', '- **2026-08-01** | markdown — Launch review'), { force: true });expect(await f.timeline('projects/example')).toEqual([{ date: '2026-08-01', source: 'markdown', summary: 'Launch review', detail: '' }]);});@@ -163,8 +164,8 @@ describe('#5567 coordinated writes keep database-only timeline history', () => {await tx.executeRaw(`INSERT INTO timeline_entries(page_id,date,source,summary,detail) VALUES($1,'2026-08-01','markdown','Removed later','recreated')`, [pageId]);await tx.executeRaw(`UPDATE timeline_entries SET detail='concurrent detail' WHERE page_id=$1 AND summary='Kept bullet'`, [pageId]);await tx.executeRaw(`INSERT INTO timeline_entries(page_id,date,source,summary,detail) VALUES($1,'2026-08-03','','Arrived mid-flight','')`, [pageId]);- }));- await f.engine.transaction(tx => withCoordinatedWrite(tx, [f.sourceId], () => project(tx)));+ }, TEST_WRITE_ATTRIBUTION));+ await f.engine.transaction(tx => withCoordinatedWrite(tx, [f.sourceId], () => project(tx), TEST_WRITE_ATTRIBUTION));expect(await f.timeline(slug)).toEqual([{ date: '2026-08-01', source: 'markdown', summary: 'Removed later', detail: 'recreated' },{ date: '2026-08-02', source: 'markdown', summary: 'Kept bullet', detail: 'concurrent detail' },@@ -181,10 +182,10 @@ describe('#5567 coordinated writes keep database-only timeline history', () => {await f.legacyTimeline(slug, legacy);const snapshot = await f.engine.readPageSnapshot(slug, { sourceId: f.sourceId, includeDeleted: true });const project = await prepareCanonicalProjections(f.engine, parseMarkdown(page(`Next for ${writer}.`), slug), slug, f.sourceId, snapshot, writer);- await f.engine.transaction(tx => withCoordinatedWrite(tx, [f.sourceId], () => project(tx)));+ await f.engine.transaction(tx => withCoordinatedWrite(tx, [f.sourceId], () => project(tx), TEST_WRITE_ATTRIBUTION));expect(await f.timeline(slug)).toEqual([legacy]);await f.engine.transaction(tx => withCoordinatedWrite(tx, [f.sourceId], () => tx.executeRaw(- 'DELETE FROM timeline_entries WHERE page_id=$1', [snapshot!.page.id])));+ 'DELETE FROM timeline_entries WHERE page_id=$1', [snapshot!.page.id]), TEST_WRITE_ATTRIBUTION));}});});@@ -211,7 +212,7 @@ describe('#5567 managed sync keeps database-only timeline history', () => {await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');await performManagedSync(engine, { sourceId, noPull: true });await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => tx.executeRaw(`INSERT INTO timeline_entries(page_id,date,source,summary,detail)- SELECT id,$3::date,$4,$5,$6 FROM pages WHERE source_id=$1 AND slug=$2`, [sourceId, 'projects/example', legacy.date, legacy.source, legacy.summary, legacy.detail])));+ SELECT id,$3::date,$4,$5,$6 FROM pages WHERE source_id=$1 AND slug=$2`, [sourceId, 'projects/example', legacy.date, legacy.source, legacy.summary, legacy.detail]), TEST_WRITE_ATTRIBUTION));const edited = page('Edited draft.', '- **2026-08-02** | markdown — Follow-up');writeFileSync(file, edited); commit(root);expect(await performManagedSync(engine, { sourceId, noPull: true })).toMatchObject({ status: 'synced' });diff --git a/test/company-brain-runtime.test.ts b/test/company-brain-runtime.test.tsindex 97c05e215b..d094294a79 100644--- a/test/company-brain-runtime.test.ts+++ b/test/company-brain-runtime.test.ts@@ -18,6 +18,7 @@ import { performSync } from '../src/commands/sync.ts';import { purgeStaleCheckpoints } from '../src/core/op-checkpoint.ts';import { submitEmbedBackfill } from '../src/core/embed-backfill-submit.ts';import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';import { makeGitFixture } from './helpers/git-fixture.ts';import * as verification from '../src/core/company-brain/verification.ts';@@ -202,7 +203,7 @@ for (const managed of [false, true]) describe(`company source lifecycle ${manageconst input = { brainId: 'company-example', sourceId: `company-${randomUUID().slice(0, 8)}`, path: root,plan: await inspectCompanyBrain({ path: root, profile: 'company-brain' }), remote: false, requestId: randomUUID() };expect((await connectCompanyBrain(engine, input)).ok).toBe(true);- await engine.transaction(tx => withCoordinatedWrite(tx, [input.sourceId], () => tx.addTag('customers/account', 'retained-tag', { sourceId: input.sourceId })));+ await engine.transaction(tx => withCoordinatedWrite(tx, [input.sourceId], () => tx.addTag('customers/account', 'retained-tag', { sourceId: input.sourceId }), TEST_WRITE_ATTRIBUTION));const file = join(root, 'customers/account.md');const changed = readFileSync(file, 'utf8') + '\nA committed source update.\n';writeFileSync(file, changed); git(root, 'add', '.'); git(root, 'commit', '-qm', 'Synthetic source update');diff --git a/test/connector-wave3.test.ts b/test/connector-wave3.test.tsindex 5f6d357bed..f4aab48f4c 100644--- a/test/connector-wave3.test.ts+++ b/test/connector-wave3.test.ts@@ -19,6 +19,7 @@ import { resolveRepairScope, runRepair } from '../src/core/repair/core.ts';import { performSync } from '../src/commands/sync.ts';import { handleToolCall } from '../src/mcp/server.ts';import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';import { inspectUnchanged } from '../src/core/persistence/noop-kernel.ts';import { ALL_SOURCES } from '../src/core/source-id.ts';import type { WriteRequest } from '../src/core/persistence/model.ts';@@ -441,7 +442,7 @@ test('#5470 connector kernel: a safe-chunk reseal, projection lag, a pending con// render (#5567): the first re-walk may materialize it into the page once; it survives, and later re-walks skip.const summaries = () => engine.executeRaw<{ summary: string }>('SELECT t.summary FROM timeline_entries t JOIN pages p ON p.id=t.page_id WHERE p.source_id=$1 AND p.slug=$2', [f.id, slug]);expect(await admitted(() => engine.transaction(tx => withCoordinatedWrite(tx, [f.id], () =>- tx.addTimelineEntry(slug, { date: '2026-01-02', summary: 'Met to review the example plan', source: 'meetings/2026-01-02' }, { sourceId: f.id }))))).toBeLessThanOrEqual(1);+ tx.addTimelineEntry(slug, { date: '2026-01-02', summary: 'Met to review the example plan', source: 'meetings/2026-01-02' }, { sourceId: f.id }), TEST_WRITE_ATTRIBUTION)))).toBeLessThanOrEqual(1);expect(await admitted(async () => {})).toBe(0);expect(await summaries()).toEqual([{ summary: 'Met to review the example plan' }]);expect(await admitted(() => engine.executeRaw('UPDATE pages SET text_projection_revision=gen_random_uuid() WHERE source_id=$1 AND slug=$2', [f.id, slug]))).toBe(1);diff --git a/test/facts-relink-routing.test.ts b/test/facts-relink-routing.test.tsindex 2ab4983ead..baf3f9f129 100644--- a/test/facts-relink-routing.test.ts+++ b/test/facts-relink-routing.test.ts@@ -21,6 +21,7 @@ import { claimWorktree } from '../src/core/persistence/ownership.ts';import { registerLocalWriter } from '../src/core/persistence/identity.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';import { withEnv } from './helpers/with-env.ts';import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';import { requirePostgresTestDatabase } from './helpers/test-backends.ts';@@ -115,7 +116,7 @@ test(`${backend}: a managed brain publishes the same way through the coordinatorawait registerLocalWriter(engine, 'cli');await activatePersistence(engine, { confirmQuiesced: true });const id = await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], async () =>- (await tx.insertFact({ fact: 'Basalt Example signed a pilot', kind: 'fact', entity_slug: null, visibility: 'world', source: 'chat' } as never, { source_id: 'default' })).id));+ (await tx.insertFact({ fact: 'Basalt Example signed a pilot', kind: 'fact', entity_slug: null, visibility: 'world', source: 'chat' } as never, { source_id: 'default' })).id, TEST_WRITE_ATTRIBUTION));expect((await relink()).linked).toBe(1);const rowNum = await expectAdopted(id, 'companies/basalt-example');const file = parseFactsFence(readFileSync(join(repo, 'companies/basalt-example.md'), 'utf8')).facts;diff --git a/test/fix-wave-5-integration.test.ts b/test/fix-wave-5-integration.test.tsindex 6be52c8dce..c5a16f80b0 100644--- a/test/fix-wave-5-integration.test.ts+++ b/test/fix-wave-5-integration.test.ts@@ -41,6 +41,7 @@ import { drainProjections } from '../src/commands/projections.ts';import { projectionBacklog } from '../src/core/page-state/projections.ts';import { checkProjectionReadiness } from '../src/commands/doctor/checks/projection-readiness.ts';import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';import { declarePersistenceProtocol } from '../src/core/persistence/protocol.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';@@ -101,7 +102,7 @@ async function prefixExpire(engine: BrainEngine, ctx: OperationContext, slug: stawait tx.executeRaw('UPDATE persistence_requests SET completed_at=now(), consumer_version=NULL WHERE request_id=$1::uuid', [receipt.request_id]);await tx.executeRaw(`UPDATE facts SET expired_at=now(), row_num=NULL WHERE source_id='default' AND source_markdown_slug=$1AND source LIKE 'cli:extract-conversation-facts%' AND expired_at IS NULL`, [slug]);- }));+ }, TEST_WRITE_ATTRIBUTION));}for (const backend of testBackends()) {@@ -129,7 +130,7 @@ for (const backend of testBackends()) {SELECT s.incarnation,p.slug,p.knowledge_revision,CASE WHEN p.slug LIKE 'notes/backlog-%' AND right(p.slug,1) IN ('0','2','4','6','8') THEN 'rebuild_failed' ELSE 'protocol_activation' ENDFROM pages p JOIN sources s ON s.id=p.source_idWHERE p.source_id='default' AND p.deleted_at IS NULL ON CONFLICT(source_incarnation,slug) DO UPDATE SET revision=EXCLUDED.revision,reason=EXCLUDED.reason`);- }));+ }, TEST_WRITE_ATTRIBUTION));const queued = (await projectionBacklog(engine)).pending;expect(queued).toBe(152);const cooling = (await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM page_projection_jobs WHERE reason='rebuild_failed'"))[0].n;@@ -341,7 +342,7 @@ for (const backend of testBackends()) {expect(worktreeManifest(root).digest).toBe(stored.digest);// A database-only tag makes the page's canonical form differ from its bytes; an upstream edit then syncs database-only.- await engine.transaction(tx => withCoordinatedWrite(tx, [id], () => tx.addTag('todos', 'kept-in-brain', { sourceId: id })));+ await engine.transaction(tx => withCoordinatedWrite(tx, [id], () => tx.addTag('todos', 'kept-in-brain', { sourceId: id }), TEST_WRITE_ATTRIBUTION));writeFileSync(join(root, 'TODOS.md'), '# Todos\n\n- keep the mirror pullable\n- and syncing\n');commit('upstream edit');const next = await performManagedSync(engine, { sourceId: id, noPull: true, noEmbed: true, noExtract: true });diff --git a/test/grandfather-managed.test.ts b/test/grandfather-managed.test.tsindex 46852b7c95..a77012829b 100644--- a/test/grandfather-managed.test.ts+++ b/test/grandfather-managed.test.ts@@ -12,6 +12,7 @@ import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';import { grandfatherCanonicalPage } from '../src/core/persistence/grandfather.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';import { runPersistenceEffects } from '../src/core/persistence/effects.ts';import { declarePersistenceProtocol } from '../src/core/persistence/protocol.ts';import { serializePageToMarkdown } from '../src/core/markdown.ts';@@ -55,7 +56,7 @@ async function preservesManagedPage(databaseUrl?: string) {await tx.executeRaw("UPDATE content_chunks SET embedding=('['||array_to_string(array_fill(0.1::real,ARRAY[$1::int]),',')||']')::vector WHERE page_id=$2", [column.width, before.page.id]);await tx.executeRaw('INSERT INTO extract_atoms_page_state(source_incarnation,page_id,content_hash,fail_count,tombstoned) VALUES($1::uuid,$2,$3,2,true)',[before.sourceIncarnation, before.page.id, before.page.content_hash]);- }));+ }, TEST_WRITE_ATTRIBUTION));const chunks = await engine.executeRaw('SELECT id,chunk_text,embedding::text FROM content_chunks WHERE page_id=$1 ORDER BY id', [before.page.id]);expect(chunks.length).toBeGreaterThan(0);const result = await phaseCGrandfather(engine, { yes: true, dryRun: false, noAutopilotInstall: true });@@ -140,7 +141,7 @@ test('archived sources and non-Markdown artifacts are not rewritten by managed gawait engine.transaction(async tx => {await tx.executeRaw("SELECT set_config('gbrain.topology_change','on',true)");await tx.executeRaw("UPDATE sources SET archived=false WHERE id='default'");- await withCoordinatedWrite(tx, ['default'], () => tx.executeRaw("UPDATE pages SET source_path='source/example.ts' WHERE slug=$1", [slug]));+ await withCoordinatedWrite(tx, ['default'], () => tx.executeRaw("UPDATE pages SET source_path='source/example.ts' WHERE slug=$1", [slug]), TEST_WRITE_ATTRIBUTION);});expect((await phaseCGrandfather(engine, { yes: true, dryRun: false, noAutopilotInstall: true })).detail).toMatchObject({ touched: 0, skipped: 1, failed: 0 });expect(readFileSync(path, 'utf8')).toBe(bytes);@@ -302,6 +303,6 @@ test('verify reports a managed page rewritten after grandfathering without failiconst { detail } = await phaseCGrandfather(engine, { yes: true, dryRun: false, noAutopilotInstall: true });expect(await phaseDVerify(engine, detail.grandfathered)).toMatchObject({ status: 'complete', detail: 'verified=1 rewritten_concurrently=0' });await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () =>- tx.executeRaw("UPDATE pages SET frontmatter=frontmatter-'validate' WHERE source_id='default' AND slug=$1", [slug])));+ tx.executeRaw("UPDATE pages SET frontmatter=frontmatter-'validate' WHERE source_id='default' AND slug=$1", [slug]), TEST_WRITE_ATTRIBUTION));expect(await phaseDVerify(engine, detail.grandfathered)).toMatchObject({ status: 'complete', detail: 'verified=0 rewritten_concurrently=1' });}), 120_000);diff --git a/test/helpers/extract-timeline-db-scenarios.ts b/test/helpers/extract-timeline-db-scenarios.tsindex bdb523eac9..3286baf200 100644--- a/test/helpers/extract-timeline-db-scenarios.ts+++ b/test/helpers/extract-timeline-db-scenarios.ts@@ -10,6 +10,7 @@ import type { OperationContext } from '../../src/core/ops/contract.ts';import { submitPageMutation } from '../../src/core/persistence/page-mutations.ts';import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';import { withCoordinatedWrite } from '../../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './write-attribution.ts';import { runExtract } from '../../src/commands/extract.ts';import { _resetCliExitVerdictForTests, currentExitCode } from '../../src/core/cli-force-exit.ts';import { managedBrain } from './managed-brain.ts';@@ -24,7 +25,7 @@ const rows = (engine: BrainEngine, slug: string) => engine.executeRaw<{ date: st/** A page published before timeline projection: its stored rows are gone, its body still has the bullets. */async function dropStoredTimeline(engine: BrainEngine, slug: string) {await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () =>- tx.executeRaw('DELETE FROM timeline_entries WHERE page_id = (SELECT id FROM pages WHERE slug = $1)', [slug])));+ tx.executeRaw('DELETE FROM timeline_entries WHERE page_id = (SELECT id FROM pages WHERE slug = $1)', [slug]), TEST_WRITE_ATTRIBUTION));}async function runCaptured(engine: BrainEngine, args: string[]) {diff --git a/test/helpers/managed-atom-compaction.ts b/test/helpers/managed-atom-compaction.tsindex 93ed34f7f7..b300496fd1 100644--- a/test/helpers/managed-atom-compaction.ts+++ b/test/helpers/managed-atom-compaction.ts@@ -9,6 +9,7 @@ import { OperationError } from '../../src/core/ops/contract.ts';import { managedAtomSession, readAtomOrigin, resumeManagedAtoms } from '../../src/core/persistence/atom-maintenance.ts';import { retryManagedAtomBatch } from '../../src/core/persistence/atom-retry.ts';import { withCoordinatedWrite } from '../../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './write-attribution.ts';import { compactWriteReceipts, receiptFor } from '../../src/core/persistence/journal.ts';import type { WriteRequest } from '../../src/core/persistence/model.ts';import { disposePersistenceConsumer, waitForWrite } from '../../src/core/persistence/service.ts';@@ -69,7 +70,7 @@ export async function exerciseAtomCompaction(engine: BrainEngine, scenario: typeawait tx.lockPageKeys([{ sourceId, slug: slugs[0] }]);const atom = (await tx.getPage(slugs[0], { sourceId }))!;await tx.putPage(slugs[0], { ...atom, compiled_truth: 'Independent correction after the original atom committed.' }, { sourceId });- }));+ }, TEST_WRITE_ATTRIBUTION));}const pagesBefore = await engine.executeRaw('SELECT * FROM pages WHERE source_id=$1 ORDER BY id', [sourceId]);const checkpointsBefore = await engine.executeRaw("SELECT * FROM op_checkpoints WHERE op='managed-atoms' AND completed_keys->0->>'sourceId'=$1 ORDER BY fingerprint", [sourceId]);diff --git a/test/helpers/managed-atom-regressions.ts b/test/helpers/managed-atom-regressions.tsindex 820b461ce3..725c8acabf 100644--- a/test/helpers/managed-atom-regressions.ts+++ b/test/helpers/managed-atom-regressions.ts@@ -9,6 +9,7 @@ import { OperationError } from '../../src/core/ops/contract.ts';import { managedAtomSession } from '../../src/core/persistence/atom-maintenance.ts';import { retryManagedAtomBatch } from '../../src/core/persistence/atom-retry.ts';import { withCoordinatedWrite } from '../../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './write-attribution.ts';import { sha256 } from '../../src/core/persistence/digest.ts';import { refreshManagedFilesystemRoots } from '../../src/core/persistence/filesystem-guard.ts';import { registerLocalWriter } from '../../src/core/persistence/identity.ts';@@ -86,7 +87,7 @@ export async function exerciseAtomRetryFence(engine: BrainEngine, state: typeofawait tx.lockPageKeys([{ sourceId, slug: slugs[0] }]);const atom = (await tx.getPage(slugs[0], { sourceId }))!;await tx.putPage(slugs[0], { ...atom, compiled_truth: 'Independent correction that must survive retry.' }, { sourceId });- }));+ }, TEST_WRITE_ATTRIBUTION));};const observe = (target: BrainEngine, inTransaction = false): BrainEngine => new Proxy(target, {get(current, key) {diff --git a/test/helpers/managed-atoms-contract.ts b/test/helpers/managed-atoms-contract.tsindex 33e0705c81..015aecf5b8 100644--- a/test/helpers/managed-atoms-contract.ts+++ b/test/helpers/managed-atoms-contract.ts@@ -12,6 +12,7 @@ import { isPhysicalRootMetadata } from '../../src/core/persistence/physical-rootimport { __setMaintenanceWriteWaitForTests } from '../../src/core/persistence/maintenance-wait.ts';import { registerLocalWriter, withVerifiedLocalRegistration, type LocalGrant } from '../../src/core/persistence/identity.ts';import { withCoordinatedWrite } from '../../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './write-attribution.ts';import { retryManagedAtomBatch } from '../../src/core/persistence/atom-retry.ts';import type { WriteRequest } from '../../src/core/persistence/model.ts';import { withSubmissionAuthority } from '../../src/core/minions/submission-authority.ts';@@ -144,7 +145,7 @@ export async function exerciseManagedAtoms(engine: BrainEngine, scenario: Case):// its explicit retry leaves the atom input unchanged.if (scenario === 'malformed_retry_revision') {const before = (await engine.readPageSnapshot(page.slug, { sourceId }))!;- await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => tx.addTag(page.slug, 'reviewed', { sourceId })));+ await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => tx.addTag(page.slug, 'reviewed', { sourceId }), TEST_WRITE_ATTRIBUTION));const after = (await engine.readPageSnapshot(page.slug, { sourceId }))!;expect(after.revision).not.toBe(before.revision);expect(after.page.content_hash).toBe(page.content_hash);@@ -578,7 +579,7 @@ export async function exerciseManagedAtomBatch(engine: BrainEngine, scenario: tyconst atom = (await tx.getPage(slugs[1], { sourceId }))!;await tx.putPage(slugs[1], { ...atom, compiled_truth: `${atom.compiled_truth}\nAn independent correction.` }, { sourceId });}- }));+ }, TEST_WRITE_ATTRIBUTION));}return result;};diff --git a/test/helpers/managed-e2e-fixture-write.ts b/test/helpers/managed-e2e-fixture-write.tsindex 771ffbe573..079cf4b3f3 100644--- a/test/helpers/managed-e2e-fixture-write.ts+++ b/test/helpers/managed-e2e-fixture-write.ts@@ -1,12 +1,13 @@import type { BrainEngine } from '../../src/core/engine.ts';import { withCoordinatedWrite } from '../../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './write-attribution.ts';export function withManagedFixtureWrite<T>(engine: BrainEngine,sourceIds: string[],write: (tx: BrainEngine) => Promise<T>,): Promise<T> {- return engine.transaction(tx => withCoordinatedWrite(tx, sourceIds, () => write(tx)));+ return engine.transaction(tx => withCoordinatedWrite(tx, sourceIds, () => write(tx), TEST_WRITE_ATTRIBUTION));}export function createManagedFixtureSource(diff --git a/test/helpers/managed-facts-compaction-contract.ts b/test/helpers/managed-facts-compaction-contract.tsindex 539e8de400..fa7d54b8db 100644--- a/test/helpers/managed-facts-compaction-contract.ts+++ b/test/helpers/managed-facts-compaction-contract.ts@@ -14,6 +14,7 @@ import { localHostId, registerLocalWriter } from '../../src/core/persistence/ideimport { claimNextWrite, compactWriteReceipts } from '../../src/core/persistence/journal.ts';import { publishMutation } from '../../src/core/persistence/coordinator.ts';import { withCoordinatedWrite } from '../../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './write-attribution.ts';import { declarePersistenceProtocol } from '../../src/core/persistence/protocol.ts';import { prepareManagedFactsMutation } from '../../src/core/persistence/facts-prepare.ts';import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';@@ -84,7 +85,7 @@ export async function exerciseFactCompaction(engine: BrainEngine, scenario: Caseconst shouldConflict = i < 2 && (scenario.endsWith('_failed') || scenario.endsWith('_partial') && i === 1);if (shouldConflict) await engine.transaction(async tx => {await declarePersistenceProtocol(tx);- await withCoordinatedWrite(tx, [sourceId], () => tx.executeRaw('UPDATE pages SET knowledge_revision=gen_random_uuid() WHERE source_id=$1 AND slug=$2', [sourceId, row.slug]));+ await withCoordinatedWrite(tx, [sourceId], () => tx.executeRaw('UPDATE pages SET knowledge_revision=gen_random_uuid() WHERE source_id=$1 AND slug=$2', [sourceId, row.slug]), TEST_WRITE_ATTRIBUTION);});const done = await publishMutation(engine, row, prepared, localHostId());expect(done.state).toBe(shouldConflict || i === 2 && !scenario.endsWith('_success') ? 'conflict' : 'committed');diff --git a/test/helpers/w5-scenarios.ts b/test/helpers/w5-scenarios.tsindex b64c14120e..35a4e07fe9 100644--- a/test/helpers/w5-scenarios.ts+++ b/test/helpers/w5-scenarios.ts@@ -17,6 +17,7 @@ import { compactWriteReceipts } from '../../src/core/persistence/journal.ts';import { declarePersistenceProtocol } from '../../src/core/persistence/protocol.ts';import { localHostId } from '../../src/core/persistence/identity.ts';import { withCoordinatedWrite } from '../../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './write-attribution.ts';import { acquireWorktree, getWorktreeBinding } from '../../src/core/persistence/ownership.ts';import { extractStaleFromDB } from '../../src/commands/extract.ts';import { computeRecommendations } from '../../src/core/brain-score-recommendations.ts';@@ -232,7 +233,7 @@ export async function managedStaleSweepKeepsNormalizedTimeline(databaseUrl?: strconst [alice] = await engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE slug='people/alice-example'");// A row written before timeline normalization (whitespace differs from the bullet).await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () =>- tx.executeRaw("UPDATE timeline_entries SET summary='Met Acme ' WHERE page_id=$1", [alice.id])));+ tx.executeRaw("UPDATE timeline_entries SET summary='Met Acme ' WHERE page_id=$1", [alice.id]), TEST_WRITE_ATTRIBUTION));const timeline = () => engine.executeRaw('SELECT date::text,source,summary FROM timeline_entries WHERE page_id=$1 ORDER BY id', [alice.id]);const before = await timeline();expect(before).toEqual([{ date: '2026-01-02', source: 'test', summary: 'Met Acme ' }]);diff --git a/test/helpers/wave-fixture.ts b/test/helpers/wave-fixture.tsindex b3f0433154..a560ec9043 100644--- a/test/helpers/wave-fixture.ts+++ b/test/helpers/wave-fixture.ts@@ -16,6 +16,7 @@ import { submitPageMutation } from '../../src/core/persistence/page-mutations.tsimport { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';import { declarePersistenceProtocol } from '../../src/core/persistence/protocol.ts';import { withCoordinatedWrite } from '../../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './write-attribution.ts';import { CLAUDE_CLI_CWD_PREFIX } from '../../src/core/ai/providers/claude-cli-scratch.ts';import { managedBrain, type ManagedBrain } from './managed-brain.ts';import { withEnv } from './with-env.ts';@@ -39,13 +40,13 @@ export async function seedWaveFindings(brain: ManagedBrain, home: string, kinds:if (kinds.includes('timeline')) {await put(ctx, 'notes/history', 'Body with history.');await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.executeRaw(- `INSERT INTO timeline_entries(page_id,date,source,summary,detail) SELECT id,'2026-07-01','legacy','A database-only event','' FROM pages WHERE source_id='default' AND slug='notes/history'`)));+ `INSERT INTO timeline_entries(page_id,date,source,summary,detail) SELECT id,'2026-07-01','legacy','A database-only event','' FROM pages WHERE source_id='default' AND slug='notes/history'`), TEST_WRITE_ATTRIBUTION));}if (kinds.includes('visibility')) await put(ctx, 'atoms/unstamped', 'An extracted atom with no visibility.', 'atom');if (kinds.includes('safe_index')) {await put(ctx, 'notes/unsealed', 'A page chunked before the safe-chunk fence.');await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.executeRaw(- "UPDATE pages SET chunker_version=3 WHERE source_id='default' AND slug='notes/unsealed'")));+ "UPDATE pages SET chunker_version=3 WHERE source_id='default' AND slug='notes/unsealed'"), TEST_WRITE_ATTRIBUTION));}await disposePersistenceConsumer(engine);if (kinds.includes('capacity')) {diff --git a/test/helpers/write-attribution.ts b/test/helpers/write-attribution.tsnew file mode 100644index 0000000000..40e4b925f2--- /dev/null+++ b/test/helpers/write-attribution.ts@@ -0,0 +1,4 @@+import type { WriteAttribution } from '../../src/core/persistence/attribution.ts';++/** The actor test fixtures name when they write through withCoordinatedWrite directly. */+export const TEST_WRITE_ATTRIBUTION: WriteAttribution = { requestId: null, principal: { kind: 'application', id: 'test:fixture' } };diff --git a/test/managed-facts-writers.test.ts b/test/managed-facts-writers.test.tsindex 66a6d0478b..fa060ed5de 100644--- a/test/managed-facts-writers.test.ts+++ b/test/managed-facts-writers.test.ts@@ -39,6 +39,7 @@ import { runLoopsExtract } from '../src/core/google/loops-extract.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';import { withEnv } from './helpers/with-env.ts';import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';import { testBackends } from './helpers/test-backends.ts';const backends = testBackends();@@ -477,7 +478,7 @@ test('managed deleted-page expiry waits for a concurrent restore of that page (Pawait put('people/bob-demo', PERSON('Bob Demo', FENCE('| 1 | Plays chess | fact | 1.0 | world | low | 2019-01-01 | | chat | |')));}, async ({ engine, sourceId }) => {if (engine.kind !== 'postgres') return;- await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => tx.softDeletePage('people/bob-demo', { sourceId })));+ await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => tx.softDeletePage('people/bob-demo', { sourceId }), TEST_WRITE_ATTRIBUTION));let release!: () => void;const gate = new Promise<void>(resolve => { release = resolve; });let locked!: () => void;@@ -487,7 +488,7 @@ test('managed deleted-page expiry waits for a concurrent restore of that page (Pawait tx.executeRaw('UPDATE pages SET deleted_at=NULL WHERE source_id=$1 AND slug=$2', [sourceId, 'people/bob-demo']);locked();await gate;- }));+ }, TEST_WRITE_ATTRIBUTION));await holding;const run = runExtractFacts(engine, { sourceId, slugs: [] });await new Promise(resolve => setTimeout(resolve, 500));diff --git a/test/managed-maintenance.test.ts b/test/managed-maintenance.test.tsindex 42fea67693..23c362a7b7 100644--- a/test/managed-maintenance.test.ts+++ b/test/managed-maintenance.test.ts@@ -18,6 +18,7 @@ import { publishMutation } from '../src/core/persistence/coordinator.ts';import { localHostId, revokeLocalWriter } from '../src/core/persistence/identity.ts';import { submitForgetMutation } from '../src/core/persistence/memory-mutations.ts';import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';import { readJournalLimits } from '../src/core/persistence/limits.ts';import { parseMarkdown, serializePageToMarkdown } from '../src/core/markdown.ts';import { configureGateway, resetGateway, __setChatTransportForTests } from '../src/core/ai/gateway.ts';@@ -270,7 +271,7 @@ for (const change of ['derived', 'semantic'] as const) {await tx.executeRaw(change === 'derived'? 'UPDATE facts SET embedding=embedding,embedded_at=now() WHERE source_id=$1': "UPDATE facts SET fact=fact||' changed' WHERE source_id=$1", [sourceId]);- }));+ }, TEST_WRITE_ATTRIBUTION));const outcome = await publishMutation(engine, row, prepared, localHostId());expect(outcome.state).toBe(change === 'derived' ? 'committed' : 'conflict');expect(await engine.executeRaw('SELECT id FROM facts WHERE source_id=$1 AND consolidated_at IS NOT NULL', [sourceId]))diff --git a/test/page-projection-code-recovery.test.ts b/test/page-projection-code-recovery.test.tsindex 27fdc973b4..15099724a2 100644--- a/test/page-projection-code-recovery.test.ts+++ b/test/page-projection-code-recovery.test.ts@@ -9,6 +9,7 @@ import { runReindexCode } from '../src/commands/reindex-code.ts';import { readProjectionSnapshot, preparePageProjection, installPageProjection, rebuildPendingPageProjections, queuePageProjection } from '../src/core/page-state/projections.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';import { withEnv } from './helpers/with-env.ts';import { testBackends } from './helpers/test-backends.ts';@@ -207,7 +208,7 @@ test('managed reindex uses a durable guarded receipt without canonical writes orconst requests = await engine.executeRaw<{ state: string; revision: string }>('SELECT state,outcome->>\'revision\' AS revision FROM persistence_requests WHERE source_id=$1 AND slug=$2', [sourceId, slug]);expect(requests).toEqual([{ state: 'committed', revision: before.revision }]);expect(await engine.executeRaw('SELECT id FROM persistence_effects WHERE source_id=$1', [sourceId])).toEqual([]);- await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => tx.softDeletePage(slug, { sourceId })));+ await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => tx.softDeletePage(slug, { sourceId }), TEST_WRITE_ATTRIBUTION));expect((await runReindexCode(engine, { sourceId, noEmbed: true, force: true })).failed).toBe(0);expect(await engine.getPage(slug, { sourceId })).toBeNull();} finally { await disposePersistenceConsumer(engine); await engine.executeRaw('UPDATE persistence_brain SET enabled=false'); }diff --git a/test/persistence-file-import.test.ts b/test/persistence-file-import.test.tsindex 02e5a0e29d..87135153e9 100644--- a/test/persistence-file-import.test.ts+++ b/test/persistence-file-import.test.ts@@ -19,6 +19,7 @@ import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';import { sha256 } from '../src/core/persistence/digest.ts';import { runImport } from '../src/commands/import.ts';import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';const home = mkdtempSync(join(tmpdir(), 'gbrain-file-import-'));const engines: BrainEngine[] = [];@@ -195,7 +196,7 @@ test('publication refuses admitted input-byte, canonical-target and page-identitif (race === 'page') {await engine.transaction(tx => withCoordinatedWrite(tx, [f.sourceId], () => tx.putPage(slug, {type: 'note', title: 'Concurrent page', compiled_truth: 'Concurrent accepted page must survive.', timeline: '', frontmatter: {}, content_hash: 'concurrent',- }, { sourceId: f.sourceId })));+ }, { sourceId: f.sourceId }), TEST_WRITE_ATTRIBUTION));} else writeFileSync(changedPath, 'Concurrent local edit must survive.\n');const outcome = await publishMutation(engine, row, prepared, localHostId());expect(outcome.state).toBe('conflict');diff --git a/test/persistence-journal.test.ts b/test/persistence-journal.test.tsindex 0a3388e89c..b9b9e0e25f 100644--- a/test/persistence-journal.test.ts+++ b/test/persistence-journal.test.ts@@ -16,6 +16,7 @@ import { claimWorktree } from '../src/core/persistence/ownership.ts';import { preparePageMutation } from '../src/core/persistence/page-prepare.ts';import { assertSafeE2eDatabaseUrl } from './helpers/db-guard.ts';import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';const engines: BrainEngine[] = [];@@ -230,7 +231,7 @@ describe('durable mutation journal', () => {await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], async () => {await tx.putPage('guarded', input('Yes'), { sourceId });await tx.addTag('guarded', 'coherent', { sourceId });- }));+ }, TEST_WRITE_ATTRIBUTION));expect((await engine.readPageSnapshot('guarded', { sourceId }))!.tags).toEqual(['coherent']);await expect(engine.addTag('guarded', 'uncoordinated', { sourceId })).rejects.toThrow('writer_coordinator_required');} finally { await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1'); }diff --git a/test/persistence-managed-lifecycle.test.ts b/test/persistence-managed-lifecycle.test.tsindex e50abec6bb..197a8cecf8 100644--- a/test/persistence-managed-lifecycle.test.ts+++ b/test/persistence-managed-lifecycle.test.ts@@ -20,6 +20,7 @@ import { runExtract } from '../src/commands/extract.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';import { LINK_EXTRACTOR_VERSION_TS } from '../src/core/link-extraction.ts';import { withEnv } from './helpers/with-env.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';const home = mkdtempSync(join(tmpdir(), 'gbrain-managed-lifecycle-'));const engines: BrainEngine[] = [];@@ -288,7 +289,7 @@ test('a managed brain prunes timeline rows an earlier page version left behind,expect(await summaries()).toEqual(['Joined Acme Example']);// A row left over from before timeline reconciliation: an earlier version produced it, the current text does not.await engine.transaction(tx => withCoordinatedWrite(tx, [f.id], () => tx.addTimelineEntry('people/bea-example',- { ...left, detail: '' }, { sourceId: f.id })));+ { ...left, detail: '' }, { sourceId: f.id }), TEST_WRITE_ATTRIBUTION));expect(await summaries()).toEqual(['Joined Acme Example', 'Left Acme Example']);expect((await timelineHistoryCheck(engine, f.id)).details).toMatchObject({ materializable_rows: 0 });const printed: string[] = [];diff --git a/test/persistence-managed-sync.test.ts b/test/persistence-managed-sync.test.tsindex a052f96055..4f72ffdcf5 100644--- a/test/persistence-managed-sync.test.ts+++ b/test/persistence-managed-sync.test.ts@@ -17,6 +17,7 @@ import { sha256 } from '../src/core/persistence/digest.ts';import { performManagedSync } from '../src/core/persistence/sync-run.ts';import { discoverManagedSync } from '../src/core/persistence/sync-discovery.ts';import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';import { withEnv } from './helpers/with-env.ts';import { prepareRemoteJob, withSubmissionAuthority } from '../src/core/minions/submission-authority.ts';@@ -185,7 +186,7 @@ test('repeated slices reuse one manifest and still reject an intervening page idexpect(manifestReads).toBe(1);await engine.transaction(tx => withCoordinatedWrite(tx, [f.id], () => tx.putPage('c', {type: 'note', title: 'c', compiled_truth: 'A newer accepted page between sync slices.', timeline: '', frontmatter: {}, content_hash: 'newer',- }, { sourceId: f.id })));+ }, { sourceId: f.id }), TEST_WRITE_ATTRIBUTION));await expect(performManagedSync(engine, options, slice)).rejects.toMatchObject({ code: 'revision_conflict' });expect(manifestReads).toBe(1);expect(await engine.executeRaw('SELECT completed_keys FROM op_checkpoints WHERE op=$1 AND fingerprint=$2',@@ -242,9 +243,9 @@ test('a write between batches cannot be overwritten by an older enumerated Git plet changed: Promise<void>|undefined;const abort=new AbortController();const first=await performManagedSync(engine,{sourceId:f.id,noPull:true,signal:abort.signal,onProgress:p=>{- if(p.bankedFiles===1){ abort.abort(); changed=engine.transaction(tx=>withCoordinatedWrite(tx,[f.id],async()=>{+ if(p.bankedFiles===1){ abort.abort(); changed=engine.transaction(tx=>withCoordinatedWrite(tx, [f.id], async()=>{await tx.putPage('b',{type:'note',title:'b',compiled_truth:'A concurrently accepted newer observation.',timeline:'',frontmatter:{},content_hash:'newer'}, {sourceId:f.id});- })); }+ }, TEST_WRITE_ATTRIBUTION)); }}});expect(first.status).toBe('partial'); await changed;await expect(performManagedSync(engine,{sourceId:f.id,noPull:true})).rejects.toMatchObject({code:'revision_conflict'});diff --git a/test/persistence-managed-takes-extract.test.ts b/test/persistence-managed-takes-extract.test.tsindex ea1c84f1d5..88a1b58676 100644--- a/test/persistence-managed-takes-extract.test.ts+++ b/test/persistence-managed-takes-extract.test.ts@@ -12,6 +12,7 @@ import { claimWorktree } from '../src/core/persistence/ownership.ts';import { registerLocalWriter } from '../src/core/persistence/identity.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';import { withEnv } from './helpers/with-env.ts';import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';import { requirePostgresTestDatabase } from './helpers/test-backends.ts';@@ -42,7 +43,7 @@ beforeAll(async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SOURCE: undefined, GBReditStaleDuringChat = false;await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], async () => {await tx.executeRaw('UPDATE pages SET compiled_truth=$1 WHERE source_id=$2 AND slug=$3', ['concurrent edit', 'default', chatSlug]);- }));+ }, TEST_WRITE_ATTRIBUTION));}const claim = text.includes('SNAPSHOT VERSION: NEW') ? 'snapshot version claim' : 'managed bootstrap claim';const response = JSON.stringify([{ claim, kind: 'take', weight: 0.7 }]);@@ -119,7 +120,7 @@ test(`${backend}: managed extraction classifies the pinned snapshot after a seleif (!await engine.readPageSnapshot(slug, { sourceId: 'default' })) throw new Error(`missing fixture ${slug}`);await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], async () => {await tx.putPage(slug, { type: 'concept', title: slug, compiled_truth: BODY, timeline: '', frontmatter: {} }, { sourceId: 'default' });- }));+ }, TEST_WRITE_ATTRIBUTION));let submittedContent = '';putPage.handler = async (_context, params) => { submittedContent = String(params.content); return { state: 'committed' }; };const originalReadPageSnapshot = engine.readPageSnapshot.bind(engine);@@ -130,7 +131,7 @@ test(`${backend}: managed extraction classifies the pinned snapshot after a sele(engine as any).readPageSnapshot = originalReadPageSnapshot;await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], async () => {await tx.putPage(slug, { type: 'concept', title: slug, compiled_truth: `SNAPSHOT VERSION: NEW\n${BODY}`, timeline: '', frontmatter: {} }, { sourceId: 'default' });- }));+ }, TEST_WRITE_ATTRIBUTION));const updated = await originalReadPageSnapshot(slug, { sourceId: 'default' });if (!updated) throw new Error(`missing fixture ${slug}`);writeFileSync(join(repo, `${slug}.md`), serializePageToMarkdown(updated.page, updated.tags));@@ -156,7 +157,7 @@ test(`${backend}: managed extraction composes from the DB snapshot when the canoconst dbBody = `SNAPSHOT VERSION: NEW\n${BODY}`;await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], async () => {await tx.putPage(slug, { type: 'concept', title: slug, compiled_truth: dbBody, timeline: '', frontmatter: {} }, { sourceId: 'default' });- }));+ }, TEST_WRITE_ATTRIBUTION));const newer = await engine.readPageSnapshot(slug, { sourceId: 'default' });if (!newer) throw new Error(`missing updated fixture ${slug}`);writeFileSync(join(repo, `${slug}.md`), serializePageToMarkdown({ ...newer.page, compiled_truth: `DISK VERSION: STALE\n${BODY}` }, newer.tags));@@ -184,7 +185,7 @@ test(`${backend}: managed duplicate filtering reads the pinned snapshot takes feconst compiledTruth = `${BODY}\n\n## Takes\n\n<!--- gbrain:takes:begin -->\n| # | claim | kind | who | weight | since | source |\n|---|-------|------|-----|--------|-------|--------|\n| 1 | managed bootstrap claim | take | system | 0.7 | | manual |\n<!--- gbrain:takes:end -->`;await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], async () => {await tx.putPage(slug, { type: 'concept', title: slug, compiled_truth: compiledTruth, timeline: '', frontmatter: {} }, { sourceId: 'default' });- }));+ }, TEST_WRITE_ATTRIBUTION));const snapshot = await engine.readPageSnapshot(slug, { sourceId: 'default' });if (!snapshot) throw new Error(`missing fixture ${slug}`);writeFileSync(join(repo, `${slug}.md`), serializePageToMarkdown(snapshot.page, snapshot.tags).replace(/managed bootstrap claim/g, 'stale disk claim'));diff --git a/test/persistence-memory-mutations.test.ts b/test/persistence-memory-mutations.test.tsindex c4d9baa5af..a0676a6189 100644--- a/test/persistence-memory-mutations.test.ts+++ b/test/persistence-memory-mutations.test.ts@@ -9,6 +9,7 @@ import { parseFactsFence, upsertFactRow } from '../src/core/facts-fence.ts';import { submitRememberMutation, submitForgetMutation, prepareMemoryMutation } from '../src/core/persistence/memory-mutations.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';import { registerLocalWriter } from '../src/core/persistence/identity.ts';import { submissionAuthority } from '../src/core/persistence/authority.ts';import { admitWrite, claimNextWrite, getWriteRequest, getWriteRequestById, receiptFor } from '../src/core/persistence/journal.ts';@@ -29,7 +30,7 @@ async function setupPage(engine: BrainEngine, slug: string, body = 'Existing bioawait tx.putPage(slug, pageInput(body), { sourceId });await tx.addTag(slug, 'existing-tag', { sourceId });return (await tx.readPageSnapshot(slug, { sourceId }))!;- }));+ }, TEST_WRITE_ATTRIBUTION));}beforeAll(async () => {configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: {} });@@ -143,7 +144,7 @@ describe('journaled memory publication, both engines', () => {await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], async () => {await tx.executeRaw('DELETE FROM facts WHERE id=$1', [Number(first.id)]);await tx.deletePage(slug, { sourceId });- }));+ }, TEST_WRITE_ATTRIBUTION));const replay = await operationsByName.remember!.handler(context(engine), params);expect(replay).toEqual(first);await expect(operationsByName.remember!.handler(context(engine), { ...params, ttl: 'P30D' })).rejects.toMatchObject({ code: 'invalid_params', writeError: 'idempotency_conflict', protocolVersion: 1 });@@ -290,7 +291,7 @@ describe('journaled memory publication, both engines', () => {const request = (await getWriteRequest(engine, { kind: 'local_cli', id: local.id }, requestId))!;expect(request.worktree_id).toBeNull();expect(await engine.executeRaw('SELECT kind FROM persistence_effects WHERE request_id=$1::uuid', [request.id])).not.toHaveLength(0);- await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => tx.executeRaw('DELETE FROM facts WHERE id=$1', [Number(remembered.id)])));+ await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => tx.executeRaw('DELETE FROM facts WHERE id=$1', [Number(remembered.id)]), TEST_WRITE_ATTRIBUTION));expect(await submitForgetMutation(context(engine), 'forget', params)).toEqual(forgotten);// The fixture's offline owner is synthetic. Durable effects otherwise// deliberately retain their worktree identity until reconciliation.@@ -306,7 +307,7 @@ describe('journaled memory publication, both engines', () => {await disposePersistenceConsumer(engine);const slug = 'people/preparation-example';await setupPage(engine, slug);- const old = await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => tx.insertFact({ fact: 'Claim withdrawn during preparation', source: 'test', entity_slug: slug, visibility: 'world' }, { source_id: sourceId })));+ const old = await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => tx.insertFact({ fact: 'Claim withdrawn during preparation', source: 'test', entity_slug: slug, visibility: 'world' }, { source_id: sourceId }), TEST_WRITE_ATTRIBUTION));const snapshot = (await engine.readPageSnapshot(slug, { sourceId }))!;const authority = await submissionAuthority(context(engine), 'remember', sourceId, snapshot.sourceIncarnation, slug);const p = { fact: 'Claim withdrawn during preparation', provenance: 'test', entity_slug: slug, visibility: 'world', fence: true,diff --git a/test/persistence-reconcile.test.ts b/test/persistence-reconcile.test.tsindex fb1bcea43d..d063a80482 100644--- a/test/persistence-reconcile.test.ts+++ b/test/persistence-reconcile.test.ts@@ -16,6 +16,7 @@ import { prepareFileTarget } from '../src/core/persistence/page-prepare.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';import { admitWrite, claimNextWrite, compactWriteReceipts, getWriteRequest } from '../src/core/persistence/journal.ts';import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';import { submissionAuthority } from '../src/core/persistence/authority.ts';import { retainReconcileBackup } from '../src/core/persistence/reconcile-backup.ts';import { prepareReconcileMutation } from '../src/core/persistence/reconcile-prepare.ts';@@ -237,7 +238,7 @@ test('matching legacy scan state migrates only during canonical publication', asconst f = await fixture(engine);const marker = f.snapshot.page.content_hash!.slice(0, 16);await withCoordinatedWrite(engine, [f.id], () => engine.executeRaw("UPDATE pages SET frontmatter=frontmatter || $3::text::jsonb WHERE source_id=$1 AND slug=$2",- [f.id, f.slug, JSON.stringify({ atoms_scan_hash: marker, atoms_custom: 'preserve' })]));+ [f.id, f.slug, JSON.stringify({ atoms_scan_hash: marker, atoms_custom: 'preserve' })]), TEST_WRITE_ATTRIBUTION);const before = (await engine.readPageSnapshot(f.slug, { sourceId: f.id }))!;writeFileSync(f.file, serializePageToMarkdown(before.page, before.tags));await local(engine, f.registration, async () => {@@ -414,7 +415,7 @@ test('source substitution, changed canonical revisions and recreated pages neverelse await withCoordinatedWrite(engine, [f.id], async () => {if (mutation === 'identity') await engine.deletePage(f.slug, { sourceId: f.id });await engine.putPage(f.slug, { type: 'note', title: 'Example', compiled_truth: 'A later database observation.', frontmatter: {} }, { sourceId: f.id });- });+ }, TEST_WRITE_ATTRIBUTION);await expect(runReconcileApply(engine, { source_id: sourceId, slug: f.slug, preview, request_id: randomUUID() })).rejects.toMatchObject({code: mutation === 'source' ? 'invalid_params' : 'source_changed' });expect(readFileSync(f.file)).toEqual(raw);@@ -542,7 +543,7 @@ test('file and database edits after reconciliation preparation abort publicationelse await engine.transaction(tx => withCoordinatedWrite(tx, [f.id], () => tx.putPage(f.slug, {type: f.snapshot.page.type, title: f.snapshot.page.title, compiled_truth: 'A competing database observation.',timeline: f.snapshot.page.timeline, frontmatter: f.snapshot.page.frontmatter,- }, { sourceId: f.id, expectedRevision: f.snapshot.revision })));+ }, { sourceId: f.id, expectedRevision: f.snapshot.revision }), TEST_WRITE_ATTRIBUTION));const competingSnapshot = (await engine.readPageSnapshot(f.slug, { sourceId: f.id }))!;const result = await publishMutation(engine, repair.row, repair.prepared);expect(result.state).toBe('conflict');@@ -566,7 +567,7 @@ test('historical basename origins in separate slug directories remain distinct cawait tx.executeRaw('UPDATE pages SET source_path=$3 WHERE source_id=$1 AND slug=$2', [f.id, f.slug, 'example.md']);await tx.putPage(otherSlug, { type: 'note', title: 'Other example', compiled_truth: 'An independent historical basename page.',frontmatter: { independent: true }, source_path: 'example.md' }, { sourceId: f.id });- }));+ }, TEST_WRITE_ATTRIBUTION));const other = (await engine.readPageSnapshot(otherSlug, { sourceId: f.id }))!;writeFileSync(otherFile, serializePageToMarkdown(other.page, other.tags));const otherBytes = readFileSync(otherFile);@@ -592,7 +593,7 @@ test('shared provenance URI does not override distinct explicit canonical paths'await tx.executeRaw('UPDATE pages SET source_uri=$3 WHERE source_id=$1 AND slug=$2', [f.id, f.slug, sharedUri]);await tx.putPage(otherSlug, { type: 'note', title: 'Independent provenance', compiled_truth: 'A distinct file sharing ingestion provenance.',frontmatter: {}, source_path: 'other/provenance.md', source_uri: sharedUri }, { sourceId: f.id });- }));+ }, TEST_WRITE_ATTRIBUTION));const other = (await engine.readPageSnapshot(otherSlug, { sourceId: f.id }))!;writeFileSync(otherFile, serializePageToMarkdown(other.page, other.tags));const otherBytes = readFileSync(otherFile);@@ -618,7 +619,7 @@ test('genuine shared-file origins through explicit paths or URI fallback still r: origin === 'repeated-separators' ? 'notes//example.md' : 'notes/example.md';await tx.putPage('other/collision', { type: 'note', title: 'Collision', compiled_truth: 'Another page claiming the same file.',frontmatter: {}, source_path: sourcePath, source_uri: origin === 'uri' ? uri : null }, { sourceId: f.id });- }));+ }, TEST_WRITE_ATTRIBUTION));const snapshot = await engine.readPageSnapshot(f.slug, { sourceId: f.id });await local(engine, f.registration, async () => {await expect(runReconcilePreview(engine, { source_id: f.id, slug: f.slug })).rejects.toMatchObject({@@ -637,7 +638,7 @@ test('candidate-origin fanout stops at a bounded verification limit rather thanawait tx.executeRaw(`INSERT INTO pages(source_id,slug,type,title,compiled_truth,frontmatter,source_path,source_uri)SELECT $1,'other/candidate-'||n,'note','Independent origin','Independent candidate '||n,'{}'::jsonb,'other/candidate-'||n||'.md',$2FROM generate_series(1,101) n`, [f.id, uri]);- }));+ }, TEST_WRITE_ATTRIBUTION));await local(engine, f.registration, async () => {await expect(runReconcilePreview(engine, { source_id: f.id, slug: f.slug })).rejects.toMatchObject({code: 'source_changed', message: 'Too many candidate page origins to verify this exact file safely.' });diff --git a/test/persistence-skill-bundles.serial.test.ts b/test/persistence-skill-bundles.serial.test.tsindex fe0d4338fa..578258255a 100644--- a/test/persistence-skill-bundles.serial.test.ts+++ b/test/persistence-skill-bundles.serial.test.ts@@ -11,6 +11,7 @@ import { submissionAuthority } from '../src/core/persistence/authority.ts';import { BUNDLE_FILE_LIMITS } from '../src/core/persistence/bundle-files.ts';import { publishMutation, recoverPublication, type PreparedMutation } from '../src/core/persistence/coordinator.ts';import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';import { cancelWriteRequest } from '../src/core/persistence/control.ts';import { advanceEffectCursor, claimPersistenceEffect, completeEffect, renewPersistenceEffectClaim } from '../src/core/persistence/effect-journal.ts';import { sha256 } from '../src/core/persistence/digest.ts';@@ -274,15 +275,15 @@ describe('typed skill bundle persistence', () => {await expect(f.engine.transaction(async tx => { await declarePersistenceProtocol(tx); await tx.executeRaw(query, params); })).rejects.toThrow('writer_coordinator_required');await f.engine.transaction(async tx => {await declarePersistenceProtocol(tx);- await withCoordinatedWrite(tx, [sourceId], () => tx.executeRaw(query, params));+ await withCoordinatedWrite(tx, [sourceId], () => tx.executeRaw(query, params), TEST_WRITE_ATTRIBUTION);});await expect(f.engine.transaction(async tx => {await declarePersistenceProtocol(tx);- await withCoordinatedWrite(tx, ['default'], () => tx.executeRaw("DELETE FROM shared_skill_heads WHERE name='guarded-example'"));+ await withCoordinatedWrite(tx, ['default'], () => tx.executeRaw("DELETE FROM shared_skill_heads WHERE name='guarded-example'"), TEST_WRITE_ATTRIBUTION);})).rejects.toThrow('writer_coordinator_required');await expect(f.engine.transaction(async tx => {await declarePersistenceProtocol(tx);- await withCoordinatedWrite(tx, [sourceId], () => tx.executeRaw("UPDATE shared_skill_heads SET source_id='default' WHERE name='guarded-example'"));+ await withCoordinatedWrite(tx, [sourceId], () => tx.executeRaw("UPDATE shared_skill_heads SET source_id='default' WHERE name='guarded-example'"), TEST_WRITE_ATTRIBUTION);})).rejects.toThrow('writer_coordinator_required');const [head] = await f.engine.executeRaw<{ source_id: string }>("SELECT source_id FROM shared_skill_heads WHERE name='guarded-example'");expect(head.source_id).toBe(sourceId);@@ -369,7 +370,7 @@ describe('typed skill bundle persistence', () => {await tx.executeRaw(`INSERT INTO shared_skill_packs(source_id,source_incarnation,pack_id,revision,manifest,manifest_hash)VALUES($1,$2::uuid,'race-example-pack',$3::uuid,$4::text::jsonb,$5)`,[sourceId, f.binding.source_incarnation, revision, packBytes, sha256(packBytes)]);- });+ }, TEST_WRITE_ATTRIBUTION);});const canonical = { bytes: readFileSync(join(f.root, pending.path), 'base64'), manifest: readFileSync(join(f.root, 'skillpack.json'), 'base64'),packs: await f.engine.executeRaw('SELECT * FROM shared_skill_packs ORDER BY source_id'),diff --git a/test/persistence-staging.test.ts b/test/persistence-staging.test.tsindex cc7bec80e6..9a8814d14f 100644--- a/test/persistence-staging.test.ts+++ b/test/persistence-staging.test.ts@@ -15,6 +15,7 @@ import { submissionAuthority } from '../src/core/persistence/authority.ts';import { admitWrite, claimNextWrite, completeWrite, clearResolvedRecovery, getWriteRequestById, prepareRecovery } from '../src/core/persistence/journal.ts';import { publishMutation, recoverPublication } from '../src/core/persistence/coordinator.ts';import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';import { reserveEffectRecovery, recoverEffectPublication } from '../src/core/persistence/effect-recovery.ts';import type { EffectRecovery, PersistenceEffect } from '../src/core/persistence/effect-model.ts';import { recoveryStagingFile } from '../src/core/persistence/staging.ts';@@ -250,7 +251,7 @@ test('withdrawal mirror staging preserves unexpected bytes and only finishes forfor (const cases of fixtures) {const f = cases[5]; const { row } = await accepted(f);await f.engine.transaction(tx => withCoordinatedWrite(tx, [f.sourceId], () => tx.putPage('page',- { type: 'note', title: 'Withdrawn example', compiled_truth: 'Current sanitized content.', frontmatter: {} }, { sourceId: f.sourceId })));+ { type: 'note', title: 'Withdrawn example', compiled_truth: 'Current sanitized content.', frontmatter: {} }, { sourceId: f.sourceId }), TEST_WRITE_ATTRIBUTION));const snapshot = (await f.engine.readPageSnapshot('page', { sourceId: f.sourceId }))!;await f.engine.transaction(tx => completeWrite(tx, row, 'committed', { revision: snapshot.revision }));const [effect] = await f.engine.executeRaw<PersistenceEffect>(`INSERT INTO persistence_effectsdiff --git a/test/persistence-sync-checkpoint-validation.test.ts b/test/persistence-sync-checkpoint-validation.test.tsindex 82a74612e1..d3c0cf4654 100644--- a/test/persistence-sync-checkpoint-validation.test.ts+++ b/test/persistence-sync-checkpoint-validation.test.ts@@ -11,6 +11,7 @@ import { claimWorktree, getWorktreeBinding } from '../src/core/persistence/ownerimport { performManagedSync } from '../src/core/persistence/sync-run.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';import { INCOMPLETE_SYNC_RECEIPT_SQL, checkpointRetryCommand, findIncompleteSyncReceipt, formatCheckpointTimeoutHint, readRequestIndexStates } from '../src/core/persistence/checkpoint-validation.ts';import { persistenceOperations } from '../src/core/ops/persistence.ts';import { printManagedSyncDiagnostic } from '../src/commands/sync-diagnostics.ts';@@ -137,7 +138,7 @@ test('#5762 a validation statement timeout fails the checkpoint terminally withexpect(lines.join('')).toContain('Docs: docs/guides/write-refusals.md#checkpoint-validation-timeout');// Nothing is left queued ahead of other writes to the source.- await engine.transaction(tx => withCoordinatedWrite(tx, [f.id], () => tx.executeRaw("UPDATE pages SET title='edited' WHERE source_id=$1 AND slug='a'", [f.id])));+ await engine.transaction(tx => withCoordinatedWrite(tx, [f.id], () => tx.executeRaw("UPDATE pages SET title='edited' WHERE source_id=$1 AND slug='a'", [f.id]), TEST_WRITE_ATTRIBUTION));expect(await engine.executeRaw("SELECT id FROM persistence_requests WHERE source_id=$1 AND state IN ('queued','running','recovering')", [f.id])).toEqual([]);// The receipt rebuilds the same hint from its durable code after a restart.diff --git a/test/persistence-sync-failures.serial.test.ts b/test/persistence-sync-failures.serial.test.tsindex b6814c3a25..90d7519f1b 100644--- a/test/persistence-sync-failures.serial.test.ts+++ b/test/persistence-sync-failures.serial.test.ts@@ -19,6 +19,7 @@ import { readManagedSyncFailures } from '../src/core/persistence/sync-failures.timport { checkSyncFailures } from '../src/commands/doctor/checks/sync-failures.ts';import { purgeStaleCheckpoints } from '../src/core/op-checkpoint.ts';import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';import { OperationError } from '../src/core/ops/contract.ts';import { admitWrite, completeWrite, claimNextWrite, markRecovering } from '../src/core/persistence/journal.ts';import { localHostId } from '../src/core/persistence/identity.ts';@@ -62,12 +63,12 @@ test('withdrawal-conflicted sync resumes only through explicit guarded rediscoveconst options = { sourceId: f.id, noPull: true, noEmbed: true, noExtract: true };expect((await performManagedSync(engine, options)).status).toBe('first_sync');const fact = await engine.transaction(tx => withCoordinatedWrite(tx, [f.id], () =>- tx.insertFact({ fact: 'synthetic sync withdrawal', source: 'synthetic', visibility: 'world' }, { source_id: f.id })));+ tx.insertFact({ fact: 'synthetic sync withdrawal', source: 'synthetic', visibility: 'world' }, { source_id: f.id }), TEST_WRITE_ATTRIBUTION));writeFileSync(join(f.root, 'a.md'), 'First updated observation.\n');writeFileSync(join(f.root, 'z.md'), `Preserve this new prose.\n${body}`); commit(f.root);expect((await performManagedSync(engine, options, { maxPages: 1, maxMs: 1000 })).status).toBe('partial');await disposePersistenceConsumer(engine);- await engine.transaction(tx => withCoordinatedWrite(tx, [f.id], () => recordFactWithdrawal(tx, fact.id, f.id)));+ await engine.transaction(tx => withCoordinatedWrite(tx, [f.id], () => recordFactWithdrawal(tx, fact.id, f.id), TEST_WRITE_ATTRIBUTION));await expect(performManagedSync(engine, options)).rejects.toMatchObject({ code: 'revision_conflict' });expect(await readManagedSyncFailures(engine, [f.id])).toEqual([expect.objectContaining({ phase: 'freeze', path: 'z.md', code: 'revision_conflict' })]);await expect(performManagedSync(engine, options)).rejects.toMatchObject({ code: 'revision_conflict' });@@ -223,7 +224,7 @@ test('checkpoint, discovery, and freeze failures remain diagnosable without a ficonst f = await fixture(engine, { 'note.md': 'A stable observation before checkpoint.\n' });const options = { sourceId: f.id, noPull: true };expect((await performManagedSync(engine, options, { maxPages: 1, maxMs: 1000 })).status).toBe('partial');- await engine.transaction(tx => withCoordinatedWrite(tx, [f.id], () => tx.executeRaw('UPDATE sources SET last_commit=$2 WHERE id=$1', [f.id, f.head])));+ await engine.transaction(tx => withCoordinatedWrite(tx, [f.id], () => tx.executeRaw('UPDATE sources SET last_commit=$2 WHERE id=$1', [f.id, f.head]), TEST_WRITE_ATTRIBUTION));const blocked = await performManagedSync(engine, options);expect(blocked).toEqual(expect.objectContaining({ status: 'blocked_by_failures', failures: [expect.objectContaining({ path: '<checkpoint>', phase: 'checkpoint', code: 'revision_conflict' })] }));expect(await performManagedSync(engine, options)).toEqual(blocked);@@ -248,7 +249,7 @@ test('checkpoint, discovery, and freeze failures remain diagnosable without a fiawait performManagedSync(engine, { sourceId: c.id, noPull: true }, { maxPages: 1, maxMs: 1000 });await engine.transaction(tx => withCoordinatedWrite(tx, [c.id], () => tx.putPage('b', {type: 'note', title: 'b', compiled_truth: 'A newer accepted database observation.', timeline: '', frontmatter: {}, content_hash: 'newer',- }, { sourceId: c.id })));+ }, { sourceId: c.id }), TEST_WRITE_ATTRIBUTION));await expect(performManagedSync(engine, { sourceId: c.id, noPull: true })).rejects.toMatchObject({ code: 'revision_conflict' });expect(await readManagedSyncFailures(engine, [c.id])).toEqual([expect.objectContaining({ phase: 'freeze', path: 'b.md', request_id: null, target: c.head })]);expect((await engine.getPage('b', { sourceId: c.id }))?.compiled_truth).toContain('newer accepted');diff --git a/test/persistence-sync-origin-native.serial.test.ts b/test/persistence-sync-origin-native.serial.test.tsindex 9a29fb3691..0cde988f5b 100644--- a/test/persistence-sync-origin-native.serial.test.ts+++ b/test/persistence-sync-origin-native.serial.test.ts@@ -20,6 +20,7 @@ import { admitWrite, claimNextWrite, getWriteRequest } from '../src/core/persistimport { localHostId } from '../src/core/persistence/identity.ts';import { publishMutation } from '../src/core/persistence/coordinator.ts';import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';import { computeSyncDelta } from '../src/core/sync-delta.ts';import { sha256 } from '../src/core/persistence/digest.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';@@ -244,7 +245,7 @@ for (const alias of [false, true]) check(`native historical ${alias ? 'alias' :if (process.platform !== 'win32') files[literal] = content;const f = await fixture(engine, literal, alias ? 'legacy-example' : 'notes/example', files);const history = await engine.getVersions(f.slug, { sourceId: f.id });- await engine.transaction(tx => withCoordinatedWrite(tx, [f.id], () => tx.executeRaw('UPDATE sources SET last_commit=$2 WHERE id=$1', [f.id, f.head])));+ await engine.transaction(tx => withCoordinatedWrite(tx, [f.id], () => tx.executeRaw('UPDATE sources SET last_commit=$2 WHERE id=$1', [f.id, f.head]), TEST_WRITE_ATTRIBUTION));const revised = content.replace('title: Example note', 'title: "Example note"');writeFileSync(join(f.root, 'notes/example.md'), revised);execFileSync('git', ['-C', f.root, 'add', 'notes/example.md']);@@ -295,7 +296,7 @@ check('deleting an unowned filename preserves the live or tombstoned foreign-oriawait engine.transaction(tx => withCoordinatedWrite(tx, [f.id], async () => {await tx.executeRaw('UPDATE sources SET last_commit=$2 WHERE id=$1', [f.id, f.head]);if (deleted) await tx.softDeletePage(f.slug, { sourceId: f.id });- }));+ }, TEST_WRITE_ATTRIBUTION));const before = await engine.readPageSnapshot(f.slug, { sourceId: f.id, includeDeleted: true });const history = await engine.getVersions(f.slug, { sourceId: f.id });unlinkSync(join(f.root, 'notes/example.md'));@@ -321,7 +322,7 @@ check('unowned deletion rechecks absent ownership and file bytes at publication''notes/recorded.md': content, 'notes/example.md': content,});await engine.transaction(tx => withCoordinatedWrite(tx, [f.id], () =>- tx.executeRaw('UPDATE sources SET last_commit=$2 WHERE id=$1', [f.id, f.head])));+ tx.executeRaw('UPDATE sources SET last_commit=$2 WHERE id=$1', [f.id, f.head]), TEST_WRITE_ATTRIBUTION));unlinkSync(join(f.root, 'notes/example.md'));execFileSync('git', ['-C', f.root, 'add', '-A']);execFileSync('git', ['-C', f.root, 'commit', '-qm', 'Remove the unowned duplicate']);@@ -355,7 +356,7 @@ check('unowned deletion rechecks absent ownership and file bytes at publication'check('a genuine committed Git deletion commits one deletion and the exact checkpoint', async engine => {const f = await fixture(engine);- await engine.transaction(tx => withCoordinatedWrite(tx, [f.id], () => tx.executeRaw('UPDATE sources SET last_commit=$2 WHERE id=$1', [f.id, f.head])));+ await engine.transaction(tx => withCoordinatedWrite(tx, [f.id], () => tx.executeRaw('UPDATE sources SET last_commit=$2 WHERE id=$1', [f.id, f.head]), TEST_WRITE_ATTRIBUTION));const history = await engine.getVersions(f.slug, { sourceId: f.id });unlinkSync(join(f.root, 'notes/example.md'));execFileSync('git', ['-C', f.root, 'add', '-A']);diff --git a/test/persistence-sync-overtaken-cursor-5522.test.ts b/test/persistence-sync-overtaken-cursor-5522.test.tsindex 91ba3a2659..6f279ba8e7 100644--- a/test/persistence-sync-overtaken-cursor-5522.test.ts+++ b/test/persistence-sync-overtaken-cursor-5522.test.ts@@ -10,6 +10,7 @@ import { claimWorktree } from '../src/core/persistence/ownership.ts';import { performManagedSync } from '../src/core/persistence/sync-run.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';import { withEnv } from './helpers/with-env.ts';@@ -78,7 +79,7 @@ test('#5522 a foreign write to the page at that origin still refuses the resume'await performManagedSync(engine, f.base, { maxPages: 1, maxMs: 60_000 });await performManagedSync(engine, f.working);await engine.transaction(tx => withCoordinatedWrite(tx, [f.id], () => tx.executeRaw(- "UPDATE pages SET compiled_truth='A foreign edit after the working-tree import.',content_hash='foreign' WHERE source_id=$1 AND slug='b'", [f.id])));+ "UPDATE pages SET compiled_truth='A foreign edit after the working-tree import.',content_hash='foreign' WHERE source_id=$1 AND slug='b'", [f.id]), TEST_WRITE_ATTRIBUTION));await expect(performManagedSync(engine, f.base)).rejects.toMatchObject({ code: 'page_identity_changed' });expect(await imports(engine, f.id)).toEqual(['a', 'b', 'c']);expect((await engine.getPage('b', { sourceId: f.id }))?.compiled_truth).toBe('A foreign edit after the working-tree import.');@@ -88,7 +89,7 @@ test('#5522 a page soft-deleted at that origin, or a pinned page deleted and recconst deleted = await fixture(engine, ['a', 'b']);await performManagedSync(engine, deleted.base, { maxPages: 1, maxMs: 60_000 });await performManagedSync(engine, deleted.working);- await engine.transaction(tx => withCoordinatedWrite(tx, [deleted.id], () => tx.softDeletePage('b', { sourceId: deleted.id })));+ await engine.transaction(tx => withCoordinatedWrite(tx, [deleted.id], () => tx.softDeletePage('b', { sourceId: deleted.id }), TEST_WRITE_ATTRIBUTION));await expect(performManagedSync(engine, deleted.base)).rejects.toMatchObject({ code: 'page_identity_changed' });// An entry enumerated against an existing page keeps its pinned identity.@@ -98,7 +99,7 @@ test('#5522 a page soft-deleted at that origin, or a pinned page deleted and reccommit(pinned.root);await performManagedSync(engine, pinned.base, { maxPages: 1, maxMs: 60_000 });const before = await engine.getPage('b', { sourceId: pinned.id });- await engine.transaction(tx => withCoordinatedWrite(tx, [pinned.id], () => tx.softDeletePage('b', { sourceId: pinned.id })));+ await engine.transaction(tx => withCoordinatedWrite(tx, [pinned.id], () => tx.softDeletePage('b', { sourceId: pinned.id }), TEST_WRITE_ATTRIBUTION));await performManagedSync(engine, pinned.working);const after = await engine.getPage('b', { sourceId: pinned.id });expect(after?.compiled_truth).toContain('Revised observation b');diff --git a/test/persistence-timeline-identity.test.ts b/test/persistence-timeline-identity.test.tsindex 9a6ab95765..ed7c96dba0 100644--- a/test/persistence-timeline-identity.test.ts+++ b/test/persistence-timeline-identity.test.ts@@ -8,6 +8,7 @@ import type { OperationContext } from '../src/core/ops/contract.ts';import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';import { timelineOperations } from '../src/core/ops/timeline.ts';import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';const root = mkdtempSync(join(tmpdir(), 'gbrain-timeline-identity-'));@@ -72,7 +73,7 @@ test('public timeline replay survives page removal and recreation without touchiawait submit('delete_page', { slug, expected_revision: (await engine.readPageSnapshot(slug, { sourceId }))!.revision });await disposePersistenceConsumer(engine);// Model later purge without removing durable receipts or source authority.- await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => tx.deletePage(slug, { sourceId })));+ await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => tx.deletePage(slug, { sourceId }), TEST_WRITE_ATTRIBUTION));expect(await engine.readPageSnapshot(slug, { sourceId })).toBeNull();expect(await operation.handler(ctx, params)).toEqual(first);await expect(operation.handler(ctx, { ...params, summary: 'Altered retry' })).rejects.toMatchObject({ code: 'idempotency_conflict' });diff --git a/test/persistence-withdrawal-retry.test.ts b/test/persistence-withdrawal-retry.test.tsindex e601654f6c..d5ead10599 100644--- a/test/persistence-withdrawal-retry.test.ts+++ b/test/persistence-withdrawal-retry.test.ts@@ -9,6 +9,7 @@ import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { registerLocalWriter } from '../src/core/persistence/identity.ts';import { submitForgetMutation } from '../src/core/persistence/memory-mutations.ts';import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';import { getWriteRequest } from '../src/core/persistence/journal.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';import { withEnv } from './helpers/with-env.ts';@@ -39,7 +40,7 @@ async function seed(engine: BrainEngine, slug: string) {const page = await tx.putPage(slug, { type: 'note', title: 'Example', compiled_truth: 'Canonical example', timeline: '', frontmatter: {} }, { sourceId });const fact = await tx.insertFact({ fact: `Withdraw ${slug}`, source: 'test', entity_slug: slug, visibility: 'world' }, { source_id: sourceId });return { page, fact };- }));+ }, TEST_WRITE_ATTRIBUTION));}for (const boundary of ['admission-counter', 'completed-withdrawal'] as const) {diff --git a/test/persistence-writer-fences.test.ts b/test/persistence-writer-fences.test.tsindex 09153bad58..09b5541dfb 100644--- a/test/persistence-writer-fences.test.ts+++ b/test/persistence-writer-fences.test.ts@@ -15,6 +15,7 @@ import { hardenBrainRepo } from '../src/core/brain-repo-durability.ts';import { recordManagedRoots, registeredManagedRoots } from '../src/core/persistence/root-registry.ts';import { assertManagedFilesystemWrite, withFilesystemPublication } from '../src/core/persistence/filesystem-guard.ts';import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';import { withEnv } from './helpers/with-env.ts';@@ -84,10 +85,10 @@ test('free-text aliases and sync checkpoints require an authorized publication tawait engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], async () => {await tx.executeRaw("UPDATE sources SET last_commit='owned' WHERE id=$1", [sourceId]);await tx.executeRaw('INSERT INTO page_aliases(source_id,alias_norm,slug) VALUES($1,$2,$3)', [sourceId, 'example alias', 'notes/example']);- }));+ }, TEST_WRITE_ATTRIBUTION));expect((await engine.executeRaw<{ last_commit: string }>('SELECT last_commit FROM sources WHERE id=$1', [sourceId]))[0].last_commit).toBe('owned');await expect(engine.executeRaw("UPDATE sources SET last_commit='after-capability' WHERE id=$1", [sourceId])).rejects.toThrow('writer_coordinator_required');- await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => tx.executeRaw('DELETE FROM page_aliases WHERE source_id=$1', [sourceId])));+ await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => tx.executeRaw('DELETE FROM page_aliases WHERE source_id=$1', [sourceId]), TEST_WRITE_ATTRIBUTION));}});diff --git a/test/remember-entity-inference.test.ts b/test/remember-entity-inference.test.tsindex 8f4976b97b..c4f09fe6d9 100644--- a/test/remember-entity-inference.test.ts+++ b/test/remember-entity-inference.test.ts@@ -13,6 +13,7 @@ import { operationsByName } from '../src/core/operations.ts';import { parseFactsFence } from '../src/core/facts-fence.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';import { registerLocalWriter } from '../src/core/persistence/identity.ts';import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';import { LEGACY_EMBEDDING_CONFIG } from './helpers/legacy-embedding-config.ts';@@ -27,7 +28,7 @@ const remember = (params: Record<string, unknown>, ctx = context()) =>async function putEntity(slug: string, title: string, type: string, body = `# ${title}`, frontmatter: Record<string, unknown> = {}) {await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () =>- tx.putPage(slug, { type, title, compiled_truth: body, frontmatter }, { sourceId })));+ tx.putPage(slug, { type, title, compiled_truth: body, frontmatter }, { sourceId }), TEST_WRITE_ATTRIBUTION));}async function factRow(id: string) {const [row] = await engine.executeRaw<{ entity_slug: string | null; context: string | null; row_num: number | null; expired_at: Date | null; superseded_by: number | null }>(diff --git a/test/repair-captured-facts.test.ts b/test/repair-captured-facts.test.tsindex 686d990195..448e70639f 100644--- a/test/repair-captured-facts.test.ts+++ b/test/repair-captured-facts.test.ts@@ -25,6 +25,7 @@ import { runRepairCommand } from '../src/commands/repair.ts';import { capturedFactsCheck } from '../src/commands/doctor/checks/captured-facts.ts';import { runWaveChecks } from '../src/commands/doctor/wave-checks.ts';import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';import { writeSingleFact } from '../src/core/facts/write-single.ts';import { managedBrain } from './helpers/managed-brain.ts';@@ -102,7 +103,7 @@ for (const backend of testBackends()) {const normal = await write('Alice Example joined Acme Example in 2024', ALICE, 'hook:writeback', 'sess-normal');const gone = await write('Alice Example likes long walks', ALICE, 'hook:writeback', 'sess-gone');await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.executeRaw(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, source)- VALUES ('default', $1, 'Alice Example lives in Lisbon', 'fact', 'private', 'cli:remember')`, [ALICE])));+ VALUES ('default', $1, 'Alice Example lives in Lisbon', 'fact', 'private', 'cli:remember')`, [ALICE]), TEST_WRITE_ATTRIBUTION));const finding = await capturedFactsCheck(engine);expect(finding.status).toBe('warn');@@ -162,7 +163,7 @@ for (const backend of testBackends()) {const id = (await writeSingleFact(engine, 'default', { fact: 'Alice Example prefers tea', entity: ALICE, provenance: 'hook:writeback', sessionId: 'sess-self' })).id;const preview = await repair(engine, []);await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () =>- tx.executeRaw("UPDATE facts SET visibility='world' WHERE id=$1", [id])));+ tx.executeRaw("UPDATE facts SET visibility='world' WHERE id=$1", [id]), TEST_WRITE_ATTRIBUTION));const applied = await repair(engine, applyArgs(preview));expect(applied.results[0].outcomes).toEqual({ changed_since_preview: 1 });expect(await active(engine, id)).toBe(true);diff --git a/test/repair-command.test.ts b/test/repair-command.test.tsindex 6a01e3aec2..25b463bec5 100644--- a/test/repair-command.test.ts+++ b/test/repair-command.test.ts@@ -12,6 +12,7 @@ import type { BrainEngine } from '../src/core/engine.ts';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';import { claimWorktree } from '../src/core/persistence/ownership.ts';import { resolveRepairScope, runRepair } from '../src/core/repair/core.ts';@@ -75,7 +76,7 @@ async function pageWithHistory(engine: BrainEngine, sourceId: string, slug: striawait submitPageMutation(ctxFor(engine, sourceId), { operation: 'put_page', params: { slug, content: page(`Body of ${slug}.`), request_id: randomUUID() } });await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => tx.executeRaw(`INSERT INTO timeline_entries(page_id,date,source,summary,detail) SELECT id,'2026-07-01','legacy',$3,'' FROM pages WHERE source_id=$1 AND slug=$2`,- [sourceId, slug, `History of ${slug}`])));+ [sourceId, slug, `History of ${slug}`]), TEST_WRITE_ATTRIBUTION));}const markedPages = async (engine: BrainEngine, sourceId: string) => (await engine.executeRaw<{ slug: string }>(@@ -192,7 +193,7 @@ describe('timeline_history doctor check', () => {await pageWithHistory(engine, source, 'notes/a');await pageWithHistory(engine, source, 'notes/b');await engine.transaction(tx => withCoordinatedWrite(tx, [source], () => tx.executeRaw(- `INSERT INTO timeline_entries(page_id,date,source,summary,detail) SELECT id,'2026-07-02','','No source row','' FROM pages WHERE source_id=$1 AND slug='notes/a'`, [source])));+ `INSERT INTO timeline_entries(page_id,date,source,summary,detail) SELECT id,'2026-07-02','','No source row','' FROM pages WHERE source_id=$1 AND slug='notes/a'`, [source]), TEST_WRITE_ATTRIBUTION));const full = await timelineHistoryCheck(engine, source);expect(full.status).toBe("warn");expect(full.details).toMatchObject({ materializable_rows: 2, kept_unrenderable_rows: 1, pages_affected: 2, count: 'exact', truncated: false });diff --git a/test/repair-extractor-facts.test.ts b/test/repair-extractor-facts.test.tsindex a5b4df526e..e6fc69a8e1 100644--- a/test/repair-extractor-facts.test.ts+++ b/test/repair-extractor-facts.test.ts@@ -31,6 +31,7 @@ import { runRepairCommand } from '../src/commands/repair.ts';import { extractorFactsRepair, EXTRACTOR_FACTS_INTENT } from '../src/core/repair/extractor-facts.ts';import { extractorFactsCheck } from '../src/commands/doctor/checks/extractor-facts.ts';import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';import { compactWriteReceipts } from '../src/core/persistence/journal.ts';import { declarePersistenceProtocol } from '../src/core/persistence/protocol.ts';@@ -113,12 +114,12 @@ for (const backend of testBackends()) {await tx.executeRaw('UPDATE persistence_requests SET completed_at=now(), consumer_version=$2 WHERE id=$1::uuid', [row.id, opts.consumer === undefined ? null : opts.consumer]);};if ((opts.transaction ?? 'same') === 'same') {- await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], async () => { await complete(tx); await expire(tx); }));+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], async () => { await complete(tx); await expire(tx); }, TEST_WRITE_ATTRIBUTION));} else {await engine.transaction(tx => complete(tx));// PGLite's now() has millisecond resolution: a later transaction is at least one tick later.await new Promise(resolve => setTimeout(resolve, 5));- await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => expire(tx)));+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => expire(tx), TEST_WRITE_ATTRIBUTION));}return row.id;}@@ -143,10 +144,10 @@ for (const backend of testBackends()) {await tx.executeRaw(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, source, row_num, source_markdown_slug)VALUES ('default', $1, 'Alice sends the deck on Friday', 'commitment', 'private', $2, 9, 'conversations/retained')`, [ENTITY, EXTRACTOR]);await tx.executeRaw("INSERT INTO fact_withdrawals (source_id, visibility, subject, fact_hash) VALUES ('default', 'private', '*', gbrain_fact_fingerprint('Alice withdrew this claim'))");- }));+ }, TEST_WRITE_ATTRIBUTION));await prefixExpire(engine, ctx, 'conversations/retained', { ids: [retainedA, retainedB, superseded, withdrawn, duplicated] });await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () =>- tx.executeRaw('UPDATE facts SET superseded_by=$1 WHERE id=$2', [retainedA, superseded])));+ tx.executeRaw('UPDATE facts SET superseded_by=$1 WHERE id=$2', [retainedA, superseded]), TEST_WRITE_ATTRIBUTION));const compacted = await prefixExpire(engine, ctx, 'conversations/compacted');// Older than the 30-day receipt retention, so compaction drops its intent but keeps its completion.await engine.transaction(async tx => {@@ -155,7 +156,7 @@ for (const backend of testBackends()) {await tx.executeRaw("UPDATE persistence_requests SET completed_at=completed_at-interval '40 days' WHERE id=$1::uuid", [compacted]);});await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () =>- tx.executeRaw("UPDATE facts SET expired_at=expired_at-interval '40 days' WHERE source_markdown_slug='conversations/compacted'")));+ tx.executeRaw("UPDATE facts SET expired_at=expired_at-interval '40 days' WHERE source_markdown_slug='conversations/compacted'"), TEST_WRITE_ATTRIBUTION));expect(await compactWriteReceipts(engine, 30)).toBeGreaterThanOrEqual(1);expect((await engine.executeRaw<{ compacted: boolean }>('SELECT compacted FROM persistence_requests WHERE id=$1::uuid', [compacted]))[0].compacted).toBe(true);await prefixExpire(engine, ctx, 'conversations/separate', { transaction: 'separate' });@@ -247,7 +248,7 @@ for (const backend of testBackends()) {const preview = await repair(engine, null, []);expect(preview.results[0].residuals).toEqual({ evidenced: 2, ambiguous: 0, excluded: 0 });await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () =>- tx.executeRaw("UPDATE facts SET fact='Alice sends the revised deck' WHERE id=$1", [ids[1]])));+ tx.executeRaw("UPDATE facts SET fact='Alice sends the revised deck' WHERE id=$1", [ids[1]]), TEST_WRITE_ATTRIBUTION));const applied = await repair(engine, null, ['--apply', '--expect', hashOf(preview)]);expect(applied.results[0]).toMatchObject({ applied: 1, outcomes: { partially_restored: 1 } });expect(applied.results[0].outcome_items![0].reason).toBe(`1 of 2 restored; changed since the preview: ${ids[1]}`);@@ -261,7 +262,7 @@ for (const backend of testBackends()) {await prefixExpire(engine, ctx, 'conversations/dupes', { transaction: 'separate' });const [{ id: later }] = await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.executeRaw<{ id: number }>(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, source, row_num, source_markdown_slug)- VALUES ('default', $1, 'Alice sends the deck', 'commitment', 'private', $2, 5, 'conversations/dupes') RETURNING id::int AS id`, [ENTITY, EXTRACTOR])));+ VALUES ('default', $1, 'Alice sends the deck', 'commitment', 'private', $2, 5, 'conversations/dupes') RETURNING id::int AS id`, [ENTITY, EXTRACTOR]), TEST_WRITE_ATTRIBUTION));await prefixExpire(engine, ctx, 'conversations/dupes', { ids: [Number(later)] });const preview = await repair(engine, null, []);expect(preview.results[0].listing!.map(entry => [Number(entry.item.split('#')[1]), entry.class])).toEqual([diff --git a/test/safe-chunk-reseal.test.ts b/test/safe-chunk-reseal.test.tsindex 224b2a39a7..766766f323 100644--- a/test/safe-chunk-reseal.test.ts+++ b/test/safe-chunk-reseal.test.ts@@ -23,6 +23,7 @@ import { runImport } from '../src/commands/import.ts';import { contentHashLegacy } from '../src/core/utils.ts';import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';import { claimWorktree } from '../src/core/persistence/ownership.ts';import { resolveRepairScope, runRepair } from '../src/core/repair/core.ts';@@ -201,7 +202,7 @@ for (const kind of backends) {let codeSlug = '';await importCodeFile(engine, 'lib/legacy.ts', code, { sourceId, noEmbed: true, prepare: async value => {codeSlug = value.slug;- await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => value.apply(tx)));+ await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => value.apply(tx), TEST_WRITE_ATTRIBUTION));return value.result;} });await engine.executeRaw('UPDATE pages SET chunker_version=1 WHERE source_id=$1', [sourceId]);diff --git a/test/shared-skills-catalog-performance.test.ts b/test/shared-skills-catalog-performance.test.tsindex bf1b6f375f..ecd2d0bc7b 100644--- a/test/shared-skills-catalog-performance.test.ts+++ b/test/shared-skills-catalog-performance.test.ts@@ -10,6 +10,7 @@ import { claimWorktree } from '../src/core/persistence/ownership.ts';import { activateSharedSkillPersistence } from '../src/core/persistence/skill-activation.ts';import { declarePersistenceProtocol } from '../src/core/persistence/protocol.ts';import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';import { getSharedSkill, listSharedSkills } from '../src/core/shared-skills/catalog.ts';import { normalizeSkillFiles, skillMetadata } from '../src/core/shared-skills/manifest.ts';import { withEnv } from './helpers/with-env.ts';@@ -52,7 +53,7 @@ test.skipIf(process.env.GBRAIN_TEST_SHARED_SKILLS_BENCHMARK !== '1')('measure seawait tx.executeRaw(`INSERT INTO shared_skill_revisions(source_id,source_incarnation,pack_id,name,revision,metadata,files,policy_epoch,request_id)SELECT 'default',$1::uuid,'benchmark',r.name,r.revision,r.metadata,r.files,'legacy-prose',$3::uuidFROM jsonb_to_recordset($2::text::jsonb) AS r(name text,revision uuid,metadata jsonb,files jsonb)`, [source.incarnation, JSON.stringify(rows), randomUUID()]);- });+ }, TEST_WRITE_ATTRIBUTION);});const rssBefore = process.memoryUsage().rss;calls = 0;diff --git a/test/shared-skills-catalog.test.ts b/test/shared-skills-catalog.test.tsindex f56cfdc8ca..3e7b59c8ae 100644--- a/test/shared-skills-catalog.test.ts+++ b/test/shared-skills-catalog.test.ts@@ -14,6 +14,7 @@ import { submissionAuthority } from '../src/core/persistence/authority.ts';import { cancelWriteRequest } from '../src/core/persistence/control.ts';import { declarePersistenceProtocol } from '../src/core/persistence/protocol.ts';import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';import { getSharedSkill, getSharedSkillAsset, listSharedSkills } from '../src/core/shared-skills/catalog.ts';import { getSharedSkillPolicy, setSharedSkillPolicy as approvePolicy } from '../src/core/shared-skills/policy.ts';import { normalizeSkillFiles } from '../src/core/shared-skills/manifest.ts';@@ -466,7 +467,7 @@ test('retention preserves active heads, tombstones, delivery, explicit pins andawait disposePersistenceConsumer(f.engine);await f.engine.transaction(async tx => {await declarePersistenceProtocol(tx);- await withCoordinatedWrite(tx, ['default'], () => tx.executeRaw("UPDATE shared_skill_revisions SET created_at=created_at-interval '48 hours' WHERE source_id='default'"));+ await withCoordinatedWrite(tx, ['default'], () => tx.executeRaw("UPDATE shared_skill_revisions SET created_at=created_at-interval '48 hours' WHERE source_id='default'"), TEST_WRITE_ATTRIBUTION);});const authority = await submissionAuthority(f.local, 'put_skill', 'default', f.incarnation, 'skills/alpha/SKILL.md');const binding = (await getWorktreeBinding(f.engine, 'default'))!;@@ -521,7 +522,7 @@ test('retention budget provides real backpressure before canonical file effects'(source_id,source_incarnation,pack_id,name,revision,metadata,files,policy_epoch,request_id)SELECT r.source_id,r.source_incarnation,r.pack_id,r.name,gen_random_uuid(),r.metadata,r.files,r.policy_epoch,r.request_idFROM shared_skill_revisions r CROSS JOIN generate_series(1,$1) n WHERE r.revision=$2::uuid`,- [SHARED_SKILL_RETENTION_LIMITS.sourceRevisions - 1, before.revision]));+ [SHARED_SKILL_RETENTION_LIMITS.sourceRevisions - 1, before.revision]), TEST_WRITE_ATTRIBUTION);});const status = await getSharedSkillRetention(f.local);expect(status.retained_revisions).toBe(SHARED_SKILL_RETENTION_LIMITS.sourceRevisions);@@ -541,7 +542,7 @@ test.skipIf(!postgresUrl)('Postgres retention serializes delivery issuance againconst member = await joinBrain(f.local, { adapter: 'generic', follow_policy: { approved: true } });await f.engine.transaction(async tx => {await declarePersistenceProtocol(tx);- await withCoordinatedWrite(tx, ['default'], () => tx.executeRaw("UPDATE shared_skill_revisions SET created_at=created_at-interval '48 hours' WHERE source_id='default'"));+ await withCoordinatedWrite(tx, ['default'], () => tx.executeRaw("UPDATE shared_skill_revisions SET created_at=created_at-interval '48 hours' WHERE source_id='default'"), TEST_WRITE_ATTRIBUTION);});const key = `${[old.brain_id, old.source_id, old.source_incarnation, old.pack_id, old.name].map(encodeURIComponent).join('/')}@${old.revision}`;const insertBatch = (tx: BrainEngine, sequence: number) => tx.executeRaw(`INSERT INTO shared_skill_delivery_batchesdiff --git a/test/shared-skills-publication-sparse.test.ts b/test/shared-skills-publication-sparse.test.tsindex 07ca874bed..f4fad54a1d 100644--- a/test/shared-skills-publication-sparse.test.ts+++ b/test/shared-skills-publication-sparse.test.ts@@ -10,6 +10,7 @@ import { claimWorktree } from '../src/core/persistence/ownership.ts';import { activateSharedSkillPersistence } from '../src/core/persistence/skill-activation.ts';import { declarePersistenceProtocol } from '../src/core/persistence/protocol.ts';import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';import { sha256 } from '../src/core/persistence/digest.ts';import { adoptSharedSkillpack, submitSharedSkillMutation } from '../src/core/shared-skills/publication.ts';@@ -191,7 +192,7 @@ test('an incomplete sealed inventory fails closed rather than dropping an unaffeconst damaged = manifest(f.root); damaged.shared_skills.skills = damaged.shared_skills.skills.filter(skill => skill.name !== 'beta');await f.engine.transaction(async tx => {await declarePersistenceProtocol(tx);- await withCoordinatedWrite(tx, ['default'], () => tx.executeRaw("UPDATE shared_skill_packs SET manifest=$1::text::jsonb WHERE source_id='default'", [JSON.stringify(damaged)]));+ await withCoordinatedWrite(tx, ['default'], () => tx.executeRaw("UPDATE shared_skill_packs SET manifest=$1::text::jsonb WHERE source_id='default'", [JSON.stringify(damaged)]), TEST_WRITE_ATTRIBUTION);});f.observe();await expect(f.put(f.editor, 'alpha', [prose('alpha', 'Must not commit')])).rejects.toMatchObject({ code: 'revision_conflict' });diff --git a/test/sources-mirror-read-only.test.ts b/test/sources-mirror-read-only.test.tsindex ae016331d4..4c86c87aa3 100644--- a/test/sources-mirror-read-only.test.ts+++ b/test/sources-mirror-read-only.test.ts@@ -28,6 +28,7 @@ import { performManagedSync } from '../src/core/persistence/sync-run.ts';import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';import { submitForgetMutation } from '../src/core/persistence/memory-mutations.ts';import { runSources } from '../src/commands/sources.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';@@ -95,7 +96,7 @@ for (const backend of testBackends()) {/** First sync, a database-only tag, then an upstream edit: the canonical form now differs from the file's bytes (an overlay). */async function overlaySync(m: { id: string; root: string }) {expect(await performManagedSync(engine, { sourceId: m.id, noPull: true })).toMatchObject({ status: 'first_sync', filesImported: 1 });- await engine.transaction(tx => withCoordinatedWrite(tx, [m.id], () => tx.addTag('todos', 'kept-in-brain', { sourceId: m.id })));+ await engine.transaction(tx => withCoordinatedWrite(tx, [m.id], () => tx.addTag('todos', 'kept-in-brain', { sourceId: m.id }), TEST_WRITE_ATTRIBUTION));writeFileSync(join(m.root, 'TODOS.md'), `${TODOS}- keep the mirror pullable\n`);commit(m.root, 'upstream edit');expect(await performManagedSync(engine, { sourceId: m.id, noPull: true })).toMatchObject({ filesImported: 1 });@@ -185,7 +186,7 @@ for (const backend of testBackends()) {content: '---\ntitle: Alice Example\ntype: person\n---\n# Alice Example\n' } });const [{ id }] = await engine.transaction(tx => withCoordinatedWrite(tx, [m.id], () => tx.executeRaw<{ id: number }>(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, source) VALUES ($1, 'people/alice-example', 'Alice prefers mornings', 'preference', 'private', 'test')- RETURNING id::int AS id`, [m.id])));+ RETURNING id::int AS id`, [m.id]), TEST_WRITE_ATTRIBUTION));const forgot = await submitForgetMutation(ctx(m.id), 'forget', { id: Number(id), request_id: randomUUID() }) as { request_id: string };let effects: Array<{ kind: string; state: string; outcome: Record<string, unknown> | null }> = [];for (let i = 0; i < 100; i++) {diff --git a/test/timeline-materialize.test.ts b/test/timeline-materialize.test.tsindex 5e4e06ec8e..2f69cc0c24 100644--- a/test/timeline-materialize.test.ts+++ b/test/timeline-materialize.test.ts@@ -14,6 +14,7 @@ import { parseMarkdown } from '../src/core/markdown.ts';import { importFromContent } from '../src/core/import-file.ts';import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';import { claimWorktree } from '../src/core/persistence/ownership.ts';import { materializeTimeline, prepareCanonicalProjections, renderMaterializedBullet, type ProjectionWriter } from '../src/core/persistence/canonical-projections.ts';@@ -73,7 +74,7 @@ async function fixture(run: (f: Fixture) => Promise<void>) {},legacy: async (slug, row) => { await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => tx.executeRaw(`INSERT INTO timeline_entries(page_id,date,source,summary,detail) SELECT id,$3::date,$4,$5,$6 FROM pages WHERE source_id=$1 AND slug=$2`,- [sourceId, slug, row.date, row.source, row.summary, row.detail ?? '']))); },+ [sourceId, slug, row.date, row.source, row.summary, row.detail ?? '']), TEST_WRITE_ATTRIBUTION)); },timeline: async slug => engine.executeRaw<Row>(`SELECT t.date::text AS date,t.source,t.summary,t.detail FROM timeline_entries tJOIN pages p ON p.id=t.page_id WHERE p.source_id=$1 AND p.slug=$2 AND t.event_page_id IS NULL ORDER BY t.date,t.summary`, [sourceId, slug]),};@@ -223,9 +224,9 @@ describe('#5567 database-only rows are materialized as marked bullets', () => {await f.put(slug, page('Draft.'), { force: true });const rendered = f.file(slug);await f.engine.transaction(tx => withCoordinatedWrite(tx, [f.sourceId], () => tx.executeRaw(- `UPDATE pages SET compiled_truth='', timeline='' WHERE source_id=$1 AND slug=$2`, [f.sourceId, slug])));+ `UPDATE pages SET compiled_truth='', timeline='' WHERE source_id=$1 AND slug=$2`, [f.sourceId, slug]), TEST_WRITE_ATTRIBUTION));await f.engine.transaction(tx => withCoordinatedWrite(tx, [f.sourceId], () =>- importFromContent(tx, slug, rendered, { sourceId: f.sourceId, noEmbed: true, forceRechunk: true })));+ importFromContent(tx, slug, rendered, { sourceId: f.sourceId, noEmbed: true, forceRechunk: true }), TEST_WRITE_ATTRIBUTION));expect(await f.body(slug)).toContain(bullet);await f.put(slug, page('Stale copy.'), { force: true });expect(await f.timeline(slug)).toEqual([normalized]);@@ -271,7 +272,7 @@ describe('#5567 per-writer classes for marked rows', () => {const carried = await materializeTimeline(f.engine, next, slug, prior, writer);expect(carried.materialized).toBe(renders ? 1 : 0);const project = await prepareCanonicalProjections(f.engine, { ...next, timeline: carried.timeline }, slug, f.sourceId, prior, writer);- await f.engine.transaction(tx => withCoordinatedWrite(tx, [f.sourceId], () => project(tx)));+ await f.engine.transaction(tx => withCoordinatedWrite(tx, [f.sourceId], () => project(tx), TEST_WRITE_ATTRIBUTION));expect(await f.timeline(slug)).toEqual(keeps ? [normalized] : []);});});diff --git a/test/withdrawal-followup-writes.test.ts b/test/withdrawal-followup-writes.test.tsindex f08877765b..df899c1b3c 100644--- a/test/withdrawal-followup-writes.test.ts+++ b/test/withdrawal-followup-writes.test.ts@@ -18,6 +18,7 @@ import type { OperationContext } from '../src/core/ops/contract.ts';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { serializePageToMarkdown } from '../src/core/markdown.ts';import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';import { localHostId, registerLocalWriter } from '../src/core/persistence/identity.ts';import { claimWorktree } from '../src/core/persistence/ownership.ts';import { submissionAuthority } from '../src/core/persistence/authority.ts';@@ -63,7 +64,7 @@ async function entity(engine: BrainEngine) {const snapshot = await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], async () => {await tx.putPage(slug, { type: 'person', title: 'Hazel Example', compiled_truth: 'Fictional.', timeline: '', frontmatter: {} }, { sourceId });return (await tx.readPageSnapshot(slug, { sourceId }))!;- }));+ }, TEST_WRITE_ATTRIBUTION));const file = join(root, `${slug}.md`); mkdirSync(dirname(file), { recursive: true });writeFileSync(file, serializePageToMarkdown(snapshot.page, snapshot.tags));const ctx = context(engine, sourceId);diff --git a/test/withdrawal-publication-file.test.ts b/test/withdrawal-publication-file.test.tsindex a8582f670d..ec6143e497 100644--- a/test/withdrawal-publication-file.test.ts+++ b/test/withdrawal-publication-file.test.ts@@ -12,6 +12,7 @@ import { serializePageToMarkdown } from '../src/core/markdown.ts';import { activatePersistence } from '../src/core/persistence/activation.ts';import { submissionAuthority } from '../src/core/persistence/authority.ts';import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';import { publishMutation } from '../src/core/persistence/coordinator.ts';import { localHostId, registerLocalWriter } from '../src/core/persistence/identity.ts';import { admitWrite, claimNextWrite } from '../src/core/persistence/journal.ts';@@ -79,8 +80,8 @@ test('a prepared repo-file write racing a withdrawal leaves the canonical file aexpect(prepared.file?.content).toContain(claim);const fact = await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () =>- tx.insertFact({ fact: claim, source: 'remember', visibility: 'world' }, { source_id: sourceId })));- await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => recordFactWithdrawal(tx, fact.id, sourceId, true)));+ tx.insertFact({ fact: claim, source: 'remember', visibility: 'world' }, { source_id: sourceId }), TEST_WRITE_ATTRIBUTION));+ await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => recordFactWithdrawal(tx, fact.id, sourceId, true), TEST_WRITE_ATTRIBUTION));const boundaries: string[] = [];const rejected = await publishMutation(engine, claimed, prepared, hostId, {