Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

belief ledger lane B: fix review #5, #18, #25, #31, #32, #34, #35, #40, #43 with regression tests

garrytan947f24fa7959
diff --git a/src/commands/sync/renames.ts b/src/commands/sync/renames.ts
index 45eca41355..c1b26d5721 100644
--- a/src/commands/sync/renames.ts
+++ b/src/commands/sync/renames.ts
@@ -361,10 +361,11 @@ export async function carryRenameIdentity(engine: BrainEngine, sourceId: string,
if (!from || !to || from.id === to.id) return;
const publication = await maintenanceTransaction(engine, async tx => {
await tx.lockPageKeys([{ sourceId, slug: staleSlug }, { sourceId, slug: newSlug }]);
- await recordRenameAlias(tx, sourceId, staleSlug, newSlug);
- await moveSlugBindings(tx, sourceId, staleSlug, newSlug);
- await movePageIdReferences(tx, Number(from.id), Number(to.id));
- return recordFallbackRename(tx, { sourceId, staleSlug, newSlug, fromPageId: Number(from.id), toPageId: Number(to.id) });
+ return recordFallbackRename(tx, { sourceId, staleSlug, newSlug, fromPageId: Number(from.id), toPageId: Number(to.id) }, async () => {
+ await recordRenameAlias(tx, sourceId, staleSlug, newSlug);
+ await moveSlugBindings(tx, sourceId, staleSlug, newSlug);
+ await movePageIdReferences(tx, Number(from.id), Number(to.id));
+ });
});
if (publication) await markBeliefCommits(engine, [publication]).catch(() => undefined);
}
diff --git a/src/core/belief/backfill.ts b/src/core/belief/backfill.ts
index 5af5c99d32..db82581d2a 100644
--- a/src/core/belief/backfill.ts
+++ b/src/core/belief/backfill.ts
@@ -17,8 +17,11 @@
* epoch moved (the page is prepared again from current, redacted versions),
* and rechecks tombstones through `appendBeliefEvents`. Events of a key a
* purge hid through derivation (`derived.hidden`) are appended hidden.
- * Publication ids are derived from the page lifetime and version, so a rerun
- * appends nothing twice.
+ * Publication ids are derived from the page lifetime and the version row; a
+ * lifetime that already has its summary is skipped, so a rerun appends
+ * nothing even after versions were pruned. The lifetime is resolved under the
+ * page key, and the append refuses when the page was renamed or replaced
+ * since preparation.
*/
import type { BrainEngine } from '../engine.ts';
import { parseFactsFence } from '../facts-fence.ts';
@@ -37,7 +40,7 @@ export interface BackfillReport { source_id: string; since: string | null; pages
interface Body { revision: string | null; source_time: string; text: string | null }
interface Keyed { kind: 'fact' | 'take'; key: string; value: Record<string, unknown>; vhash: string; visibility: string; claimFp: string; validFrom: string | null; validUntil: string | null }
-interface Prepared { epoch: number; incarnation: string; lifetime: string; pageId: number; versions: Body[]; drafts: BeliefEventDraft[][]; summary: BeliefEventDraft; complete: boolean; reasons: string[] }
+interface Prepared { epoch: number; incarnation: string; lifetime: string; pageId: number; versions: Body[]; drafts: BeliefEventDraft[][]; publications: string[]; summary: BeliefEventDraft; complete: boolean; reasons: string[] }
const MAX_EPOCH_RETRIES = 3;
const toUuid = (hex: string) => `${hex.slice(0, 8)}-${hex.slice(8, 12)}-4${hex.slice(13, 16)}-a${hex.slice(17, 20)}-${hex.slice(20, 32)}`;
@@ -92,7 +95,10 @@ async function preparePage(engine: BrainEngine, sourceId: string, slug: string,
p.body_storage = 'segmented' AS large, p.compiled_truth, p.timeline, (${privatePagesFilterFragment('p')}) AS visible
FROM pages p WHERE p.source_id = $1 AND p.slug = $2`, [sourceId, slug]);
if (!page) return null;
- const lifetime = (await resolveLifetimes(engine, [{ sourceId, incarnation: source.incarnation, slug, pageId: Number(page.id) }])).get(Number(page.id))!;
+ const lifetime = await engine.transaction(async tx => {
+ await tx.lockPageKeys([{ sourceId, slug }]);
+ return (await resolveLifetimes(tx, [{ sourceId, incarnation: source.incarnation, slug, pageId: Number(page.id) }])).get(Number(page.id))!;
+ });
const versions = await engine.executeRaw<{ id: number; snapshot_at: string; revision: string | null; compiled_truth: string | null; timeline: string | null; segmented: boolean }>(`SELECT v.id,
v.snapshot_at, v.knowledge_revision::text AS revision, v.compiled_truth, v.timeline, v.body_storage = 'segmented' AS segmented
FROM page_versions v WHERE v.page_id = $1 ORDER BY v.snapshot_at, v.id`, [page.id]);
@@ -109,6 +115,7 @@ async function preparePage(engine: BrainEngine, sourceId: string, slug: string,
const hidden = new Set((await engine.executeRaw<{ subject_key: string }>(`SELECT DISTINCT subject_key FROM belief_events WHERE source_id = $1 AND event_type = 'derived.hidden'`,
[sourceId])).map(r => r.subject_key));
const drafts: BeliefEventDraft[][] = [];
+ const publications: string[] = [];
let prior: Keyed[] = [];
let priorRevision: string | null = null;
const stateHash = sha256Hex(`backfill:${lifetime}`);
@@ -133,6 +140,7 @@ async function preparePage(engine: BrainEngine, sourceId: string, slug: string,
else if (was.vhash !== s.vhash) draft(s, `${s.kind}.revised`, s.value, was.vhash);
}
drafts.push(out);
+ publications.push(i < bodies.length ? `version:${before[i]!.id}` : closing ? `version:${closing.id}` : 'current');
prior = subjects;
priorRevision = body.revision;
}
@@ -140,7 +148,7 @@ async function preparePage(engine: BrainEngine, sourceId: string, slug: string,
const summary: BeliefEventDraft = { ...base, subjectKind: 'page', subjectKey: pageKey(lifetime), eventType: 'backfill', visibility,
value: { backfill_complete: complete, versions: before.length, reasons: [...new Set(reasons)].sort(), coverage_start: since }, sourceTime: bodies[0]?.source_time ?? null,
cause: { op: 'backfill', purge_epoch: source.purgeEpoch } };
- return { epoch: source.purgeEpoch, incarnation: source.incarnation, lifetime, pageId: Number(page.id), versions: chain, drafts, summary, complete, reasons: [...new Set(reasons)].sort() };
+ return { epoch: source.purgeEpoch, incarnation: source.incarnation, lifetime, pageId: Number(page.id), versions: chain, drafts, publications, summary, complete, reasons: [...new Set(reasons)].sort() };
}
/** Appends one prepared page under its key; refuses (`belief_preparation_stale`) when a purge moved the source's epoch since preparation. */
@@ -154,9 +162,18 @@ async function appendPrepared(engine: BrainEngine, sourceId: string, slug: strin
throw opError('belief_preparation_stale', `A purge ran in source ${sourceId} after the backfill of ${slug} was prepared.`,
'The backfill prepares the page again from the current, redacted versions; rerun gbrain beliefs backfill if it gave up.');
}
+ const [open] = await tx.executeRaw<{ id: number; page_lifetime: string | null }>(`SELECT p.id, l.page_lifetime::text AS page_lifetime FROM pages p
+ LEFT JOIN belief_page_lifetimes l ON l.source_incarnation = $2::uuid AND l.slug = p.slug AND l.ended_at IS NULL WHERE p.source_id = $1 AND p.slug = $3`,
+ [sourceId, source.incarnation, slug]);
+ if (Number(open?.id) !== prepared.pageId || open?.page_lifetime !== prepared.lifetime) {
+ throw opError('belief_preparation_stale', `The page at ${slug} in source ${sourceId} was renamed or replaced after its backfill was prepared.`,
+ 'The backfill prepares the page again; rerun gbrain beliefs backfill if it gave up.');
+ }
+ const [done] = await tx.executeRaw<{ id: number }>(`SELECT id FROM belief_events WHERE page_lifetime = $1::uuid AND event_type = 'backfill' LIMIT 1`, [prepared.lifetime]);
+ if (done) return 0;
let n = 0;
for (const [i, group] of [...prepared.drafts, [prepared.summary]].entries()) {
- const publicationId = toUuid(sha256Hex(`backfill\u0000${prepared.lifetime}\u0000${i === prepared.drafts.length ? 'summary' : i}`));
+ const publicationId = toUuid(sha256Hex(`backfill\u0000${prepared.lifetime}\u0000${prepared.publications[i] ?? 'summary'}`));
const appended = await appendBeliefEvents(tx, group, { publicationId, origin: 'backfill', purgesPossible: source.purgesPossible });
if (appended) publications.push(publicationId);
n += appended;
diff --git a/src/core/belief/identity.ts b/src/core/belief/identity.ts
index 073c9c49c9..02a8207cc8 100644
--- a/src/core/belief/identity.ts
+++ b/src/core/belief/identity.ts
@@ -14,35 +14,64 @@ import type { BrainEngine } from '../engine.ts';
import { readManagedMode } from '../persistence/managed-mode.ts';
import { assertHeldPageKeys } from '../page-state/guards.ts';
import { appendBeliefEvents } from './append.ts';
-import { pageKey } from './keys.ts';
-import { coverageActive, currentStateHash, readLedgerSource } from './ledger.ts';
-import { endLifetime, mintLifetime, readOpenLifetimes, renameLifetime } from './lifetimes.ts';
+import { lifetimeRef, pageKey } from './keys.ts';
+import { coverageActive, currentStateHash, readLedgerSource, streamSubjectDrafts } from './ledger.ts';
+import { endLifetime, renameLifetime } from './lifetimes.ts';
+import { keyedSubjects, type Subject } from './subjects.ts';
+
+/** One stream's current subjects, keyed as the ledger keys them now, with its state hash. */
+async function keyedStream(tx: BrainEngine, sourceId: string, incarnation: string, slug: string) {
+ const { hash, state, lifetimes } = await currentStateHash(tx, sourceId, incarnation, slug);
+ const page = state.pages.find(p => p.slug === slug) ?? null;
+ const subjects = keyedSubjects({ incarnation, lifetimes, pagesBySlug: new Map(page ? [[slug, page]] : []) }, state,
+ id => state.pages.find(p => p.id === id)?.visible === false ? 'private' : 'world').filter(s => s.stream === slug);
+ return { hash, page, lifetimes, subjects, writerTier: state.writerTier };
+}
/**
- * Inside the fallback rename's transaction, after its row moves, with both
- * slugs' page keys held: the destination row takes the stale row's lifetime
- * (the destination's own lifetime, minted by its import, ends) and one
- * `page.renamed` is appended. Returns the publication id when it appended.
+ * The fallback rename's transaction, with both slugs' page keys held: `moves`
+ * carries the stale row's identity onto the destination row, then the
+ * destination takes the stale row's lifetime (the destination's own lifetime,
+ * minted by its import, ends). One `page.renamed` is appended, plus the
+ * subject events that make the surviving lifetime describe the destination:
+ * each destination row's belief is `*.transferred` from the ended lifetime,
+ * and a stale belief the destination does not hold is retracted. Returns the
+ * publication id when it appended.
*/
-export async function recordFallbackRename(tx: BrainEngine, input: { sourceId: string; staleSlug: string; newSlug: string; fromPageId: number; toPageId: number }): Promise<string | null> {
+export async function recordFallbackRename(tx: BrainEngine, input: { sourceId: string; staleSlug: string; newSlug: string; fromPageId: number; toPageId: number },
+ moves: () => Promise<void>): Promise<string | null> {
const source = await readLedgerSource(tx, input.sourceId);
- if (!source || !coverageActive(source.coverage)) return null;
+ if (!source || !coverageActive(source.coverage)) { await moves(); return null; }
assertHeldPageKeys(tx, [{ sourceId: input.sourceId, slug: input.staleSlug }, { sourceId: input.sourceId, slug: input.newSlug }]);
- const open = await readOpenLifetimes(tx, [{ incarnation: source.incarnation, slug: input.staleSlug }, { incarnation: source.incarnation, slug: input.newSlug }]);
- const stale = open.get(`${source.incarnation}\u0000${input.staleSlug}`);
- const lifetime = stale && (stale.page_id == null || stale.page_id === input.fromPageId) ? stale.page_lifetime
- : await mintLifetime(tx, { sourceId: input.sourceId, incarnation: source.incarnation, slug: input.staleSlug, pageId: input.fromPageId });
- const absorbed = open.get(`${source.incarnation}\u0000${input.newSlug}`)?.page_lifetime;
+ const stale = await keyedStream(tx, input.sourceId, source.incarnation, input.staleSlug);
+ const dest = await keyedStream(tx, input.sourceId, source.incarnation, input.newSlug);
+ const lifetime = stale.lifetimes.get(input.fromPageId)!;
+ const absorbed = dest.lifetimes.get(input.toPageId) ?? null;
+ await moves();
if (absorbed && absorbed !== lifetime) await endLifetime(tx, absorbed);
await renameLifetime(tx, lifetime, input.newSlug, input.toPageId);
- const [page] = await tx.executeRaw<{ trust_tier: string }>('SELECT trust_tier FROM pages WHERE id = $1', [input.toPageId]);
- const { hash, state } = await currentStateHash(tx, input.sourceId, source.incarnation, input.newSlug);
- const visible = state.pages.find(p => p.id === input.toPageId)?.visible !== false;
+ const after = await keyedStream(tx, input.sourceId, source.incarnation, input.newSlug);
+ // Each destination belief moves onto the surviving lifetime: by its rows, else (its row merged into an equal stale row) by its key; one with neither ends.
+ const transfers = new Map<string, { from: Subject; fromLifetime: string | null }>();
+ const ended: Subject[] = [];
+ const rowsAfter = new Set(after.subjects.flatMap(a => a.rowIds.map(id => `${a.kind}:${id}`)));
+ for (const s of dest.subjects) {
+ if (s.rowIds.some(id => rowsAfter.has(`${s.kind}:${id}`))) { for (const id of s.rowIds) transfers.set(`${s.kind}:${id}`, { from: s, fromLifetime: absorbed }); continue; }
+ const target = absorbed ? after.subjects.find(a => a.kind === s.kind && a.key === s.key.split(lifetimeRef(absorbed)).join(lifetimeRef(lifetime))) : undefined;
+ if (target) for (const id of target.rowIds) { if (!transfers.has(`${target.kind}:${id}`)) transfers.set(`${target.kind}:${id}`, { from: s, fromLifetime: absorbed }); }
+ else ended.push(s);
+ }
+ const cause = { op: 'rename_fallback' };
const publicationId = randomUUID();
const appended = await appendBeliefEvents(tx, [{ sourceId: input.sourceId, incarnation: source.incarnation, lifetime, slug: input.newSlug, stream: input.newSlug,
- subjectKind: 'page', subjectKey: pageKey(lifetime), eventType: 'page.renamed', trustTier: page?.trust_tier || 'unknown',
- visibility: visible ? 'world' : 'private', value: { old_slug: input.staleSlug, new_slug: input.newSlug, ...(absorbed && absorbed !== lifetime ? { absorbed_lifetime: absorbed } : {}) },
- stateHash: hash, cause: { op: 'rename_fallback' } }], { publicationId, origin: await readManagedMode(tx) ? 'live' : 'unmanaged', purgesPossible: source.purgesPossible });
+ subjectKind: 'page', subjectKey: pageKey(lifetime), eventType: 'page.renamed', trustTier: after.page?.tier || 'unknown',
+ visibility: after.page?.visible === false ? 'private' : 'world', value: { old_slug: input.staleSlug, new_slug: input.newSlug, ...(absorbed && absorbed !== lifetime ? { absorbed_lifetime: absorbed } : {}) },
+ stateHash: after.hash, cause },
+ ...streamSubjectDrafts({ sourceId: input.sourceId, incarnation: source.incarnation, slug: input.newSlug, lifetime, op: cause.op, writerTier: after.writerTier,
+ stateHash: after.hash, before: stale.subjects, after: after.subjects, transfers }),
+ ...streamSubjectDrafts({ sourceId: input.sourceId, incarnation: source.incarnation, slug: input.newSlug, lifetime: absorbed, op: cause.op, writerTier: after.writerTier,
+ stateHash: after.hash, before: ended, after: [], transfers: new Map() })],
+ { publicationId, origin: await readManagedMode(tx) ? 'live' : 'unmanaged', purgesPossible: source.purgesPossible });
return appended ? publicationId : null;
}
diff --git a/src/core/belief/ledger.ts b/src/core/belief/ledger.ts
index 33da404c48..bd12c02f1b 100644
--- a/src/core/belief/ledger.ts
+++ b/src/core/belief/ledger.ts
@@ -28,7 +28,9 @@ export type BeliefNote =
| { kind: 'withdrawn'; factIds: number[] }
| { kind: 'superseded'; oldId: number; newId: number | null }
| { kind: 'purged'; table: 'facts' | 'takes' | 'pages'; ids: number[]; request: string; derivedWalk?: 'truncated' }
- | { kind: 'transferred'; fromSlug: string; table: 'facts' | 'takes' | 'links'; ids: number[] };
+ | { kind: 'transferred'; fromSlug: string; table: 'facts' | 'takes' | 'links'; ids: number[] }
+ /** A tier change another writer caused (derived propagation): the batch's own `trust.retiered` for the row carries this cause. */
+ | { kind: 'retier_cause'; table: 'facts' | 'takes' | 'pages'; rowId: number; cause: Record<string, unknown> };
export interface BeliefBatchOptions {
sourceId: string;
@@ -136,9 +138,18 @@ async function streamLifetimes(tx: BrainEngine, sourceId: string, incarnation: s
const out = new Map<number, string>();
const pairs = streams.flatMap(s => [s.pre, s.post]).filter((p): p is RawPage => !!p).map(p => ({ incarnation, slug: p.slug }));
const open = await readOpenLifetimes(tx, pairs);
- const openAt = (slug: string) => open.get(`${incarnation}\u0000${slug}`) ?? null;
const fits = (row: { page_id: number | null } | null, id: number) => !!row && (row.page_id == null || row.page_id === id);
const mint = (page: RawPage) => mintLifetime(tx, { sourceId, incarnation, slug: page.slug, pageId: page.id });
+ // Renamed pages keep their lifetimes. Each moving lifetime is parked first, so renames that swap or chain slugs in one
+ // transaction neither end one another's lifetimes nor collide on the open-slug index; the slugs they leave read as free.
+ const moving = new Map<number, string>();
+ for (const { pre, post } of streams) {
+ const row = pre && post && pre.slug !== post.slug ? open.get(`${incarnation}\u0000${pre.slug}`) ?? null : null;
+ if (row && fits(row, post!.id)) moving.set(post!.id, row.page_lifetime);
+ }
+ const movingLifetimes = new Set(moving.values());
+ const openAt = (slug: string) => { const row = open.get(`${incarnation}\u0000${slug}`) ?? null; return row && movingLifetimes.has(row.page_lifetime) ? null : row; };
+ for (const [pageId, lifetime] of moving) await renameLifetime(tx, lifetime, `~moving-${lifetime}`, pageId);
for (const { pre, post } of streams) {
if (!pre || post) continue;
const row = openAt(pre.slug);
@@ -146,21 +157,24 @@ async function streamLifetimes(tx: BrainEngine, sourceId: string, incarnation: s
out.set(pre.id, lifetime);
await endLifetime(tx, lifetime);
}
+ const renames: Array<[string, RawPage]> = [];
for (const { pre, post } of streams) {
if (!post) continue;
- const row = openAt(pre?.slug ?? post.slug);
if (pre && pre.slug !== post.slug) {
const target = openAt(post.slug);
- if (target && target.page_lifetime !== row?.page_lifetime) await endLifetime(tx, target.page_lifetime);
- if (fits(row, post.id)) { await renameLifetime(tx, row!.page_lifetime, post.slug, post.id); out.set(post.id, row!.page_lifetime); }
+ if (target) await endLifetime(tx, target.page_lifetime);
+ const lifetime = moving.get(post.id);
+ if (lifetime) { renames.push([lifetime, post]); out.set(post.id, lifetime); }
else out.set(post.id, await mint(post));
continue;
}
+ const row = openAt(post.slug);
if (row && row.page_id === post.id) { out.set(post.id, row.page_lifetime); continue; }
if (pre && row && row.page_id == null) { out.set(post.id, row.page_lifetime); continue; }
if (row) await endLifetime(tx, row.page_lifetime);
out.set(post.id, await mint(post));
}
+ for (const [lifetime, post] of renames) await renameLifetime(tx, lifetime, post.slug, post.id);
return out;
}
@@ -212,6 +226,29 @@ function transferSources(notes: BeliefNote[], preSubjects: Subject[], lifetimeOf
return out;
}
+/**
+ * Subject events for one stream between two keyed sides, outside a batch's
+ * own diff: the fallback rename re-describes the lifetime it moves onto
+ * another row. `transfers` maps `kind:rowId` to the subject the row left.
+ */
+export function streamSubjectDrafts(input: { sourceId: string; incarnation: string; slug: string; lifetime: string | null; op: string; writerTier: string | null;
+ stateHash: string; before: Subject[]; after: Subject[]; transfers: Map<string, { from: Subject; fromLifetime: string | null }> }): BeliefEventDraft[] {
+ const opts: BeliefBatchOptions = { sourceId: input.sourceId, slugs: [input.slug], op: input.op };
+ const batch: Batch = { opts, publicationId: '', incarnation: input.incarnation, managed: false, purgesPossible: false, notes: [],
+ pre: { pages: [], facts: [], takes: [], links: [], transitions: [], writerTier: null } };
+ return subjectDrafts({ opts, batch, writerTier: tierOrUnknown(input.writerTier), lifetimeAt: () => input.lifetime, streamHash: () => input.stateHash,
+ cause: (extra = {}) => ({ op: input.op, ...extra }), postSubjects: input.after, transfers: input.transfers }, input.slug, input.before, input.after);
+}
+
+const RETIER_TABLE: Record<string, string> = { fact: 'facts', take: 'takes', page: 'pages' };
+/** The cause fields (minus `op`) another writer attached to this row's tier change, e.g. the inputs of a derived propagation. */
+function retierCauseOf(notes: BeliefNote[], s: { kind: string; rowIds: number[] }): Record<string, unknown> {
+ const note = notes.find(n => n.kind === 'retier_cause' && n.table === RETIER_TABLE[s.kind] && s.rowIds.includes(n.rowId));
+ if (note?.kind !== 'retier_cause') return {};
+ const { op: _op, ...rest } = note.cause;
+ return rest;
+}
+
/** Subject events of one stream side: asserted/retracted/revised, adoption, replacement links, retiering. */
function subjectDrafts(d: DiffContext, slug: string, before: Subject[], after: Subject[]): BeliefEventDraft[] {
const { batch, writerTier } = d;
@@ -275,7 +312,7 @@ function subjectDrafts(d: DiffContext, slug: string, before: Subject[], after: S
if (!prior || transferred.has(s)) continue;
const type = changeType(s.kind, prior, s);
if (type) draft(s, type, s.value, prior);
- if (prior.tier !== s.tier && s.kind !== 'link' && s.kind !== 'link_transition') draft(s, 'trust.retiered', { from: prior.tier, to: s.tier }, prior);
+ if (prior.tier !== s.tier && s.kind !== 'link' && s.kind !== 'link_transition') draft(s, 'trust.retiered', { from: prior.tier, to: s.tier }, prior, retierCauseOf(batch.notes, s));
}
return out;
}
@@ -309,7 +346,8 @@ function pageDrafts(d: DiffContext, stream: Stream, lifetime: string, after: Sub
else if (d.opts.pageEventType === 'page.view_changed' && p0!.content_hash !== p1!.content_hash) {
emit('page.view_changed', { revision_before: p0!.revision, revision_after: p1!.revision, materialized: true }, p1!.tier);
}
- if (p0!.tier !== p1!.tier) emit('trust.retiered', { from: p0!.tier, to: p1!.tier }, p1!.tier);
+ if (p0!.tier !== p1!.tier) push({ ...base, eventType: 'trust.retiered', trustTier: p1!.tier, value: { from: p0!.tier, to: p1!.tier },
+ cause: d.cause(retierCauseOf(d.batch.notes, { kind: 'page', rowIds: [p1!.id] })) });
return silenced || (p0!.deleted && p1!.deleted);
}
@@ -349,11 +387,22 @@ export async function finalizeBeliefEvents(tx: BrainEngine, batch: Batch): Promi
const silenced = pageDrafts(d, stream, lifetimes.get(page.id)!, after, draft => drafts.push(draft));
if (!silenced) drafts.push(...subjectDrafts(d, page.slug, before, after));
}
- const dbSlugs = new Set([...preSubjects, ...postSubjects].filter(s => s.dbOnly).map(s => s.stream));
- for (const slug of dbSlugs) drafts.push(...subjectDrafts(d, slug, preSubjects.filter(s => s.dbOnly && s.stream === slug), postSubjects.filter(s => s.dbOnly && s.stream === slug)));
+ // A renamed page's database-only facts follow it: their pre side is diffed under the slug the page moved to, so a rename moves no key.
+ const renamedTo = new Map(streams.flatMap(s => s.pre && s.post && s.pre.slug !== s.post.slug ? [[s.pre.slug, s.post.slug] as const] : []));
+ const dbPre = preSubjects.filter(s => s.dbOnly), dbPost = postSubjects.filter(s => s.dbOnly);
+ const dbStream = (s: Subject) => renamedTo.get(s.stream) ?? s.stream;
+ for (const slug of new Set([...dbPre.map(dbStream), ...dbPost.map(s => s.stream)])) {
+ drafts.push(...subjectDrafts(d, slug, dbPre.filter(s => dbStream(s) === slug), dbPost.filter(s => s.stream === slug)));
+ }
+ // A contested fact outside the batch's streams is keyed and hashed as its own stream holds it now (its page's lifetime when the page exists).
+ const extraStreams = new Map<string, Awaited<ReturnType<typeof currentStateHash>>>();
+ for (const f of extraFacts) {
+ const stream = f.sms ?? f.entity_slug;
+ if (stream && !extraStreams.has(stream)) extraStreams.set(stream, await currentStateHash(tx, opts.sourceId, batch.incarnation, stream));
+ }
for (const note of batch.notes) {
- if (note.kind === 'contested') drafts.push(...contestedDraft(d, note, { pre, post, preSubjects, postSubjects, extraFacts, lifetimes }));
+ if (note.kind === 'contested') drafts.push(...contestedDraft(d, note, { pre, post, preSubjects, postSubjects, extraFacts, extraStreams, lifetimes }));
else if (note.kind === 'held') {
const page = postPageAt(note.slug);
drafts.push({ sourceId: opts.sourceId, incarnation: batch.incarnation, lifetime: lifetimeAt(note.slug), slug: note.slug, stream: note.slug,
@@ -368,7 +417,8 @@ export async function finalizeBeliefEvents(tx: BrainEngine, batch: Batch): Promi
/** `trust.contested` on the held row's key: its tier as trust_tier, the challenger's as writer_tier (section 6.1). */
function contestedDraft(d: DiffContext, note: Extract<BeliefNote, { kind: 'contested' }>, s: { pre: RawState; post: RawState; preSubjects: Subject[];
- postSubjects: Subject[]; extraFacts: Awaited<ReturnType<typeof readFactsById>>; lifetimes: Map<number, string> }): BeliefEventDraft[] {
+ postSubjects: Subject[]; extraFacts: Awaited<ReturnType<typeof readFactsById>>; extraStreams: Map<string, Awaited<ReturnType<typeof currentStateHash>>>;
+ lifetimes: Map<number, string> }): BeliefEventDraft[] {
const cause = d.cause({ proposal: `tp${note.proposalId}`, guard: note.guard });
const base = { sourceId: d.opts.sourceId, incarnation: d.batch.incarnation, eventType: 'trust.contested', writerTier: d.writerTier, value: null };
if (note.table === 'pages') {
@@ -385,9 +435,12 @@ function contestedDraft(d: DiffContext, note: Extract<BeliefNote, { kind: 'conte
const fact = kind === 'fact' ? s.extraFacts.find(f => f.id === note.rowId) : undefined;
if (!fact) return [];
const stream = fact.sms ?? fact.entity_slug ?? '';
- const key = keyFact({ incarnation: d.batch.incarnation, lifetimes: s.lifetimes, pagesBySlug: new Map(s.post.pages.map(p => [p.slug, p])) }, fact).key;
- return [{ ...base, lifetime: d.lifetimeAt(stream), slug: stream, stream, subjectKind: 'fact', subjectKey: key, trustTier: fact.tier,
- visibility: fact.visibility, claimFp: fact.fp, stateHash: d.streamHash(stream), cause }];
+ const own = s.extraStreams.get(stream);
+ const page = own?.state.pages.find(p => p.slug === stream) ?? null;
+ const lifetimes = new Map([...s.lifetimes, ...own?.lifetimes ?? []]);
+ const key = keyFact({ incarnation: d.batch.incarnation, lifetimes, pagesBySlug: new Map(page ? [[stream, page]] : []) }, fact).key;
+ return [{ ...base, lifetime: page ? lifetimes.get(page.id) ?? null : null, slug: stream, stream, subjectKind: 'fact', subjectKey: key, trustTier: fact.tier,
+ visibility: fact.visibility, claimFp: fact.fp, stateHash: own?.hash ?? d.streamHash(stream), cause }];
}
/** The current belief-set hash of one stream, for the doctor drift check and reconcile. */
diff --git a/src/core/belief/lifetimes.ts b/src/core/belief/lifetimes.ts
index 4ea8fe628e..7a8e59697e 100644
--- a/src/core/belief/lifetimes.ts
+++ b/src/core/belief/lifetimes.ts
@@ -51,9 +51,18 @@ export async function resolveLifetimes(tx: BrainEngine, needs: readonly PageRefN
const unique = [...new Map(needs.map(n => [n.pageId, n])).values()];
const open = await readOpenLifetimes(tx, unique);
const out = new Map<number, string>();
+ const misses = unique.filter(need => { const row = open.get(pairKey(need.incarnation, need.slug)); return !row || (row.page_id != null && row.page_id !== need.pageId); });
+ // A page whose key the caller does not hold can be renamed between its read and this one (READ COMMITTED): an open lifetime of that page
+ // at the slug the page has now is still its own, so it is used rather than minting a second one at the slug the caller read.
+ const byPage = misses.length ? new Map((await tx.executeRaw<{ page_id: number; source_incarnation: string; page_lifetime: string }>(`SELECT l.page_id, l.source_incarnation::text AS source_incarnation,
+ l.page_lifetime::text AS page_lifetime FROM belief_page_lifetimes l JOIN pages p ON p.id = l.page_id AND p.slug = l.slug
+ WHERE l.page_id = ANY($1::int[]) AND l.ended_at IS NULL`, [misses.map(n => n.pageId)]))
+ .map(r => [`${r.source_incarnation}\u0000${Number(r.page_id)}`, r.page_lifetime])) : new Map<string, string>();
for (const need of unique) {
const row = open.get(pairKey(need.incarnation, need.slug));
if (row && (row.page_id == null || row.page_id === need.pageId)) { out.set(need.pageId, row.page_lifetime); continue; }
+ const moved = byPage.get(`${need.incarnation}\u0000${need.pageId}`);
+ if (moved) { out.set(need.pageId, moved); continue; }
if (row) await endLifetime(tx, row.page_lifetime);
out.set(need.pageId, await mintLifetime(tx, need));
}
diff --git a/src/core/belief/retier.ts b/src/core/belief/retier.ts
index 557c9b7dbf..8d50bf65e7 100644
--- a/src/core/belief/retier.ts
+++ b/src/core/belief/retier.ts
@@ -8,8 +8,10 @@
* `trust.retiered` per source and stream page, plus one
* `belief_retier_manifest` row (subject key, from, to) per changed subject,
* keyed by the summary event, so replay can say which belief's trust changed;
- * - derived propagation appends one `trust.retiered` per lowered dependent,
- * whose cause names each input and the event that recorded its change.
+ * - derived propagation appends one `trust.retiered` per lowered dependent
+ * outside the enclosing batch's streams, whose cause names each input and
+ * the event that recorded its change; a dependent inside them is recorded
+ * by the batch's diff, at its final state hash, with that cause.
*
* Neither holds its dependents' page keys (a lock taken late can deadlock), so
* these events order within a stream by the row locks the tier UPDATE took.
@@ -19,7 +21,7 @@ import type { BrainEngine } from '../engine.ts';
import { readManagedMode } from '../persistence/managed-mode.ts';
import { appendBeliefEvents, type BeliefEventDraft } from './append.ts';
import { eventKeyHex, pageKey, slugRef } from './keys.ts';
-import { coverageActive, currentBeliefBatch, readLedgerSource, stateHashOf } from './ledger.ts';
+import { coverageActive, currentBeliefBatch, noteBelief, readLedgerSource, stateHashOf } from './ledger.ts';
import { resolveLifetimes } from './lifetimes.ts';
import { readBeliefState, type RawPage } from './state.ts';
import { keyedSubjects, pageNeeds } from './subjects.ts';
@@ -81,9 +83,14 @@ const draftOf = (r: Resolved, cause: Record<string, unknown>): BeliefEventDraft
* one, else under `publicationId`. Returns the publication id when it appended.
*/
export async function appendRetierEvents(tx: BrainEngine, rows: readonly RetierRow[], cause: Record<string, unknown>, publicationId?: string): Promise<string | null> {
- const resolved = await resolveSubjects(tx, rows);
+ const batch = currentBeliefBatch();
+ const all = await resolveSubjects(tx, rows);
+ // A dependent in the enclosing batch's own streams is recorded by its finalization (after every write, with the final state hash); the batch carries the cause.
+ const inBatch = (r: Resolved) => !!batch && batch.sourceId === r.sourceId && batch.slugs.includes(r.stream);
+ for (const r of all.filter(inBatch)) noteBelief({ kind: 'retier_cause', table: r.row.table as 'facts' | 'takes' | 'pages', rowId: r.row.id, cause });
+ const resolved = all.filter(r => !inBatch(r));
if (!resolved.length) return null;
- const pub = currentBeliefBatch()?.publicationId ?? publicationId ?? randomUUID();
+ const pub = batch?.publicationId ?? publicationId ?? randomUUID();
let appended = 0;
for (const sourceId of new Set(resolved.map(r => r.sourceId))) {
const source = (await readLedgerSource(tx, sourceId))!;
diff --git a/src/core/facts/forget.ts b/src/core/facts/forget.ts
index 0584f5ffd3..26dd520340 100644
--- a/src/core/facts/forget.ts
+++ b/src/core/facts/forget.ts
@@ -10,6 +10,7 @@
* A Markdown-only clone does not carry DB-only withdrawal records.
*/
+import { randomUUID } from 'node:crypto';
import { existsSync, readFileSync, writeFileSync, renameSync } from 'node:fs';
import type { BrainEngine } from '../engine.ts';
@@ -23,6 +24,7 @@ import { contentHash } from '../utils.ts';
import { assertInlineBody } from '../page-body/page-shape.ts';
import { recordFactWithdrawal } from './withdrawal.ts';
import { maintenanceTransaction } from '../persistence/attribution.ts';
+import { markBeliefCommits } from '../belief/append.ts';
import { withdrawnFact } from './withdrawal-overlay.ts';
export interface ForgetFactResult {
@@ -168,7 +170,11 @@ export async function forgetFactInFence(
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 maintenanceTransaction(engine, tx => recordFactWithdrawal(tx, factId, row.source_id, opts.worldOnly === true));
+ // W1 #6783 §5.1: the withdrawal's ledger publication is marked committed once its transaction commits.
+ const publicationId = randomUUID();
+ const beliefReport = { appended: 0 };
+ await maintenanceTransaction(engine, tx => recordFactWithdrawal(tx, factId, row.source_id, opts.worldOnly === true, { publicationId, beliefReport }));
+ if (beliefReport.appended) await markBeliefCommits(engine, [publicationId]).catch(() => undefined);
}
if (row.expired_at !== null) {
diff --git a/src/core/facts/withdrawal.ts b/src/core/facts/withdrawal.ts
index 1865950bdf..dd851e0bae 100644
--- a/src/core/facts/withdrawal.ts
+++ b/src/core/facts/withdrawal.ts
@@ -51,7 +51,7 @@ export function reviewWithdrawOn(raw: string | null | undefined): boolean {
export async function recordFactWithdrawal(
engine: BrainEngine, id: number, sourceId: string, worldOnly = false,
- opts: { requestId?: string; semanticReview?: boolean; excludePrivate?: boolean; beliefReport?: { appended: number } } = {},
+ opts: { requestId?: string; publicationId?: string; semanticReview?: boolean; excludePrivate?: boolean; beliefReport?: { appended: number } } = {},
): Promise<WithdrawalCommit> {
return engine.transaction(async tx => {
// A managed caller takes this EXCLUSIVE source lock before authority,
@@ -89,7 +89,7 @@ export async function recordFactWithdrawal(
if (preimage) await createPageVersion(tx, page.slug, sourceId, preimage);
}
}
- return withBeliefBatch(tx, { sourceId, slugs, publicationId: opts.requestId ?? null, op: 'forget', pageEventType: 'page.view_changed',
+ return withBeliefBatch(tx, { sourceId, slugs, publicationId: opts.requestId ?? opts.publicationId ?? null, op: 'forget', pageEventType: 'page.view_changed',
remote: worldOnly, ...(opts.beliefReport ? { report: opts.beliefReport } : {}) }, async () => {
// Scoped to the forgotten row's entity: the same claim about another
// entity stays active and rememberable. A subjectless fact withdraws
diff --git a/src/core/page-state/materialize.ts b/src/core/page-state/materialize.ts
index 10d8c73372..580e9dddc1 100644
--- a/src/core/page-state/materialize.ts
+++ b/src/core/page-state/materialize.ts
@@ -1,4 +1,6 @@
+import { randomUUID } from 'node:crypto';
import type { BrainEngine } from '../engine.ts';
+import { markBeliefCommits } from '../belief/append.ts';
import { contentHash } from '../utils.ts';
import { assertInlineBody } from '../page-body/page-shape.ts';
import { assertPageRevision, type PageSnapshot } from './types.ts';
@@ -12,6 +14,8 @@ export async function materializePageSnapshot(engine: BrainEngine, snapshot: Pag
const sourceId = snapshot.page.source_id;
const slug = snapshot.page.slug;
const attribution = await maintenanceAttribution(engine);
+ const publicationId = randomUUID();
+ const report = { appended: 0 };
await engine.transaction(async tx => {
await tx.lockPageKeys([{ sourceId, slug }]);
const current = await tx.readPageSnapshot(slug, { sourceId, includeDeleted: true });
@@ -29,10 +33,11 @@ export async function materializePageSnapshot(engine: BrainEngine, snapshot: Pag
? (await tx.executeRaw<{ content_hash: string | null }>('SELECT content_hash FROM pages WHERE id=$1', [page.id]))[0]?.content_hash : undefined;
const hash = contentHash({ ...page, tags: current.tags });
if (stored !== undefined && stored !== hash) await createPageVersion(tx, slug, sourceId, current);
- await withCoordinatedWrite(tx, [sourceId], () => withBeliefBatch(tx, { sourceId, slugs: [slug], op: 'withdrawal_materialize', pageEventType: 'page.view_changed' },
+ await withCoordinatedWrite(tx, [sourceId], () => withBeliefBatch(tx, { sourceId, slugs: [slug], publicationId, op: 'withdrawal_materialize', pageEventType: 'page.view_changed', report },
() => tx.executeRaw(`UPDATE pages SET compiled_truth=$1,timeline=$2,content_hash=$3
WHERE id=$4 AND knowledge_revision=$5::uuid`,
[page.compiled_truth, page.timeline, hash, page.id, current.revision])), attribution);
await tx.executeRaw("SELECT set_config('gbrain.materializing_revision',$1,true)", [previous[0]?.revision ?? '']);
});
+ if (report.appended) await markBeliefCommits(engine, [publicationId]).catch(() => undefined);
}
diff --git a/src/core/trust/confirm.ts b/src/core/trust/confirm.ts
index 71bcfcd627..935b9d3afd 100644
--- a/src/core/trust/confirm.ts
+++ b/src/core/trust/confirm.ts
@@ -18,8 +18,6 @@ import { opError, OperationError, type OperationContext } from '../ops/contract.
import { databaseRefusal } from '../persistence/publication-failure.ts';
import { hasScope } from '../scope.ts';
import type { BrainEngine } from '../engine.ts';
-import { randomUUID } from 'node:crypto';
-import { releaseSuppressedFields, suppressedFields } from '../belief/purge.ts';
export const MEMORY_CONFIRM_SCOPE = 'memory_confirm';
@@ -92,19 +90,6 @@ export async function requireOwnerConfirmation(ctx: OperationContext, target: Co
{ why: 'Raising trust is the owner\'s decision, so it needs a person at a terminal typing the confirmation token; piped input, agents and --yes cannot confirm.', fix });
}
-/**
- * BELIEF_LEDGER.md 6.5: a carrying field a purge redacted (a fact's context, a take's resolution evidence) stays
- * redacted in recorded history until the owner releases it. Confirming the row is that release, bound to the field's
- * current value, so it needs the same owner confirmation as a raise. `pendingRedactionRelease` says whether a confirm
- * has one to make; `releaseConfirmedRedactions` makes it after the owner confirmed.
- */
-export async function pendingRedactionRelease(engine: BrainEngine, table: 'facts' | 'takes', id: number): Promise<string[]> {
- return suppressedFields(engine, table, id);
-}
-export async function releaseConfirmedRedactions(engine: BrainEngine, table: 'facts' | 'takes', id: number): Promise<string[]> {
- return releaseSuppressedFields(engine, table, id, randomUUID());
-}
-
/**
* The tier trigger's database refusal (trust/schema.ts) as the registered
* `trust_raise_refused` error, for direct writers outside the coordinator
diff --git a/src/core/trust/owner-actions.ts b/src/core/trust/owner-actions.ts
index a7b1a26bd0..71ea5d1ab8 100644
--- a/src/core/trust/owner-actions.ts
+++ b/src/core/trust/owner-actions.ts
@@ -24,7 +24,8 @@ import type { OperationContext } from '../ops/contract.ts';
import { opError } from '../ops/contract.ts';
import type { Principal } from '../persistence/model.ts';
import type { OwnerConfirmation } from './confirm.ts';
-import { pendingRedactionRelease, releaseConfirmedRedactions, tierRaiseFix } from './confirm.ts';
+import { tierRaiseFix } from './confirm.ts';
+import { releaseSuppressedFields, suppressedFields } from '../belief/purge.ts';
import { decideTrustProposal } from './decide.ts';
import { resolveContestedFactOnConfirm } from './supersede-handlers.ts';
import { getTrustProposal, pendingTrustProposalsFor, trustProposalRef, type TrustDecisionResult, type TrustProposalRow } from './proposals.ts';
@@ -281,7 +282,7 @@ async function previewConfirm(engine: BrainEngine, ref: TrustRef, input: OwnerAc
const row = ref.kind === 'fact' ? await readFactTarget(engine, ref.id) : await readTakeTarget(engine, ref.id);
if (!row) throw notFound(label, ref.kind);
if (!row.live) throw opError('invalid_params', `${label} is no longer active (expired, superseded or forgotten); there is nothing to confirm.`, 'Confirm the row that replaced it instead; gbrain trust explain shows its history.');
- const release = await pendingRedactionRelease(engine, row.table, row.id);
+ const release = await suppressedFields(engine, row.table, row.id);
return { action: 'confirm', ref: label, token: label, command: trustCommand('confirm', label), raises: row.tier !== 'user_confirmed' || release.length > 0, binding: row.binding,
tier: row.tier, target_tier: 'user_confirmed', summary: `Raise ${ref.kind} ${label} ("${snippet(row.text)}") from "${trustLabel(row.tier)}" to "confirmed by you"`
+ (release.length ? ` and release its purge-redacted ${release.join(', ')} in recorded history` : '') };
@@ -446,11 +447,13 @@ export async function applyOwnerAction(engine: BrainEngine, input: OwnerActionIn
const resolved = ref.kind === 'fact' && row.binding === opts.binding ? await resolveContestedFactOnConfirm(engine, ref.id, decision) : null;
if (resolved?.status === 'accepted') return { action: input.action, ref: preview.ref, status: 'confirmed', tier: 'user_confirmed', prior_tier: row.tier, detail: { resolved_proposal: resolved.ref } };
if (!preview.raises) return { action: input.action, ref: preview.ref, status: 'unchanged', tier: 'user_confirmed', prior_tier: 'user_confirmed' };
- const ok = row.tier === 'user_confirmed' || await setRowTier(engine, { table: row.table, id: row.id, sourceId: row.sourceId, tier: 'user_confirmed', ceiling: 'user_confirmed', by,
+ // BELIEF_LEDGER.md 6.5: the release is part of the confirm's publication, which released_by names.
+ let released: string[] = [];
+ const ok = await setRowTier(engine, { table: row.table, id: row.id, sourceId: row.sourceId, tier: 'user_confirmed', ceiling: 'user_confirmed', by,
note: { via: confirmation.via, action: 'confirm', by: principalLabel(by) },
- expect: async tx => (await read(tx, ref.id))?.binding === opts.binding });
+ expect: async tx => (await read(tx, ref.id))?.binding === opts.binding,
+ also: async (tx, publicationId) => { released = await releaseSuppressedFields(tx, row.table, row.id, publicationId); } });
if (!ok) throw opError('preview_changed', `${preview.ref} changed after you approved it; nothing was changed.`, 'Run the command again.');
- const released = await releaseConfirmedRedactions(engine, row.table, row.id);
return { action: input.action, ref: preview.ref, status: 'confirmed', tier: 'user_confirmed', prior_tier: row.tier, ...(released.length ? { detail: { released_redactions: released } } : {}) };
}
if (ref?.kind === 'page') {
diff --git a/src/core/trust/page-handlers.ts b/src/core/trust/page-handlers.ts
index c1973ac454..9d1cc5d49b 100644
--- a/src/core/trust/page-handlers.ts
+++ b/src/core/trust/page-handlers.ts
@@ -126,7 +126,7 @@ async function attributionFor(engine: BrainEngine, by: Principal | null | undefi
export async function setRowTier(engine: BrainEngine, input: {
table: 'facts' | 'takes' | 'pages'; id: number; sourceId: string; tier: TrustTier; ceiling?: TrustTier;
expect?: (tx: BrainEngine) => Promise<boolean>; by?: Principal | null; note?: Record<string, unknown>;
- also?: (tx: BrainEngine) => Promise<void>;
+ also?: (tx: BrainEngine, publicationId: string) => Promise<void>;
}): Promise<boolean> {
const attribution = await attributionFor(engine, input.by);
const enabled = await managed(engine);
@@ -139,13 +139,13 @@ export async function setRowTier(engine: BrainEngine, input: {
const update = () => tx.executeRaw<{ id: number }>(
`UPDATE ${input.table} SET trust_tier = $2,
write_origin = COALESCE(write_origin, '{}'::jsonb) || jsonb_build_object('owner_decision', $3::text::jsonb)
- WHERE id = $1 RETURNING id`, [input.id, input.tier, JSON.stringify({ tier: input.tier, at: new Date().toISOString(), ...input.note })]);
+ WHERE id = $1 RETURNING id`, [input.id, input.tier, JSON.stringify({ tier: input.tier, at: new Date().toISOString(), publication_id: publicationId, ...input.note })]);
const rows = input.ceiling ? await withTrustPromotion(tx, input.ceiling, update) : await update();
if (rows.length !== 1) return false;
await queueTierProjection(tx, input.table, input.id);
// W1 #6783 §12 (b): a lowering reaches what was derived from the row; a raise never does.
if (prior && compareTrust(input.tier, storedTrustTier(prior.trust_tier)) < 0) await propagateTierLowering(tx, [{ table: input.table, id: input.id }]);
- await input.also?.(tx);
+ await input.also?.(tx, publicationId);
return true;
};
// W1 #6783 §6.4: the tier change is recorded as trust.retiered in the row's stream, under its page key.
diff --git a/test/belief-ledger-coverage.test.ts b/test/belief-ledger-coverage.test.ts
index 0e27b385e8..2e56009646 100644
--- a/test/belief-ledger-coverage.test.ts
+++ b/test/belief-ledger-coverage.test.ts
@@ -32,6 +32,7 @@ import { runExtractFacts } from '../src/core/cycle/extract-facts.ts';
import { extractTakes } from '../src/core/cycle/extract-takes.ts';
import { extractStaleFromDB } from '../src/commands/extract.ts';
import { backfillBeliefHistory } from '../src/core/belief/backfill.ts';
+import { endLifetime, mintLifetime } from '../src/core/belief/lifetimes.ts';
import { beliefLedgerEntry } from '../src/commands/doctor/checks/belief-ledger.ts';
import type { DoctorContext } from '../src/commands/doctor/context.ts';
import type { Check } from '../src/commands/doctor.ts';
@@ -469,6 +470,44 @@ for (const engineCase of testBackends().map(beliefEngineCase)) {
}, { enable: false });
}, 180_000);
+ test('review #35: a backfill rerun after versions were pruned appends nothing, and a page whose lifetime turned over after preparation is not backfilled onto the ended lifetime', async () => {
+ await brain(async b => {
+ await b.put('companies/acme-example', beliefPage({ facts: ['Acme raised a seed round'] }));
+ await b.put('companies/acme-example', beliefPage({ facts: ['Acme raised a seed round', 'Acme has ten staff'] }));
+ await b.put('companies/acme-example', beliefPage({ facts: ['Acme has ten staff'] }));
+ await b.enable();
+ expect((await backfillBeliefHistory(b.engine, b.sourceId)).events).toBe(7);
+ const after = await b.lastId();
+ await b.engine.executeRaw(`DELETE FROM page_versions WHERE id = (SELECT min(v.id) FROM page_versions v JOIN pages p ON p.id = v.page_id
+ WHERE p.source_id = $1 AND p.slug = 'companies/acme-example')`, [b.sourceId]);
+ expect((await backfillBeliefHistory(b.engine, b.sourceId)).events).toBe(0);
+ expect(await b.lastId()).toBe(after);
+ const keyed = await b.engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM belief_events WHERE source_id = $1 AND origin = 'backfill'
+ AND subject_kind = 'fact' AND event_type = 'fact.asserted' GROUP BY subject_key HAVING count(*) > 1`, [b.sourceId]);
+ expect(keyed).toEqual([]);
+ await b.put('companies/beta-example', beliefPage({ title: 'Beta Example', facts: ['Beta ships late'] }));
+ await b.put('companies/beta-example', beliefPage({ title: 'Beta Example', facts: ['Beta ships early'] }));
+ const since = (await coverageIntervals(b.engine, b.sourceId))[0]!.started_at;
+ await b.engine.executeRaw(`UPDATE pages SET created_at = $2::timestamptz - interval '1 hour' WHERE source_id = $1 AND slug = 'companies/beta-example'`, [b.sourceId, since]);
+ await b.engine.executeRaw(`UPDATE page_versions SET snapshot_at = $2::timestamptz - interval '1 minute' WHERE page_id = (SELECT id FROM pages
+ WHERE source_id = $1 AND slug = 'companies/beta-example')`, [b.sourceId, since]);
+ const [{ page_lifetime: old }] = await b.engine.executeRaw<{ page_lifetime: string }>(`SELECT l.page_lifetime::text AS page_lifetime FROM belief_page_lifetimes l
+ WHERE l.source_id = $1 AND l.slug = 'companies/beta-example' AND l.ended_at IS NULL`, [b.sourceId]);
+ const report = await backfillBeliefHistory(b.engine, b.sourceId, { slugs: ['companies/beta-example'], prepareHook: async (_slug, attempt) => {
+ if (attempt > 0) return;
+ const source = (await readLedgerSource(b.engine, b.sourceId))!;
+ const [{ id }] = await b.engine.executeRaw<{ id: number }>(`SELECT id FROM pages WHERE source_id = $1 AND slug = 'companies/beta-example'`, [b.sourceId]);
+ await b.engine.transaction(async tx => {
+ await tx.lockPageKeys([{ sourceId: b.sourceId, slug: 'companies/beta-example' }]);
+ await endLifetime(tx, old);
+ await mintLifetime(tx, { sourceId: b.sourceId, incarnation: source.incarnation, slug: 'companies/beta-example', pageId: Number(id) });
+ });
+ } });
+ expect(report).toMatchObject({ events: 6, retried: 1, pages: [{ slug: 'companies/beta-example', events: 6 }] });
+ expect(await b.engine.executeRaw(`SELECT id FROM belief_events WHERE page_lifetime = $1::uuid AND origin = 'backfill'`, [old])).toEqual([]);
+ }, { enable: false });
+ }, 180_000);
+
test('probe 9: graduation PGLite -> ' + engineCase.name + ' carries an identical ledger: equal event_key sets, digests and replay', async () => {
await beliefBrain(async b => {
await seeded(b);
diff --git a/test/belief-ledger-identity.test.ts b/test/belief-ledger-identity.test.ts
index 1c6e900813..385327dfd1 100644
--- a/test/belief-ledger-identity.test.ts
+++ b/test/belief-ledger-identity.test.ts
@@ -27,7 +27,12 @@ import { renamePageOntoSlug } from '../src/commands/sync/rename-collision.ts';
import { carryRenameIdentity } from '../src/commands/sync/renames.ts';
import { enableBeliefLedger } from '../src/core/belief/coverage.ts';
import { lifetimeAtSlug, lifetimeSlugAt } from '../src/core/belief/identity.ts';
-import { currentStateHash } from '../src/core/belief/ledger.ts';
+import { currentStateHash, noteBelief, withBeliefBatch } from '../src/core/belief/ledger.ts';
+import { renameLifetime, resolveLifetimes } from '../src/core/belief/lifetimes.ts';
+import { maintenanceTransaction } from '../src/core/persistence/attribution.ts';
+import { recordDerivationInputs } from '../src/core/facts/derivation-inputs.ts';
+import { propagateTierLowering } from '../src/core/trust/propagation.ts';
+import { keyedSubjects } from '../src/core/belief/subjects.ts';
import { lifetimeRef, pageKey } from '../src/core/belief/keys.ts';
import { __setBeliefEmitterFaultForTests, type BeliefEventDraft } from '../src/core/belief/append.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
@@ -142,6 +147,142 @@ for (const engineCase of testBackends().map(beliefEngineCase)) {
await expect(check(forced, 'notes/forced-example', 'notes/forced-moved-example', forcedLifetime)).rejects.toThrow();
}), 120_000);
+ test('review #5: a cheap rename of a page with a database-only fact moves no fact key and leaves the fact live', () => brain(async b => {
+ await operationsByName.remember!.handler(b.ctx as OperationContext, { fact: 'Zeta example prefers tea', provenance: 'notes', entity: 'people/zeta-example', request_id: randomUUID() });
+ await b.put('people/zeta-example', beliefPage({ type: 'person', title: 'Zeta Example' }));
+ const factKey = (await b.events()).find(e => e.event_type === 'fact.adopted')!.subject_key;
+ const [{ incarnation }] = await b.engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [b.sourceId]);
+ const check = async (events: BeliefEvent[], slug: string) => {
+ expect(events.filter(e => e.subject_kind === 'fact' && e.event_type !== 'trust.retiered')).toEqual([]);
+ const last = (await b.events()).filter(e => e.subject_key === factKey).at(-1)!;
+ expect(last.event_type).toMatch(/^fact\.(asserted|adopted|revised|transferred)$|^trust\.retiered$/);
+ const now = await b.engine.transaction(tx => currentStateHash(tx, b.sourceId, incarnation!, slug));
+ const [newest] = await b.engine.executeRaw<{ state_hash: string }>('SELECT state_hash FROM belief_events WHERE source_id=$1 AND slug=$2 ORDER BY id DESC LIMIT 1', [b.sourceId, slug]);
+ expect(newest!.state_hash).toBe(now.hash);
+ };
+ // The new slug sorts before the old one, so a per-slug diff would append the retraction last.
+ renameSync(join(b.root, 'people/zeta-example.md'), join(b.root, 'people/alpha-example.md'));
+ const renamed = await since(b, () => renamePageOntoSlug(b.engine, { sourceId: b.sourceId, oldSlug: 'people/zeta-example', newSlug: 'people/alpha-example', to: 'people/alpha-example.md' }));
+ expect(renamed.filter(e => e.event_type === 'page.renamed')).toHaveLength(1);
+ await check(renamed, 'people/alpha-example');
+ // Forced probe: an emitter that records the fact as retracted on the rename is caught.
+ fault(drafts => [...drafts, ...drafts.filter(d => d.eventType === 'page.renamed').map(d => ({ ...d, subjectKind: 'fact' as const, subjectKey: factKey, eventType: 'fact.retracted', value: null }))]);
+ renameSync(join(b.root, 'people/alpha-example.md'), join(b.root, 'people/aardvark-example.md'));
+ const forced = await since(b, () => renamePageOntoSlug(b.engine, { sourceId: b.sourceId, oldSlug: 'people/alpha-example', newSlug: 'people/aardvark-example', to: 'people/aardvark-example.md' }));
+ await expect(check(forced, 'people/aardvark-example')).rejects.toThrow();
+ }), 120_000);
+
+ test('review #18: after a fallback rename the surviving lifetime describes the destination page, and the ended lifetime keeps no belief', () => brain(async b => {
+ const [{ incarnation }] = await b.engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [b.sourceId]);
+ const currentKeys = async (slug: string) => {
+ const { state, lifetimes } = await b.engine.transaction(tx => currentStateHash(tx, b.sourceId, incarnation!, slug));
+ const page = state.pages.find(p => p.slug === slug)!;
+ return keyedSubjects({ incarnation: incarnation!, lifetimes, pagesBySlug: new Map([[slug, page]]) }, state, () => 'world')
+ .filter(s => s.stream === slug && s.kind !== 'link_transition').map(s => s.key);
+ };
+ const run = async (stale: string, dest: string) => {
+ await b.put(stale, beliefPage({ type: 'note', title: 'Stale', takes: ['Stale take survives'], facts: ['Both pages hold this'] }));
+ await b.put(dest, beliefPage({ type: 'note', title: 'Dest', takes: ['Dest take is new'], facts: ['Both pages hold this', 'Only the destination holds this'] }));
+ const staleKeys = await currentKeys(stale), destKeys = await currentKeys(dest);
+ const absorbed = await lifetimeOf(b, dest);
+ const events = await since(b, () => carryRenameIdentity(b.engine, b.sourceId, stale, dest));
+ return { staleKeys, destKeys, absorbed, events, after: await currentKeys(dest) };
+ };
+ const asserting = /\.(asserted|revised|adopted|transferred)$/;
+ const check = (r: Awaited<ReturnType<typeof run>>) => {
+ expect(r.events.filter(e => e.subject_kind === 'page').map(e => e.event_type)).toEqual(['page.renamed']);
+ const last = new Map(r.events.filter(e => e.subject_kind !== 'page' && !e.event_type.startsWith('trust.')).map(e => [e.subject_key, e]));
+ // A destination belief the stale lifetime did not hold is recorded on it; a stale belief the destination lacks is retracted.
+ for (const key of r.after.filter(k => !r.staleKeys.includes(k))) expect(last.get(key)?.event_type).toMatch(asserting);
+ for (const key of r.staleKeys.filter(k => !r.after.includes(k))) expect(last.get(key)?.event_type).toMatch(/\.retracted$/);
+ // Every belief of the ended lifetime is named by a transfer onto the surviving one.
+ const from = new Set(r.events.filter(e => e.event_type.endsWith('.transferred')).map(e => e.cause.from_key));
+ expect(r.destKeys.every(k => from.has(k))).toBe(true);
+ expect(r.events.filter(e => e.event_type.endsWith('.transferred')).every(e => e.cause.from_lifetime === r.absorbed)).toBe(true);
+ expect(r.events.filter(e => e.event_type === 'take.retracted').map(e => e.value)).toEqual([null]);
+ };
+ check(await run('notes/stale-example', 'notes/dest-example'));
+ // Forced probe: an emitter that records the destination's beliefs as fresh assertions, leaving the ended lifetime's beliefs live, is caught.
+ fault(drafts => drafts.map(d => d.eventType.endsWith('.transferred') ? { ...d, eventType: d.eventType.replace('.transferred', '.asserted') } : d));
+ const forced = await run('notes/stale-two-example', 'notes/dest-two-example');
+ expect(() => check(forced)).toThrow();
+ }), 120_000);
+
+ test('review #31: a contested fact outside the batch\'s streams is keyed by its page\'s lifetime and hashed as its own stream', () => brain(async b => {
+ await b.put('companies/acme-example', beliefPage({ facts: ['Acme raised a seed round'] }));
+ await b.put('notes/other-example', beliefPage({ type: 'note', title: 'Other' }));
+ const acme = await lifetimeOf(b, 'companies/acme-example');
+ const [fact] = await b.engine.executeRaw<{ id: number }>('SELECT id FROM facts WHERE source_id=$1 AND fact=$2', [b.sourceId, 'Acme raised a seed round']);
+ const [{ incarnation }] = await b.engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [b.sourceId]);
+ const events = await since(b, () => b.engine.transaction(async tx => {
+ await tx.lockPageKeys([{ sourceId: b.sourceId, slug: 'notes/other-example' }]);
+ await withBeliefBatch(tx, { sourceId: b.sourceId, slugs: ['notes/other-example'], op: 'review_probe' },
+ async () => noteBelief({ kind: 'contested', table: 'facts', rowId: Number(fact!.id), proposalId: 1, guard: 'review_probe' }));
+ }));
+ const hash = (await b.engine.transaction(tx => currentStateHash(tx, b.sourceId, incarnation!, 'companies/acme-example'))).hash;
+ expect(events.map(e => [e.event_type, e.slug, e.page_lifetime, (JSON.parse(e.subject_key) as unknown[]).slice(0, 2), e.state_hash]))
+ .toEqual([['trust.contested', 'companies/acme-example', acme, ['f', lifetimeRef(acme)], hash]]);
+ }), 120_000);
+
+ test('review #40: a lifetime renamed after the caller read the page is resolved by page id, not minted again at the old slug', () => brain(async b => {
+ await b.put('notes/p-example', beliefPage({ type: 'note', title: 'P' }));
+ const lifetime = await lifetimeOf(b, 'notes/p-example');
+ const [{ id, incarnation }] = await b.engine.executeRaw<{ id: number; incarnation: string }>(
+ 'SELECT p.id, s.incarnation::text AS incarnation FROM pages p JOIN sources s ON s.id=p.source_id WHERE p.source_id=$1 AND p.slug=$2', [b.sourceId, 'notes/p-example']);
+ // A concurrent rename commits between this caller's page read (slug notes/p-example) and its lifetime read.
+ await b.engine.transaction(async tx => {
+ await tx.executeRaw('UPDATE pages SET slug=$1 WHERE id=$2', ['notes/q-example', id]);
+ await renameLifetime(tx, lifetime, 'notes/q-example', Number(id));
+ });
+ const resolved = await b.engine.transaction(tx => resolveLifetimes(tx, [{ sourceId: b.sourceId, incarnation: incarnation!, slug: 'notes/p-example', pageId: Number(id) }]));
+ expect(resolved.get(Number(id))).toBe(lifetime);
+ const open = await b.engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM belief_page_lifetimes WHERE page_id=$1 AND ended_at IS NULL', [id]);
+ expect(Number(open[0]!.n)).toBe(1);
+ }), 120_000);
+
+ test('review #32: a dependent lowered inside the batch\'s own stream is recorded once by the batch, with its final state hash and the input as cause', () => brain(async b => {
+ const slug = 'notes/lab-example';
+ await b.put(slug, beliefPage({ type: 'note', title: 'Lab', facts: ['The lab opened in 2020', 'The lab has ten benches'] }));
+ const ids = await b.engine.executeRaw<{ id: number; fact: string }>('SELECT id, fact FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 ORDER BY row_num', [b.sourceId, slug]);
+ const [input, dependent] = ids.map(r => Number(r.id));
+ await maintenanceTransaction(b.engine, tx => recordDerivationInputs(tx, { table: 'facts', id: dependent!, sourceId: b.sourceId }, [{ table: 'facts', id: input! }]));
+ const [{ incarnation }] = await b.engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [b.sourceId]);
+ const events = await since(b, () => maintenanceTransaction(b.engine, async tx => {
+ await tx.lockPageKeys([{ sourceId: b.sourceId, slug }]);
+ await withBeliefBatch(tx, { sourceId: b.sourceId, slugs: [slug], op: 'review_probe' }, async () => {
+ await tx.executeRaw(`UPDATE facts SET trust_tier='external_untrusted' WHERE id=$1`, [input]);
+ await propagateTierLowering(tx, [{ table: 'facts', id: input! }]);
+ // A later write in the same stream, after the propagation.
+ await tx.executeRaw('UPDATE facts SET confidence=0.5 WHERE id=$1', [dependent]);
+ });
+ }));
+ const final = (await b.engine.transaction(tx => currentStateHash(tx, b.sourceId, incarnation!, slug))).hash;
+ const retiered = events.filter(e => e.event_type === 'trust.retiered' && e.subject_kind === 'fact');
+ expect(retiered).toHaveLength(2);
+ expect(new Set(retiered.map(e => e.state_hash))).toEqual(new Set([final]));
+ const inputKey = retiered.find(e => !e.cause.inputs)!.subject_key;
+ expect(retiered.find(e => e.cause.inputs)!.cause).toMatchObject({ op: 'review_probe', inputs: [{ subject_key: inputKey }] });
+ }), 120_000);
+
+ test('review #34: two pages that swap slugs in one transaction each keep their own lifetime, both open', () => brain(async b => {
+ await b.put('notes/a-example', beliefPage({ type: 'note', title: 'A' }));
+ await b.put('notes/b-example', beliefPage({ type: 'note', title: 'B' }));
+ const a = await lifetimeOf(b, 'notes/a-example'), bb = await lifetimeOf(b, 'notes/b-example');
+ const events = await since(b, () => maintenanceTransaction(b.engine, async tx => {
+ await tx.lockPageKeys(['notes/a-example', 'notes/b-example'].map(slug => ({ sourceId: b.sourceId, slug })));
+ await withBeliefBatch(tx, { sourceId: b.sourceId, slugs: ['notes/a-example', 'notes/b-example'], op: 'review_probe' }, async () => {
+ await tx.executeRaw('UPDATE pages SET slug=$1 WHERE source_id=$2 AND slug=$3', ['notes/swap-example', b.sourceId, 'notes/a-example']);
+ await tx.executeRaw('UPDATE pages SET slug=$1 WHERE source_id=$2 AND slug=$3', ['notes/a-example', b.sourceId, 'notes/b-example']);
+ await tx.executeRaw('UPDATE pages SET slug=$1 WHERE source_id=$2 AND slug=$3', ['notes/b-example', b.sourceId, 'notes/swap-example']);
+ });
+ }));
+ expect(events.filter(e => e.event_type === 'page.renamed').map(e => [e.page_lifetime, e.value]).sort()).toEqual([
+ [a, { old_slug: 'notes/a-example', new_slug: 'notes/b-example' }], [bb, { old_slug: 'notes/b-example', new_slug: 'notes/a-example' }]].sort());
+ const open = await b.engine.executeRaw<{ page_lifetime: string; slug: string }>(
+ 'SELECT page_lifetime::text AS page_lifetime, slug FROM belief_page_lifetimes WHERE page_lifetime = ANY($1::uuid[]) AND ended_at IS NULL ORDER BY slug', [[a, bb]]);
+ expect(open.map(r => [r.slug, r.page_lifetime])).toEqual([['notes/a-example', bb], ['notes/b-example', a]]);
+ }), 120_000);
+
test('probe 29: a renamed link endpoint changes no key, a reused slug starts a new lifetime, and a database-only fact is adopted by its later page', () => brain(async b => {
await b.put('people/bob-example', beliefPage({ type: 'person', title: 'Bob Example' }));
await b.put('notes/meeting-example', beliefPage({ type: 'note', title: 'Meeting', links: ['people/bob-example'] }));
diff --git a/test/belief-ledger-purge.test.ts b/test/belief-ledger-purge.test.ts
index 58a2d5d535..17a7c2009b 100644
--- a/test/belief-ledger-purge.test.ts
+++ b/test/belief-ledger-purge.test.ts
@@ -192,6 +192,29 @@ for (const engineCase of testBackends().map(beliefEngineCase)) {
}, redactionFault('skip_live_carriers'));
}, 240_000);
+ test('review #43: a confirm releases the purge redaction in its own publication, which released_by names and the row records', async () => {
+ await brain(async b => {
+ const slug = 'companies/acme-example';
+ const page = (context: string, confidence = '1.0') => beliefPage({ facts: [X, { claim: 'Acme sells widgets', context, confidence }] });
+ await b.put(slug, page(`notes say ${X}`));
+ await purgeFact(b, X);
+ await b.put(slug, page('agent rewrote this', '0.5'));
+ const [fact] = await b.engine.executeRaw<{ id: number }>(`SELECT id FROM facts WHERE source_id = $1 AND fact = 'Acme sells widgets' AND expired_at IS NULL`, [b.sourceId]);
+ const preview = await previewOwnerAction(b.engine, { action: 'confirm', ref: `f${fact!.id}` });
+ const mark = await b.lastId();
+ const result = await applyOwnerAction(b.engine, { action: 'confirm', ref: `f${fact!.id}` }, { binding: preview.binding, confirmation: { via: 'tty' } });
+ expect(result).toMatchObject({ status: 'confirmed', detail: { released_redactions: ['context'] } });
+ const [register] = await b.engine.executeRaw<{ released_by: string }>(`SELECT released_by::text AS released_by FROM belief_redactions
+ WHERE source_id = $1 AND field = 'context' AND released_hash IS NOT NULL`, [b.sourceId]);
+ const confirm = (await b.events(mark)).filter(e => e.publication_id === register!.released_by);
+ expect(confirm.map(e => [`${e.subject_kind}:${e.event_type}`, e.trust_tier])).toEqual([['fact:trust.retiered', 'user_confirmed']]);
+ const [row] = await b.engine.executeRaw<{ publication: string; marked: boolean }>(`SELECT f.write_origin->'owner_decision'->>'publication_id' AS publication,
+ EXISTS (SELECT 1 FROM belief_commit_marks m WHERE m.publication_id::text = f.write_origin->'owner_decision'->>'publication_id') AS marked
+ FROM facts f WHERE f.id = $1`, [fact!.id]);
+ expect(row).toEqual({ publication: register!.released_by, marked: true });
+ });
+ }, 240_000);
+
test('probe 38: the suppression follows replacement, adoption, transfer and a verbatim copy into an unlinked fact', async () => {
const scenario = () => collect<Record<string, unknown>>(resolve => brain(async b => {
const slug = 'companies/acme-example', quote = `notes say ${X}`;
diff --git a/test/belief-ledger-trust.test.ts b/test/belief-ledger-trust.test.ts
index e85c83df59..80b6bdfd1b 100644
--- a/test/belief-ledger-trust.test.ts
+++ b/test/belief-ledger-trust.test.ts
@@ -39,7 +39,9 @@ import { withEnv } from './helpers/with-env.ts';
import { waitForValue } from './helpers/wait-for.ts';
import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
import { testBackends } from './helpers/test-backends.ts';
-import { beliefEngineCase, beliefPage, readEvents, shape, type BeliefEvent } from './helpers/belief-ledger.ts';
+import { beliefBrain, beliefEngineCase, beliefPage, readEvents, shape, type BeliefEvent } from './helpers/belief-ledger.ts';
+import { unmarkedPublications } from '../src/core/belief/coverage-report.ts';
+import { forgetFactInFence } from '../src/core/facts/forget.ts';
const home = mkdtempSync(join(tmpdir(), 'gbrain-belief-trust-'));
const quiet = { info() {}, warn() {}, error() {} };
@@ -151,6 +153,27 @@ for (const engineCase of testBackends().map(beliefEngineCase)) {
expect(() => check(forced, current)).toThrow();
}), 120_000);
+ test('review #25: the withdrawal, its materialization and an unmanaged forget each leave a commit mark', withHome(async () => {
+ const b = await brain();
+ const slug = 'companies/acme-example';
+ await run(b.local, 'put_page', { slug, content: beliefPage({ facts: ['Acme raised a seed round', 'Acme has ten staff'] }) });
+ const mark = await lastId(b);
+ await run(b.local, 'forget', { id: String(await factId(b, 'Acme has ten staff')) });
+ await waitForValue(async () => (await readEvents(b.engine, b.sourceId, mark)).find(e => e.cause.op === 'withdrawal_materialize'), { timeoutMs: 30_000, label: 'withdrawal materialization' });
+ const ops = new Set((await readEvents(b.engine, b.sourceId, mark)).map(e => e.cause.op));
+ expect([...ops].sort()).toEqual(['forget', 'withdrawal_materialize']);
+ expect(await unmarkedPublications(b.engine, b.sourceId)).toEqual([]);
+ await beliefBrain(async u => {
+ const remembered = await operationsByName.remember!.handler(u.ctx, { fact: 'Dana example likes tea', provenance: 'notes', entity: 'people/dana-example', request_id: randomUUID() }) as Record<string, any>;
+ const row = { id: Number(remembered.id) };
+ const before = await u.lastId();
+ // The legacy fence path (`forgetFactInFence`), which records the withdrawal in its own maintenance transaction.
+ expect((await forgetFactInFence(u.engine, Number(row!.id), { sourceId: u.sourceId })).ok).toBe(true);
+ expect((await u.events(before)).filter(e => e.event_type === 'fact.withdrawn')).toHaveLength(1);
+ expect(await unmarkedPublications(u.engine, u.sourceId)).toEqual([]);
+ }, { databaseUrl: engineCase.databaseUrl });
+ }), 180_000);
+
test('probe 8: a lower-tier fence rewrite, remember.replaces, takes_supersede and a refused remote forget each append trust.contested with the proposal', withHome(async () => {
const b = await brain();
const slug = 'companies/acme-example';