Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

attribution: route legacy facts and takes helpers through maintenanceTransaction

garrytanbea680da5543
diff --git a/docs/architecture/system-of-record.md b/docs/architecture/system-of-record.md
index 734bed20b3..a69c893fbd 100644
--- a/docs/architecture/system-of-record.md
+++ b/docs/architecture/system-of-record.md
@@ -215,8 +215,13 @@ or a physical projection that leaves attribution untouched):
- `src/core/cycle/extract-takes.ts` (2): coordinated per page on managed brains; the unmanaged batch upsert runs in `maintenanceTransaction`.
- `src/core/embed-facts.ts` (1): embedding columns only (physical projection).
- `src/core/embedding-dim-check.ts` (1): embedding columns only (physical projection).
+- `src/core/facts/backstop.ts` (3): the facts backstop's DB-only fallbacks insert each fact in `maintenanceTransaction`; managed brains publish through the facts request preparer.
+- `src/core/facts/fence-write.ts` (2): the markdown-first fence reconcile insert and its page body mirror each run in `maintenanceTransaction`.
+- `src/core/facts/forget.ts` (4): the legacy fence expiry, withdrawal and strike-through each run in `maintenanceTransaction` (nested inside a caller's coordinated write, they keep its actor).
+- `src/core/facts/proposal-supersede.ts` (4): unmanaged `decide` proposal accept and undo run in one `maintenanceTransaction` each; managed brains publish a `decide_proposal` request.
- `src/core/facts/relink-publish.ts` (2): `relink_facts` request preparer.
- `src/core/facts/withdrawal.ts` (1): runs inside the `forget` request's coordinated write.
+- `src/core/facts/write-single.ts` (2): the legacy single-fact insert and its supersession link each run in `maintenanceTransaction`; managed brains publish through the fact request.
- `src/core/import-file.ts` (11): direct markdown, code and image imports, the moved-file rename (`updateSlug`) and the #3694 legacy-hash re-stamp run in `maintenanceTransaction`; managed imports go through the page request preparer.
- `src/core/page-state/materialize.ts` (1): coordinated maintenance.
- `src/core/page-state/rename-alias.ts` (2): the fact slug rewrite runs inside its caller's `updateSlug` transaction, and every caller is attributed.
@@ -241,6 +246,7 @@ or a physical projection that leaves attribution untouched):
- `src/core/repair/frontmatter.ts` (1): a `managed_file_repair` request on managed sources; the unmanaged rename runs in `maintenanceTransaction`.
- `src/core/repair/stale-atoms.ts` (3): a request on managed brains; the unmanaged retirement runs in `maintenanceTransaction`.
- `src/core/sweep.ts` (1): the maintenance sweep's bounded timeline batch runs in `maintenanceTransaction`.
+- `src/core/takes-write.ts` (7): the takes file helpers' DB mirror (add, append, update, supersede, resolve and its self-heal) runs in `maintenanceTransaction`; managed brains publish through the takes request preparer.
- `src/core/timeline-dedup-repair.ts` (1): the legacy timeline source repair rewrites each page's rows in one `maintenanceTransaction`.
- `src/core/timeline-write-through.ts` (2): the timeline write-through's page row splice and entry insert run in one `maintenanceTransaction`.
<!-- write-attribution-covered:end -->
@@ -265,11 +271,6 @@ these write with `NULL` attribution):
- `src/core/enrichment-service.ts` (2): enrichment page and auto-timeline entry.
- `src/core/extract-timeline-from-meetings.ts` (1): meeting timeline batch.
- `src/core/extract/receipt-writer.ts` (1): extraction receipt page.
-- `src/core/facts/backstop.ts` (3): legacy DB-only fact fallbacks.
-- `src/core/facts/fence-write.ts` (2): markdown-first fence reconcile insert and page body refresh.
-- `src/core/facts/forget.ts` (4): legacy forget expiry and fence strike-through.
-- `src/core/facts/proposal-supersede.ts` (4): unmanaged `decide` proposal accept and undo (facts and page body).
-- `src/core/facts/write-single.ts` (2): legacy single-fact insert and supersession.
- `src/core/minions/handlers/ingest-capture.ts` (1): capture ingest soft delete.
- `src/core/ops/extraction.ts` (2): extraction review promote (frontmatter) and reject (soft delete).
- `src/core/output/writer.ts` (4): synthesize-phase BrainWriter pages and timeline.
@@ -279,7 +280,6 @@ these write with `NULL` attribution):
- `src/core/schema-pack/page-to-link.ts` (1): page-to-link conversion soft delete.
- `src/core/schema-pack/retype.ts` (1): schema-pack retype.
- `src/core/schema-pack/sync.ts` (1): schema-pack type sync.
-- `src/core/takes-write.ts` (7): legacy takes file helper mirror rows and resolutions.
- `src/core/think/index.ts` (1): saved `think` result page.
<!-- write-attribution-unattributed:end -->
diff --git a/src/core/facts/backstop.ts b/src/core/facts/backstop.ts
index 787e83acba..50aa4b1024 100644
--- a/src/core/facts/backstop.ts
+++ b/src/core/facts/backstop.ts
@@ -50,6 +50,7 @@ import { decideSingleFact } from './single-prepare.ts';
import { cosineVerdict, dedupCapturedFacts, withCaptureDrops } from './capture-dedup.ts';
import { appendContextNote, type InferredVia } from './subject-infer.ts';
import { inferenceNote, inferMissingSubjects } from './subject-infer-write.ts';
+import { maintenanceTransaction } from '../persistence/attribution.ts';
/**
* Notability-filter vocabulary shared by the durable facts-absorb payload
@@ -793,7 +794,7 @@ async function runPipelineBodyInner(
valid_from: f.valid_from ?? ctx.validFrom,
context: annotateUnverifiedResolution(ctx.sourceSlug ?? input.pageSlug ?? null, resolutionSource, f.entity_inferred),
};
- const result = await ctx.engine.insertFact(newFact, { source_id: ctx.sourceId }); // gbrain-allow-direct-insert: legacy DB-only fallback for unparented / thin-client facts (no entity page to fence onto)
+ const result = await maintenanceTransaction(ctx.engine, tx => tx.insertFact(newFact, { source_id: ctx.sourceId })); // gbrain-allow-direct-insert: legacy DB-only fallback for unparented / thin-client facts (no entity page to fence onto)
fact_ids.push(result.id);
if (result.status === 'inserted') inserted += 1;
else if ((result.status as FactInsertStatus) === 'duplicate') duplicate += 1;
@@ -880,7 +881,7 @@ async function runPipelineBodyInner(
valid_from: f.valid_from ?? ctx.validFrom,
context: ctx.sourceSlug ?? input.pageSlug ?? null,
};
- const legacyResult = await ctx.engine.insertFact(newFact, { source_id: ctx.sourceId }); // gbrain-allow-direct-insert: stub-guard / unresolvable-target fallback for unprefixed or fallback-resolved entity slugs (no fenceable page or usable tree)
+ const legacyResult = await maintenanceTransaction(ctx.engine, tx => tx.insertFact(newFact, { source_id: ctx.sourceId })); // gbrain-allow-direct-insert: stub-guard / unresolvable-target fallback for unprefixed or fallback-resolved entity slugs (no fenceable page or usable tree)
fact_ids.push(legacyResult.id);
if (legacyResult.status === 'inserted') inserted += 1;
else if ((legacyResult.status as FactInsertStatus) === 'duplicate') duplicate += 1;
@@ -913,7 +914,7 @@ async function runPipelineBodyInner(
valid_from: f.valid_from ?? ctx.validFrom,
context: ctx.sourceSlug ?? input.pageSlug ?? null,
};
- const legacyResult = await ctx.engine.insertFact(newFact, { source_id: ctx.sourceId }); // gbrain-allow-direct-insert: DB-only fallback when the fence lane declined the write (write_through opt-out race / localPath echo)
+ const legacyResult = await maintenanceTransaction(ctx.engine, tx => tx.insertFact(newFact, { source_id: ctx.sourceId })); // gbrain-allow-direct-insert: DB-only fallback when the fence lane declined the write (write_through opt-out race / localPath echo)
fact_ids.push(legacyResult.id);
if (legacyResult.status === 'inserted') inserted += 1;
else if ((legacyResult.status as FactInsertStatus) === 'duplicate') duplicate += 1;
diff --git a/src/core/facts/fence-write.ts b/src/core/facts/fence-write.ts
index 921f421147..d8b20e87af 100644
--- a/src/core/facts/fence-write.ts
+++ b/src/core/facts/fence-write.ts
@@ -55,6 +55,7 @@ import { extractFactsFromFenceText } from './extract-from-fence.ts';
import { logStubGuardEvent } from './stub-guard-audit.ts';
import { isFactWithdrawn } from './withdrawal.ts';
import { managedPersistenceEnabled } from '../persistence/ownership.ts';
+import { maintenanceTransaction } from '../persistence/attribution.ts';
/** Resolved source binding for the entity page. */
export interface FenceTarget {
@@ -519,9 +520,9 @@ export async function writeFactsToFence(
const reparsed = parseMarkdown(tmpBody, `${target.slug}.md`);
const existing = await engine.getPage(target.slug, { sourceId: target.sourceId });
if (existing) {
- await engine.refreshPageBody(target.slug, target.sourceId,
+ await maintenanceTransaction(engine, tx => tx.refreshPageBody(target.slug, target.sourceId,
sanitizeText(reparsed.compiled_truth), sanitizeText(reparsed.timeline),
- existing.content_hash || contentHash(existing));
+ existing.content_hash || contentHash(existing)));
}
} catch (err) {
// The file is committed; the page cache stays stale until the next
@@ -550,7 +551,7 @@ export async function writeFactsToFence(
source_session: facts[i].sessionId,
}));
- const result = await engine.insertFacts(enriched, { source_id: target.sourceId }); // gbrain-allow-direct-insert: writeFactsToFence is the markdown-first reconcile path; runs only after the atomic fence write commits
+ const result = await maintenanceTransaction(engine, tx => tx.insertFacts(enriched, { source_id: target.sourceId })); // gbrain-allow-direct-insert: writeFactsToFence is the markdown-first reconcile path; runs only after the atomic fence write commits
// v0.46 (#3014) — an unresolvable `superseded by #N` reference (self
// / dangling / struck target) leaves superseded_by NULL; log it rather
// than swallow it. The row still lands (expired_at set for struck
diff --git a/src/core/facts/forget.ts b/src/core/facts/forget.ts
index b4673b265d..7f1d56a665 100644
--- a/src/core/facts/forget.ts
+++ b/src/core/facts/forget.ts
@@ -21,6 +21,7 @@ import { parseMarkdown } from '../markdown.ts';
import { sanitizeText } from '../batch-rows.ts';
import { contentHash } from '../utils.ts';
import { recordFactWithdrawal } from './withdrawal.ts';
+import { maintenanceTransaction } from '../persistence/attribution.ts';
import { withdrawnFact } from './withdrawal-overlay.ts';
export interface ForgetFactResult {
@@ -161,10 +162,10 @@ export async function forgetFactInFence(
// withdrawn claim. Intent commits independently of filesystem availability.
// A supersession only expires the row.
if (supersession) {
- await engine.executeRaw(`UPDATE facts SET valid_until = LEAST(COALESCE(valid_until, now()), now()), expired_at = now()
- WHERE id = $1 AND expired_at IS NULL`, [factId]);
+ await maintenanceTransaction(engine, tx => tx.executeRaw(`UPDATE facts SET valid_until = LEAST(COALESCE(valid_until, now()), now()), expired_at = now()
+ WHERE id = $1 AND expired_at IS NULL`, [factId]));
} else {
- await recordFactWithdrawal(engine, factId, row.source_id, opts.worldOnly === true);
+ await maintenanceTransaction(engine, tx => recordFactWithdrawal(tx, factId, row.source_id, opts.worldOnly === true));
}
if (row.expired_at !== null) {
@@ -185,8 +186,8 @@ export async function forgetFactInFence(
// content_chunks with the live claim for good. A row-shaped hash over the
// struck body can never equal the unchanged file's, so the next sync
// re-imports + re-chunks through the withdrawal overlay.
- await engine.refreshPageBody(slug, row.source_id, struck, page.timeline ?? '',
- contentHash({ ...page, compiled_truth: struck }));
+ await maintenanceTransaction(engine, tx => tx.refreshPageBody(slug, row.source_id, struck, page.timeline ?? '',
+ contentHash({ ...page, compiled_truth: struck })));
};
// DB-only path: the withdrawal remains authoritative during reimport.
@@ -266,11 +267,11 @@ export async function forgetFactInFence(
// This keeps DB query patterns (active facts WHERE expired_at IS NULL)
// accurate the moment the forget commits, without waiting for the
// next extract_facts cycle phase to reconcile.
- await engine.executeRaw(
+ await maintenanceTransaction(engine, tx => tx.executeRaw(
`UPDATE facts SET valid_until = $1, expired_at = now()
WHERE id = $2 AND expired_at IS NULL`,
[today, factId],
- );
+ ));
// #4696: mirror the rewritten file into the DB body, or the reconcile
// (which reads pages.compiled_truth) resurrects the claim before the
@@ -287,9 +288,9 @@ export async function forgetFactInFence(
const reparsed = parseMarkdown(tmpBody, `${slug}.md`);
const page = await engine.getPage(slug, { sourceId: row.source_id });
if (page) {
- await engine.refreshPageBody(slug, row.source_id,
+ await maintenanceTransaction(engine, tx => tx.refreshPageBody(slug, row.source_id,
sanitizeText(reparsed.compiled_truth), sanitizeText(reparsed.timeline),
- page.content_hash || contentHash(page));
+ page.content_hash || contentHash(page)));
}
} catch { /* degrades to the pre-#4696 window (stale until the next sync) */ }
diff --git a/src/core/facts/proposal-supersede.ts b/src/core/facts/proposal-supersede.ts
index ea63f8a194..fc73b4c4d9 100644
--- a/src/core/facts/proposal-supersede.ts
+++ b/src/core/facts/proposal-supersede.ts
@@ -30,6 +30,7 @@ import { opError } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
import { getProposal, transitionProposal, type ProposalRow } from '../ai/decide/proposals-store.ts';
import { strikeFenceRow, supersededFact } from './forget.ts';
+import { maintenanceTransaction } from '../persistence/attribution.ts';
import type { PreparedMutation } from '../persistence/coordinator.ts';
import type { WriteRequest } from '../persistence/model.ts';
@@ -221,7 +222,7 @@ async function acceptUnmanaged(engine: BrainEngine, proposal: ProposalRow): Prom
const before: SupersedeState = { old: factFields(oldF!), new: factFields(newF!), fence: plan ? fence(plan.before, snapshot?.revision ?? null) : null };
let published = false;
try {
- await engine.transaction(async (tx) => {
+ await maintenanceTransaction(engine, async (tx) => {
const revision = plan ? await mirrorBody(tx, slug!, fresh.source_id, plan.body, fileBody !== null) : null;
await expireOld(tx, fresh);
await finishAccept(tx, fresh, before, plan ? fence(plan.after, revision) : null);
@@ -258,7 +259,7 @@ async function undoUnmanaged(engine: BrainEngine, proposal: ProposalRow): Promis
}
let published = false;
try {
- await engine.transaction(async (tx) => {
+ await maintenanceTransaction(engine, async (tx) => {
if (plan) await mirrorBody(tx, before.fence!.slug, fresh.source_id, plan.body, fileBody !== null);
await applyUndoDb(tx, fresh, before, after);
if (plan && fileBody !== null) { publishFile(filePath!, plan.body); published = true; }
diff --git a/src/core/facts/write-single.ts b/src/core/facts/write-single.ts
index e48e72cdd1..982a4d79d4 100644
--- a/src/core/facts/write-single.ts
+++ b/src/core/facts/write-single.ts
@@ -24,6 +24,7 @@
*/
import type { BrainEngine, FactInsertStatus, NewFact } from '../engine.ts';
+import { maintenanceTransaction } from '../persistence/attribution.ts';
const DEDUP_THRESHOLD = 0.95;
const DEDUP_CANDIDATE_LIMIT = 5;
@@ -247,10 +248,10 @@ export async function writeSingleFact(
// tree unusable) → DB-only path below.
}
- const inserted = await engine.insertFact(newFact, { // gbrain-allow-direct-insert: writeSingleFact legacy path for unparented / thin-client / stub-guarded facts (mirrors the pipeline's fallback buckets)
+ const inserted = await maintenanceTransaction(engine, tx => tx.insertFact(newFact, { // gbrain-allow-direct-insert: writeSingleFact legacy path for unparented / thin-client / stub-guarded facts (mirrors the pipeline's fallback buckets)
source_id: sourceId,
...(supersedeId !== null ? { supersedeId } : {}),
- });
+ }));
return {
id: inserted.id,
@@ -285,7 +286,7 @@ async function expireSuperseded(engine: BrainEngine, oldId: number, newId: numbe
report('fence strike', err);
}
try {
- await engine.executeRaw(`UPDATE facts SET superseded_by = $1 WHERE id = $2`, [newId, oldId]);
+ await maintenanceTransaction(engine, tx => tx.executeRaw(`UPDATE facts SET superseded_by = $1 WHERE id = $2`, [newId, oldId]));
} catch (err) {
report('superseded_by link', err);
}
diff --git a/src/core/takes-write.ts b/src/core/takes-write.ts
index 4141922c91..6d57d7baa7 100644
--- a/src/core/takes-write.ts
+++ b/src/core/takes-write.ts
@@ -57,6 +57,7 @@ import { sanitizeRecordedSourcePath, recordedPathFromFileUri, scannerSlugRootMod
import { isWriteTargetContained, msysToNativePath } from './path-confine.ts';
import { atomicWriteFileSync } from './atomic-write.ts';
import { commitWriteThroughFile, isDurabilityHardened } from './brain-repo-durability.ts';
+import { maintenanceTransaction } from './persistence/attribution.ts';
export type TakesWriteErrorCode =
| 'page_not_found' // slug has no pages row (scoped)
@@ -566,12 +567,12 @@ export async function addTakeToPage(
writePageBody(path, nextBody, writeRoot, target.slug);
let mirrorWarning: string | undefined;
try {
- await target.engine.addTakesBatch([{
+ await maintenanceTransaction(target.engine, tx => tx.addTakesBatch([{
page_id: pageId, row_num: rowNum, claim: input.claim, kind: input.kind,
holder: input.holder, weight: input.weight ?? 0.5,
since_date: input.sinceDate, source: input.source,
active: true, superseded_by: null,
- }]);
+ }]));
} catch (err) {
// P1-4/F4: md is canonical + already written — a failed DB mirror is
// healed by the next reconcile, so surface a warning instead of throwing
@@ -631,7 +632,7 @@ export async function appendTakesToPageMdFirst(
const after = parseTakesFence(nextBody).takes.filter(t => appended.has(t.rowNum));
let mirrorWarning: string | undefined;
try {
- await target.engine.addTakesBatch(after.map(t => toBatchInput(pageId, t)));
+ await maintenanceTransaction(target.engine, tx => tx.addTakesBatch(after.map(t => toBatchInput(pageId, t))));
} catch (err) {
mirrorWarning = mirrorErrorMessage(err); // P1-4/F4: md written; DB mirror deferred to reconcile.
}
@@ -685,7 +686,7 @@ export async function updateTakeOnPage(
// base columns only, resolution columns preserved by the DO UPDATE list.
let mirrorWarning: string | undefined;
try {
- await target.engine.addTakesBatch([toBatchInput(pageId, updated)]);
+ await maintenanceTransaction(target.engine, tx => tx.addTakesBatch([toBatchInput(pageId, updated)]));
} catch (err) {
mirrorWarning = mirrorErrorMessage(err); // P1-4/F4: md written; DB mirror deferred to reconcile.
}
@@ -753,7 +754,7 @@ export async function supersedeTakeOnPage(
if (newAfter) mirrorRows.push(toBatchInput(pageId, newAfter, null));
let mirrorWarning: string | undefined;
try {
- await target.engine.addTakesBatch(mirrorRows);
+ await maintenanceTransaction(target.engine, tx => tx.addTakesBatch(mirrorRows));
} catch (err) {
mirrorWarning = mirrorErrorMessage(err); // P1-4/F4: md written; DB mirror deferred to reconcile.
}
@@ -832,12 +833,14 @@ export async function resolveTakeOnPage(
// md write and duplicate the row).
let mirrorWarning: string | undefined;
try {
- await target.engine.resolveTake(pageId, rowNum, resolveArgs);
+ await maintenanceTransaction(target.engine, tx => tx.resolveTake(pageId, rowNum, resolveArgs));
} catch (err) {
if (err instanceof Error && err.message.includes('TAKE_ROW_NOT_FOUND')) {
try {
- await target.engine.addTakesBatch([toBatchInput(pageId, targetRow)]);
- await target.engine.resolveTake(pageId, rowNum, resolveArgs);
+ await maintenanceTransaction(target.engine, async tx => {
+ await tx.addTakesBatch([toBatchInput(pageId, targetRow)]);
+ await tx.resolveTake(pageId, rowNum, resolveArgs);
+ });
} catch (healErr) {
mirrorWarning = mirrorErrorMessage(healErr);
}
diff --git a/test/e2e/write-attribution-postgres.test.ts b/test/e2e/write-attribution-postgres.test.ts
index 6f2976c122..2cdb1308c9 100644
--- a/test/e2e/write-attribution-postgres.test.ts
+++ b/test/e2e/write-attribution-postgres.test.ts
@@ -13,6 +13,7 @@ if (hasDatabase()) {
await import('../write-attribution-sync.test.ts');
await import('../write-attribution-timeline.test.ts');
await import('../write-attribution-timeline-10k.slow.test.ts');
+ await import('../write-attribution-facts-takes.test.ts');
} else {
test.skip('write attribution on Postgres requires DATABASE_URL', () => {});
}
diff --git a/test/fence-write.test.ts b/test/fence-write.test.ts
index 24d46a2f82..2deefb146e 100644
--- a/test/fence-write.test.ts
+++ b/test/fence-write.test.ts
@@ -619,10 +619,11 @@ describe('writeFactsToFence — row_num survives a fence-less rewrite', () => {
// fence writes impossible (pre-v51 brains, transient DB errors).
const brokenEngine = Object.create(engine) as typeof engine;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
- (brokenEngine as any).executeRaw = async (sqlText: string, params: unknown[]) => {
+ // A transaction engine derived from brokenEngine keeps its own connection: delegate with `this`.
+ (brokenEngine as any).executeRaw = async function (this: typeof engine, sqlText: string, params: unknown[]) {
if (sqlText.includes('MAX(row_num)')) throw new Error('simulated lookup failure');
// eslint-disable-next-line @typescript-eslint/no-explicit-any
- return (engine as any).executeRaw(sqlText, params);
+ return (engine as any).executeRaw.call(this, sqlText, params);
};
const result = await writeFactsToFence(
@@ -810,10 +811,11 @@ describe('writeFactsToFence — durability latch recovery', () => {
let gated = false;
const gatedEngine = Object.create(engine) as typeof engine;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
- (gatedEngine as any).insertFacts = async (rows: unknown, opts: unknown) => {
+ // The insert runs on a transaction engine derived from gatedEngine: delegate with `this`.
+ (gatedEngine as any).insertFacts = async function (this: typeof engine, rows: unknown, opts: unknown) {
if (!gated) { gated = true; await gate; }
// eslint-disable-next-line @typescript-eslint/no-explicit-any
- return (engine as any).insertFacts(rows, opts);
+ return (engine as any).insertFacts.call(this, rows, opts);
};
const a = writeFactsToFence(
diff --git a/test/write-attribution-facts-takes.test.ts b/test/write-attribution-facts-takes.test.ts
new file mode 100644
index 0000000000..10a33ebeb3
--- /dev/null
+++ b/test/write-attribution-facts-takes.test.ts
@@ -0,0 +1,210 @@
+/**
+ * Foundations 2 (Lane C) attribution for the legacy facts and takes helpers on
+ * an unmanaged brain: `writeSingleFact`'s DB-only and fence paths (with their
+ * supersession bookkeeping), the facts backstop's DB-only fallbacks, the
+ * unmanaged `decide` proposal accept and undo, and the takes file helpers'
+ * DB mirror (add, append, update, supersede, resolve and its self-heal) write
+ * inside maintenanceTransaction. Rows they create name the local maintenance
+ * principal; rows they change keep their creator and move their last writer;
+ * the page revisions their body mirrors advance name the maintenance principal.
+ *
+ * Protects the legacy facts and takes writer family in
+ * docs/architecture/system-of-record.md. Fails if write-single.ts,
+ * fence-write.ts, forget.ts, backstop.ts, proposal-supersede.ts or
+ * takes-write.ts writes outside maintenanceTransaction. Runs on PGLite, and on
+ * Postgres (direct and transaction-mode PgBouncer) through
+ * test/e2e/write-attribution-postgres.test.ts.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { writeSingleFact } from '../src/core/facts/write-single.ts';
+import { runFactsBackstop } from '../src/core/facts/backstop.ts';
+import { applyProposalAction } from '../src/core/facts/proposal-supersede.ts';
+import { insertProposal } from '../src/core/ai/decide/proposals-store.ts';
+import { addTakeToPage, appendTakesToPageMdFirst, resolveTakeOnPage, supersedeTakeOnPage, updateTakeOnPage } from '../src/core/takes-write.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { writePageThrough, _resetWriteThroughCacheForTest } from '../src/core/write-through.ts';
+import { renderFactsTable } from '../src/core/facts-fence.ts';
+import { renderTakesFence } from '../src/core/takes-fence.ts';
+import { __resetFactsQueueForTests } from '../src/core/facts/queue.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { __setChatTransportForTests, __setEmbedTransportForTests, configureGateway, resetGateway, type ChatResult } from '../src/core/ai/gateway.ts';
+import { LEGACY_EMBEDDING_CONFIG } from './helpers/legacy-embedding-config.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { CREATOR_ACTOR, asCreator, revisionActor, rowActors, unmanagedBrain, type Actor, type UnmanagedBrain } from './helpers/unmanaged-attribution.ts';
+
+const engines: BrainEngine[] = [];
+const scratch = mkdtempSync(join(tmpdir(), 'gbrain-write-attribution-facts-takes-'));
+let closePostgres: (() => Promise<void>) | undefined;
+const VECTOR = [1, ...new Array(1535).fill(0)];
+const FIXED_EMBEDDING = (async (opts: { values: string[] }) => ({ embeddings: opts.values.map(() => VECTOR) })) as never;
+
+beforeAll(async () => {
+ configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: {} });
+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);
+ if (process.env.DATABASE_URL) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL);
+ engines.push(pg.engine); closePostgres = pg.close;
+ }
+}, 120_000);
+afterAll(async () => {
+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }
+ await closePostgres?.();
+ rmSync(scratch, { recursive: true, force: true });
+});
+
+async function withFixedEmbeddings(fn: () => Promise<void>) {
+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: 1536, env: { OPENAI_API_KEY: 'sk-test-attribution' } });
+ __setEmbedTransportForTests(FIXED_EMBEDDING);
+ try { await fn(); }
+ finally { __setEmbedTransportForTests(null); configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: {} }); }
+}
+const actors = (rows: Array<{ id: number; created: Actor; last: Actor }>) => Object.fromEntries(rows.map(row => [row.id, { created: row.created, last: row.last }]));
+const both = (actor: Actor) => ({ created: actor, last: actor });
+const VECTOR_TEXT = `[${VECTOR.join(',')}]`;
+async function creatorFact(brain: UnmanagedBrain, fact: string, extra: { entity?: string; rowNum?: number; page?: string } = {}): Promise<number> {
+ const [row] = await asCreator(brain.engine, tx => tx.executeRaw<{ id: number }>(`INSERT INTO facts
+ (source_id, entity_slug, fact, kind, visibility, source, row_num, source_markdown_slug, embedding, embedding_model, embedded_text_hash)
+ VALUES ($1, $2, $3, 'fact', 'private', 'test', $4, $5, $6::vector, 'openai:text-embedding-3-small', md5($3)) RETURNING id::int AS id`,
+ [brain.sourceId, extra.entity ?? null, fact, extra.rowNum ?? null, extra.page ?? null, VECTOR_TEXT]));
+ return row.id;
+}
+async function sourceRoot(brain: UnmanagedBrain): Promise<string> {
+ const root = join(scratch, brain.sourceId);
+ mkdirSync(join(root, 'people'), { recursive: true });
+ await brain.engine.executeRaw('UPDATE sources SET local_path=$2 WHERE id=$1', [brain.sourceId, root]);
+ _resetWriteThroughCacheForTest();
+ return root;
+}
+
+describe('legacy facts helpers on an unmanaged brain', () => {
+ test('writeSingleFact DB-only supersession: the new fact is maintenance-created and the old fact keeps its creator', () => withFixedEmbeddings(async () => {
+ for (const engine of engines) {
+ const brain = await unmanagedBrain(engine);
+ const old = await creatorFact(brain, 'Prefers morning meetings', { entity: 'people/alice-example' });
+
+ const written = await writeSingleFact(engine, brain.sourceId, { fact: 'Prefers afternoon meetings', provenance: 'test', entity: 'people/alice-example' });
+
+ expect(written.status).toBe('superseded');
+ expect(actors(await rowActors(engine, 'facts', 'source_id=$1', [brain.sourceId])))
+ .toEqual({ [old]: { created: CREATOR_ACTOR, last: brain.maintenance }, [written.id]: both(brain.maintenance) });
+ }
+ }), 120_000);
+
+ test('writeSingleFact fence path: the fenced fact, its supersession strike and the page body mirror name the maintenance principal', () => withFixedEmbeddings(async () => {
+ for (const engine of engines) {
+ const brain = await unmanagedBrain(engine);
+ await sourceRoot(brain);
+ const slug = 'people/bob-example';
+ await importFromContent(engine, slug, '---\ntype: person\ntitle: Bob\n---\nA person.\n', { sourceId: brain.sourceId, sourcePath: `${slug}.md`, noEmbed: true });
+ await writePageThrough(engine, slug, { sourceId: brain.sourceId });
+
+ const first = await writeSingleFact(engine, brain.sourceId, { fact: 'Works from the harbor office', provenance: 'test', entity: slug });
+ await engine.executeRaw('UPDATE pages SET revision_principal_kind=NULL, revision_principal_id=NULL WHERE source_id=$1 AND slug=$2', [brain.sourceId, slug]);
+ const second = await writeSingleFact(engine, brain.sourceId, { fact: 'Works from the river office', provenance: 'test', entity: slug });
+
+ expect([first.status, second.status]).toEqual(['inserted', 'superseded']);
+ const [stored] = await engine.executeRaw<{ superseded_by: number | null; expired: boolean }>(
+ 'SELECT superseded_by::int AS superseded_by, expired_at IS NOT NULL AS expired FROM facts WHERE id=$1', [first.id]);
+ expect(stored).toEqual({ superseded_by: second.id, expired: true });
+ expect(actors(await rowActors(engine, 'facts', 'source_id=$1', [brain.sourceId])))
+ .toEqual({ [first.id]: both(brain.maintenance), [second.id]: both(brain.maintenance) });
+ expect(await revisionActor(engine, brain.sourceId, slug)).toEqual(brain.maintenance);
+ }
+ }), 120_000);
+
+ test('the facts backstop stamps its DB-only fallbacks (unparented and stub-guarded facts)', async () => {
+ for (const engine of engines) {
+ const brain = await unmanagedBrain(engine);
+ await sourceRoot(brain);
+ resetGateway();
+ __setChatTransportForTests(async (): Promise<ChatResult> => ({
+ text: JSON.stringify({ facts: [
+ { fact: 'The launch moved to spring', kind: 'fact', entity: null, confidence: 1.0, notability: 'medium' },
+ { fact: 'Leads the example project', kind: 'fact', entity: 'people/zed-example', confidence: 1.0, notability: 'medium' },
+ ] }),
+ blocks: [], stopReason: 'end', model: 'test:stub', providerId: 'test',
+ usage: { input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ }));
+ try {
+ const result = await runFactsBackstop(
+ { slug: 'meetings/example-sync', type: 'meeting', compiled_truth: 'An example planning meeting about the launch and the project. '.repeat(3), frontmatter: {} },
+ { engine, sourceId: brain.sourceId, sessionId: null, source: 'mcp:put_page', mode: 'inline' });
+ if (result.mode !== 'inline') throw new Error('expected an inline backstop run');
+ expect(result.fact_ids).toHaveLength(2);
+ expect(actors(await rowActors(engine, 'facts', 'id=ANY($1::bigint[])', [result.fact_ids])))
+ .toEqual(Object.fromEntries(result.fact_ids.map(id => [id, both(brain.maintenance)])));
+ } finally {
+ __setChatTransportForTests(null);
+ __resetFactsQueueForTests();
+ configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: {} });
+ }
+ }
+ }, 120_000);
+
+ test('an unmanaged decide proposal accept and undo keep the old fact creator and move its last writer and page revision', async () => {
+ for (const engine of engines) {
+ const brain = await unmanagedBrain(engine);
+ const slug = 'people/carol-example';
+ const fence = renderFactsTable([
+ { rowNum: 1, claim: 'Lives in the north district', kind: 'fact', confidence: 1, visibility: 'private', notability: 'medium', active: true },
+ { rowNum: 2, claim: 'Lives in the south district', kind: 'fact', confidence: 1, visibility: 'private', notability: 'medium', active: true },
+ ] as never);
+ await asCreator(engine, tx => tx.putPage(slug, { type: 'person', title: 'Carol', compiled_truth: `Profile\n\n${fence}` }, { sourceId: brain.sourceId }));
+ const old = await creatorFact(brain, 'Lives in the north district', { entity: slug, rowNum: 1, page: slug });
+ const replacement = await creatorFact(brain, 'Lives in the south district', { entity: slug, rowNum: 2, page: slug });
+ const id = (await insertProposal(engine, { source_id: brain.sourceId, sweep_id: `sweep-${brain.sourceId}`, pair_index: 0,
+ new_fact_id: replacement, old_fact_id: old, direction: 'new_supersedes_old', p_supersede: 0.9, threshold: 0.8, proposal_floor: 0.5, model_resolved: null } as never))!;
+
+ expect(await applyProposalAction(engine, id, 'accept')).toMatchObject({ status: 'accepted' });
+ expect(actors(await rowActors(engine, 'facts', 'id=$1', [old]))).toEqual({ [old]: { created: CREATOR_ACTOR, last: brain.maintenance } });
+ expect(await revisionActor(engine, brain.sourceId, slug)).toEqual(brain.maintenance);
+
+ await engine.executeRaw('UPDATE pages SET revision_principal_kind=NULL, revision_principal_id=NULL WHERE source_id=$1 AND slug=$2', [brain.sourceId, slug]);
+ expect(await applyProposalAction(engine, id, 'undo')).toMatchObject({ status: 'undone' });
+ expect(actors(await rowActors(engine, 'facts', 'source_id=$1', [brain.sourceId])))
+ .toEqual({ [old]: { created: CREATOR_ACTOR, last: brain.maintenance }, [replacement]: both(CREATOR_ACTOR) });
+ expect(await revisionActor(engine, brain.sourceId, slug)).toEqual(brain.maintenance);
+ }
+ }, 120_000);
+});
+
+describe('legacy takes file helpers on an unmanaged brain', () => {
+ test('add, append, update, supersede and resolve mirror their rows under the maintenance principal', async () => {
+ for (const engine of engines) {
+ const brain = await unmanagedBrain(engine);
+ const root = await sourceRoot(brain);
+ const slug = 'people/dana-example';
+ const takes = renderTakesFence([{ rowNum: 1, claim: 'Ships carefully', kind: 'take', holder: 'world', weight: 0.6, active: true }] as never);
+ const page = await asCreator(engine, tx => tx.putPage(slug, { type: 'person', title: 'Dana', compiled_truth: `Profile\n\n${takes}` }, { sourceId: brain.sourceId }));
+ writeFileSync(join(root, `${slug}.md`), `---\ntype: person\ntitle: Dana\n---\nProfile\n\n${takes}\n`);
+ await engine.executeRaw('DELETE FROM takes WHERE page_id=$1', [page.id]);
+ await asCreator(engine, tx => tx.addTakesBatch([{ page_id: page.id, row_num: 1, claim: 'Ships carefully', kind: 'take', holder: 'world', weight: 0.6, active: true, superseded_by: null }]));
+ const target = { engine, slug, sourceId: brain.sourceId, brainDir: root };
+ const byRow = async () => Object.fromEntries((await engine.executeRaw<{ row_num: number; created: Actor; last: Actor }>(`SELECT row_num::int AS row_num,
+ jsonb_build_object('request',write_request_id::text,'kind',write_principal_kind,'id',write_principal_id) AS created,
+ jsonb_build_object('request',last_write_request_id::text,'kind',last_write_principal_kind,'id',last_write_principal_id) AS last
+ FROM takes WHERE page_id=$1 ORDER BY row_num`, [page.id])).map(row => [row.row_num, { created: row.created, last: row.last }]));
+
+ expect((await updateTakeOnPage(target, 1, { weight: 0.7 })).mirror.mirror_warning).toBeUndefined();
+ expect(await byRow()).toEqual({ 1: { created: CREATOR_ACTOR, last: brain.maintenance } });
+
+ const superseded = await supersedeTakeOnPage(target, 1, { claim: 'Ships carefully and fast' });
+ const added = await addTakeToPage(target, { claim: 'Prefers small teams', kind: 'take', holder: 'world' });
+ const appended = await appendTakesToPageMdFirst(target, [{ claim: 'Writes long memos', kind: 'take', holder: 'world' }]);
+ const resolved = await resolveTakeOnPage(target, superseded.newRow, { quality: 'correct', resolvedBy: 'example-reviewer' });
+ for (const mirror of [superseded.mirror, added.mirror, appended.mirror, resolved.mirror]) expect(mirror.mirror_warning).toBeUndefined();
+ expect(await byRow()).toEqual({ 1: { created: CREATOR_ACTOR, last: brain.maintenance }, [superseded.newRow]: both(brain.maintenance),
+ [added.rowNum]: both(brain.maintenance), [appended.rowNums[0]]: both(brain.maintenance) });
+
+ await engine.executeRaw('DELETE FROM takes WHERE page_id=$1 AND row_num=$2', [page.id, added.rowNum]);
+ const healed = await resolveTakeOnPage(target, added.rowNum, { quality: 'incorrect', resolvedBy: 'example-reviewer' });
+ expect(healed.mirror.mirror_warning).toBeUndefined();
+ expect((await byRow())[added.rowNum]).toEqual(both(brain.maintenance));
+ }
+ }, 120_000);
+});