Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

W1 lane B: trust, withdrawal and database-only writers record belief events (probes 8, 20, 23, 24, 25, 26, 28)

garrytan7ae2b1971d8b
diff --git a/src/commands/sync/renames.ts b/src/commands/sync/renames.ts
index eea86a78c4..45eca41355 100644
--- a/src/commands/sync/renames.ts
+++ b/src/commands/sync/renames.ts
@@ -33,6 +33,8 @@ import type { TrackedSlugIndex } from './rename-reconcile.ts';
import { clearLegacyHold, holdRefusedImport, holdRenameDestination, noteScreenedImport } from './holds.ts';
import { partial, noteTypeWarning, markCompleted } from './sync-run.ts';
import type { SyncPlan, SyncRun, SyncProgress } from './sync-run.ts';
+import { recordFallbackRename } from '../../core/belief/identity.ts';
+import { markBeliefCommits } from '../../core/belief/append.ts';
type RenamePlan = Pick<SyncPlan, 'opts' | 'filtered' | 'manifest' | 'lastCommit' | 'pin' | 'gitContextRoot' | 'modePath' | 'syncImportRoot' | 'syncActivePack' | 'holds'>;
@@ -352,16 +354,19 @@ async function applyRename(
* aliases) move, and page-id-keyed rows (edges, timeline, versions) move with
* duplicates on their unique keys dropped from the stale side.
*/
-async function carryRenameIdentity(engine: BrainEngine, sourceId: string, staleSlug: string, newSlug: string): Promise<void> {
+export async function carryRenameIdentity(engine: BrainEngine, sourceId: string, staleSlug: string, newSlug: string): Promise<void> {
const rows = await engine.executeRaw<{ slug: string; id: number | string }>(
'SELECT slug, id FROM pages WHERE source_id = $1 AND slug = ANY($2::text[])', [sourceId, [staleSlug, newSlug]]);
const from = rows.find(r => r.slug === staleSlug), to = rows.find(r => r.slug === newSlug);
if (!from || !to || from.id === to.id) return;
- await maintenanceTransaction(engine, async tx => {
+ 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) });
});
+ if (publication) await markBeliefCommits(engine, [publication]).catch(() => undefined);
}
/**
diff --git a/src/core/belief/coverage.ts b/src/core/belief/coverage.ts
index 1204cbeda7..d736d8dc5c 100644
--- a/src/core/belief/coverage.ts
+++ b/src/core/belief/coverage.ts
@@ -78,6 +78,7 @@ async function pendingSlugs(engine: BrainEngine, sourceId: string, runId: string
const rows = await engine.executeRaw<{ slug: string }>(`SELECT slug FROM (
SELECT p.slug FROM pages p WHERE p.source_id = $1
UNION SELECT f.entity_slug FROM facts f WHERE f.source_id = $1 AND f.source_markdown_slug IS NULL AND f.expired_at IS NULL AND f.entity_slug IS NOT NULL
+ UNION SELECT f.source_markdown_slug FROM facts f WHERE f.source_id = $1 AND f.dimension IS NOT NULL AND f.row_num IS NULL AND f.expired_at IS NULL AND f.source_markdown_slug IS NOT NULL
) s WHERE s.slug > $3 AND NOT EXISTS (SELECT 1 FROM belief_events e WHERE e.source_id = $1 AND e.slug = s.slug AND e.event_type = 'baseline' AND e.cause->>'run' = $2)
ORDER BY s.slug LIMIT ${BASELINE_BATCH}`, [sourceId, runId, after]);
return rows.map(r => r.slug);
diff --git a/src/core/belief/identity.ts b/src/core/belief/identity.ts
new file mode 100644
index 0000000000..ae2a635ab5
--- /dev/null
+++ b/src/core/belief/identity.ts
@@ -0,0 +1,71 @@
+/**
+ * Identity events outside a publication diff (docs/designs/BELIEF_LEDGER.md
+ * section 3) and the slug-at-time lookup replay uses.
+ *
+ * A cheap rename (`updateSlug`) keeps the page row, so the publication's batch
+ * pairs the two sides by page id and records `page.renamed` itself. The
+ * fallback rename (#5431) materializes the destination as a new row and moves
+ * the old row's identity onto it; `recordFallbackRename` gives the destination
+ * the old page's lifetime, so the rename is one `page.renamed` and the history
+ * stays on one lifetime.
+ */
+import { randomUUID } from 'node:crypto';
+import type { BrainEngine } from '../engine.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';
+
+/**
+ * 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.
+ */
+export async function recordFallbackRename(tx: BrainEngine, input: { sourceId: string; staleSlug: string; newSlug: string; fromPageId: number; toPageId: number }): Promise<string | null> {
+ const source = await readLedgerSource(tx, input.sourceId);
+ if (!source || !coverageActive(source.coverage)) 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;
+ 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 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: source.managed ? 'live' : 'unmanaged', purgesPossible: source.purgesPossible });
+ return appended ? publicationId : null;
+}
+
+/**
+ * The slug a page lifetime had at `at`, from its own events (each carries the
+ * stream slug at recording time); null when the lifetime had no event by then.
+ * Replay resolves a rename this way: before it, the old slug.
+ */
+export async function lifetimeSlugAt(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, lifetime: string, at: Date): Promise<string | null> {
+ const [row] = await engine.executeRaw<{ slug: string }>(`SELECT slug FROM belief_events
+ WHERE source_id = $1 AND page_lifetime = $2::uuid AND subject_kind = 'page' AND recorded_at <= $3::timestamptz ORDER BY id DESC LIMIT 1`,
+ [sourceId, lifetime, at.toISOString()]);
+ return row?.slug ?? null;
+}
+
+/**
+ * The page lifetime that held `slug` at `at`: the lifetime of the newest page
+ * event recorded at that slug by then, unless that lifetime had moved to
+ * another slug by then. Null when no page held it.
+ */
+export async function lifetimeAtSlug(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, slug: string, at: Date): Promise<string | null> {
+ const [row] = await engine.executeRaw<{ lifetime: string }>(`SELECT e.page_lifetime::text AS lifetime FROM belief_events e
+ WHERE e.source_id = $1 AND e.slug = $2 AND e.subject_kind = 'page' AND e.page_lifetime IS NOT NULL AND e.recorded_at <= $3::timestamptz
+ ORDER BY e.id DESC LIMIT 1`, [sourceId, slug, at.toISOString()]);
+ if (!row) return null;
+ return await lifetimeSlugAt(engine, sourceId, row.lifetime, at) === slug ? row.lifetime : null;
+}
diff --git a/src/core/belief/ledger.ts b/src/core/belief/ledger.ts
index c68a131c8b..bab7ffca1f 100644
--- a/src/core/belief/ledger.ts
+++ b/src/core/belief/ledger.ts
@@ -27,7 +27,7 @@ export type BeliefNote =
| { kind: 'withdrawn'; factIds: number[] }
| { kind: 'superseded'; oldId: number; newId: number | null }
| { kind: 'purged'; table: 'facts' | 'takes'; ids: number[]; request: string }
- | { kind: 'transferred'; fromLifetime: string; table: 'facts' | 'takes'; ids: number[] };
+ | { kind: 'transferred'; fromSlug: string; table: 'facts' | 'takes' | 'links'; ids: number[] };
export interface BeliefBatchOptions {
sourceId: string;
@@ -61,6 +61,12 @@ export function noteBelief(note: BeliefNote): void {
store.getStore()?.notes.push(note);
}
+/** The enclosing batch's publication, source and stream slugs, or null outside a batch. */
+export function currentBeliefBatch(): { publicationId: string; sourceId: string; slugs: readonly string[] } | null {
+ const batch = store.getStore();
+ return batch ? { publicationId: batch.publicationId, sourceId: batch.opts.sourceId, slugs: batch.opts.slugs } : null;
+}
+
/** Coverage and purge probes for one source, in one read. */
export async function readLedgerSource(tx: Pick<BrainEngine, 'executeRaw'>, sourceId: string): Promise<{ incarnation: string; purgeEpoch: number; coverage: string | null; managed: boolean; purgesPossible: boolean } | null> {
const [row] = await tx.executeRaw<Record<string, unknown>>(`SELECT s.incarnation::text AS incarnation, s.purge_epoch,
@@ -177,6 +183,24 @@ const retractType = (kind: Subject['kind']) => kind === 'link_transition' ? 'lin
interface DiffContext {
opts: BeliefBatchOptions; batch: Batch; writerTier: string; lifetimeAt: (slug: string) => string | null; streamHash: (slug: string) => string;
cause: (extra?: Record<string, unknown>) => Record<string, unknown>; postSubjects: Subject[];
+ /** `kind:rowId` of each row a transfer note moved -> the subject it left and the lifetime of the page it left. */
+ transfers: Map<string, { from: Subject; fromLifetime: string | null }>;
+}
+
+const TRANSFER_KIND: Record<string, Subject['kind']> = { facts: 'fact', takes: 'take', links: 'link' };
+
+/** The pre-transaction subject of each row a `transferred` note moved, keyed `kind:rowId`. */
+function transferSources(notes: BeliefNote[], preSubjects: Subject[], lifetimeOfPreSlug: (slug: string) => string | null): DiffContext['transfers'] {
+ const out: DiffContext['transfers'] = new Map();
+ for (const note of notes) {
+ if (note.kind !== 'transferred') continue;
+ const kind = TRANSFER_KIND[note.table]!;
+ for (const id of note.ids) {
+ const from = preSubjects.find(s => s.kind === kind && s.stream === note.fromSlug && s.rowIds.includes(id));
+ if (from) out.set(`${kind}:${id}`, { from, fromLifetime: lifetimeOfPreSlug(note.fromSlug) });
+ }
+ }
+ return out;
}
/** Subject events of one stream side: asserted/retracted/revised, adoption, replacement links, retiering. */
@@ -196,8 +220,17 @@ function subjectDrafts(d: DiffContext, slug: string, before: Subject[], after: S
claimFp: s.claimFp, validFrom: s.validFrom, validUntil: s.validUntil,
cause: d.cause({ ...(s.rowNum != null ? { row: s.rowNum } : {}), label: s.label, ...extra }) });
};
- const removed = [...preMap].filter(([id]) => !postMap.has(id)).map(([, s]) => s);
+ const transferOf = (s: Subject) => s.rowIds.map(id => d.transfers.get(`${s.kind}:${id}`)).find(t => t && t.from.key !== s.key);
+ const removed = [...preMap].filter(([id]) => !postMap.has(id)).map(([, s]) => s)
+ .filter(s => !s.rowIds.length || !s.rowIds.every(id => d.transfers.has(`${s.kind}:${id}`)));
const fresh = [...postMap].filter(([id]) => !preMap.has(id)).map(([, s]) => s);
+ const transferred = new Set<Subject>();
+ for (const s of after) {
+ const t = transferOf(s);
+ if (!t) continue;
+ transferred.add(s);
+ draft(s, `${s.kind}.transferred`, s.value, t.from, { from_key: t.from.key, ...(t.fromLifetime ? { from_lifetime: t.fromLifetime } : {}) });
+ }
const adoptedFrom = new Map<Subject, Subject>();
for (const s of fresh) {
const parts = s.kind === 'fact' ? factKeySubject(s.key) : null;
@@ -222,6 +255,7 @@ function subjectDrafts(d: DiffContext, slug: string, before: Subject[], after: S
draft(r, type, null, r, { ...(successorKey ? { replaced_by: successorKey } : {}), ...(purgeRequest ? { purge_request: purgeRequest } : {}) });
}
for (const s of fresh) {
+ if (transferred.has(s)) continue;
const from = adoptedFrom.get(s);
if (from) { draft(s, 'fact.adopted', s.value, from, { from_key: from.key }); continue; }
const replaced = [...replacedBy].find(([, v]) => v === s)?.[0];
@@ -229,7 +263,7 @@ function subjectDrafts(d: DiffContext, slug: string, before: Subject[], after: S
}
for (const [id, s] of postMap) {
const prior = preMap.get(id);
- if (!prior) continue;
+ 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);
@@ -260,6 +294,9 @@ function pageDrafts(d: DiffContext, stream: Stream, lifetime: string, after: Sub
else if (p0!.deleted && !p1!.deleted) { emit('page.restored', { revision_before: p0!.revision, revision_after: p1!.revision }, p1!.tier); silenced = true; }
else if (p0!.revision !== p1!.revision) emit(d.opts.pageEventType ?? 'page.published', { revision_before: p0!.revision, revision_after: p1!.revision }, p1!.tier);
else if (p0!.visible !== p1!.visible) emit('page.visibility_changed', { visible: p1!.visible }, p1!.tier);
+ 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);
return silenced || (p0!.deleted && p1!.deleted);
}
@@ -287,7 +324,8 @@ export async function finalizeBeliefEvents(tx: BrainEngine, batch: Batch): Promi
const postPageAt = (slug: string) => streams.find(s => s.post?.slug === slug)?.post ?? null;
const lifetimeAt = (slug: string) => { const page = postPageAt(slug); return page ? lifetimes.get(page.id) ?? null : null; };
const streamHash = (slug: string) => { const page = postPageAt(slug); return stateHashOf(page, page ? lifetimes.get(page.id)! : null, postSubjects.filter(s => s.stream === slug)); };
- const d: DiffContext = { opts, batch, writerTier, lifetimeAt, streamHash, postSubjects,
+ const preLifetimeAt = (slug: string) => { const page = streams.find(s => s.pre?.slug === slug)?.pre; return page ? lifetimes.get(page.id) ?? null : null; };
+ const d: DiffContext = { opts, batch, writerTier, lifetimeAt, streamHash, postSubjects, transfers: transferSources(batch.notes, preSubjects, preLifetimeAt),
cause: (extra = {}) => ({ op: opts.op, ...(opts.publicationId ? { request: opts.publicationId } : {}), ...opts.cause, ...extra }) };
const drafts: BeliefEventDraft[] = [];
diff --git a/src/core/belief/retier.ts b/src/core/belief/retier.ts
new file mode 100644
index 0000000000..5d28455ccd
--- /dev/null
+++ b/src/core/belief/retier.ts
@@ -0,0 +1,154 @@
+/**
+ * Tier changes outside a publication diff (docs/designs/BELIEF_LEDGER.md
+ * sections 6.3 and 6.4). A publication or owner action whose tier change lies
+ * in its own streams is recorded by its batch's diff. Two writers change tiers
+ * of rows in streams they do not publish:
+ *
+ * - bulk runs (`trust backfill`, `claim-sources --relower`) append one summary
+ * `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.
+ *
+ * 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.
+ */
+import { randomUUID } from 'node:crypto';
+import type { BrainEngine } from '../engine.ts';
+import { appendBeliefEvents, type BeliefEventDraft } from './append.ts';
+import { eventKeyHex, pageKey, slugRef } from './keys.ts';
+import { coverageActive, currentBeliefBatch, readLedgerSource, stateHashOf } from './ledger.ts';
+import { resolveLifetimes } from './lifetimes.ts';
+import { readBeliefState, type RawPage } from './state.ts';
+import { keyedSubjects, pageNeeds } from './subjects.ts';
+
+export interface RetierRow { table: string; id: number; from: string | null; to: string }
+
+interface Resolved {
+ row: RetierRow; sourceId: string; incarnation: string; stream: string; page: RawPage | null; lifetime: string | null;
+ kind: 'page' | 'fact' | 'take'; key: string; visibility: string; claimFp: string | null; stateHash: string; writerTier: string | null;
+}
+
+const KIND: Record<string, 'page' | 'fact' | 'take'> = { pages: 'page', facts: 'fact', takes: 'take' };
+
+/** Each ledger subject among `rows` (timeline rows are not subjects), keyed as its stream's current state keys it; covered sources only. */
+async function resolveSubjects(tx: BrainEngine, rows: readonly RetierRow[]): Promise<Resolved[]> {
+ const subjects = rows.filter(r => KIND[r.table]);
+ if (!subjects.length) return [];
+ const ids = (table: string) => subjects.filter(r => r.table === table).map(r => r.id);
+ const located = await tx.executeRaw<{ t: string; id: number; source_id: string; slug: string | null }>(`
+ SELECT 'facts' AS t, id, source_id, COALESCE(source_markdown_slug, entity_slug) AS slug FROM facts WHERE id = ANY($1::bigint[])
+ UNION ALL SELECT 'takes', t.id, p.source_id, p.slug FROM takes t JOIN pages p ON p.id = t.page_id WHERE t.id = ANY($2::bigint[])
+ UNION ALL SELECT 'pages', id, source_id, slug FROM pages WHERE id = ANY($3::bigint[])`, [ids('facts'), ids('takes'), ids('pages')]);
+ const where = new Map(located.filter(r => r.slug).map(r => [`${r.t}:${Number(r.id)}`, { sourceId: r.source_id, slug: r.slug! }]));
+ const out: Resolved[] = [];
+ for (const sourceId of new Set([...where.values()].map(w => w.sourceId))) {
+ const source = await readLedgerSource(tx, sourceId);
+ if (!source || !coverageActive(source.coverage)) continue;
+ const mine = subjects.filter(r => where.get(`${r.table}:${r.id}`)?.sourceId === sourceId);
+ const streams = [...new Set(mine.map(r => where.get(`${r.table}:${r.id}`)!.slug))];
+ const state = await readBeliefState(tx, sourceId, streams);
+ const lifetimes = await resolveLifetimes(tx, pageNeeds(sourceId, source.incarnation, state));
+ const pagesBySlug = new Map(state.pages.map(p => [p.slug, p]));
+ const keyed = keyedSubjects({ incarnation: source.incarnation, lifetimes, pagesBySlug }, state,
+ id => state.pages.find(p => p.id === id)?.visible === false ? 'private' : 'world');
+ const hash = (slug: string) => { const page = pagesBySlug.get(slug) ?? null; return stateHashOf(page, page ? lifetimes.get(page.id)! : null, keyed.filter(s => s.stream === slug)); };
+ for (const row of mine) {
+ const stream = where.get(`${row.table}:${row.id}`)!.slug;
+ const page = pagesBySlug.get(stream) ?? null;
+ const lifetime = page ? lifetimes.get(page.id) ?? null : null;
+ const base = { row, sourceId, incarnation: source.incarnation, stream, page, lifetime, stateHash: hash(stream), writerTier: state.writerTier };
+ if (row.table === 'pages') {
+ if (page && lifetime) out.push({ ...base, kind: 'page', key: pageKey(lifetime), visibility: page.visible ? 'world' : 'private', claimFp: null });
+ continue;
+ }
+ const subject = keyed.find(s => s.kind === KIND[row.table] && s.rowIds.includes(row.id));
+ if (subject) out.push({ ...base, kind: subject.kind as 'fact' | 'take', key: subject.key, visibility: subject.visibility, claimFp: subject.claimFp });
+ }
+ }
+ return out;
+}
+
+const draftOf = (r: Resolved, cause: Record<string, unknown>): BeliefEventDraft => ({ sourceId: r.sourceId, incarnation: r.incarnation, lifetime: r.lifetime, slug: r.stream,
+ stream: r.stream, subjectKind: r.kind, subjectKey: r.key, eventType: 'trust.retiered', trustTier: r.row.to, writerTier: r.writerTier, tierBasis: 'row',
+ visibility: r.visibility, value: { from: r.row.from, to: r.row.to }, stateHash: r.stateHash, claimFp: r.claimFp, cause });
+
+/**
+ * Per-subject `trust.retiered` events for rows whose tier changed (derived
+ * propagation). Appended under the enclosing batch's publication when there is
+ * 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);
+ if (!resolved.length) return null;
+ const pub = currentBeliefBatch()?.publicationId ?? publicationId ?? randomUUID();
+ let appended = 0;
+ for (const sourceId of new Set(resolved.map(r => r.sourceId))) {
+ const source = (await readLedgerSource(tx, sourceId))!;
+ appended += await appendBeliefEvents(tx, resolved.filter(r => r.sourceId === sourceId).map(r => draftOf(r, cause)),
+ { publicationId: pub, origin: source.managed ? 'live' : 'unmanaged', purgesPossible: source.purgesPossible });
+ }
+ return appended ? pub : null;
+}
+
+/**
+ * A bulk run's tier changes in one transaction: one summary `trust.retiered`
+ * per source and stream (the stream page's key, or the slug form for a stream
+ * with no page) and one manifest row per changed subject. Returns the
+ * publication id when it appended.
+ */
+export async function appendBulkRetier(tx: BrainEngine, rows: readonly RetierRow[], op: string, publicationId = randomUUID()): Promise<string | null> {
+ const resolved = await resolveSubjects(tx, rows.filter(r => r.from !== r.to));
+ if (!resolved.length) return null;
+ let appended = 0;
+ for (const sourceId of new Set(resolved.map(r => r.sourceId))) {
+ const source = (await readLedgerSource(tx, sourceId))!;
+ const mine = resolved.filter(r => r.sourceId === sourceId);
+ const summaries = [...new Set(mine.map(r => r.stream))].map(stream => {
+ const members = mine.filter(r => r.stream === stream);
+ const first = members[0]!;
+ const to: Record<string, number> = {};
+ for (const m of members) to[m.row.to] = (to[m.row.to] ?? 0) + 1;
+ const draft: BeliefEventDraft = { sourceId, incarnation: first.incarnation, lifetime: first.lifetime, slug: stream, stream, subjectKind: 'page',
+ subjectKey: first.lifetime ? pageKey(first.lifetime) : JSON.stringify(['p', slugRef(first.incarnation, stream)]), eventType: 'trust.retiered',
+ trustTier: first.page?.tier ?? 'unknown', writerTier: first.writerTier, tierBasis: first.page ? 'row' : 'unknown',
+ visibility: first.page && !first.page.visible ? 'private' : 'world', value: { summary: true, subjects: members.length, to }, stateHash: first.stateHash,
+ cause: { op, manifest: true } };
+ return { draft, members };
+ });
+ appended += await appendBeliefEvents(tx, summaries.map(s => s.draft), { publicationId, origin: source.managed ? 'live' : 'unmanaged', purgesPossible: source.purgesPossible });
+ const manifest = summaries.flatMap(({ draft, members }) => members.map(m => ({ event_key: eventKeyHex(publicationId, draft.subjectKey, draft.eventType),
+ subject_kind: m.kind, subject_key: m.key, from_tier: m.row.from, to_tier: m.row.to })));
+ await tx.executeRaw(`INSERT INTO belief_retier_manifest (summary_event, source_id, subject_kind, subject_key, from_tier, to_tier)
+ SELECT e.id, $1, m.subject_kind, m.subject_key, m.from_tier, m.to_tier
+ FROM jsonb_to_recordset($2::text::jsonb) AS m(event_key text, subject_kind text, subject_key text, from_tier text, to_tier text)
+ JOIN belief_events e ON e.event_key = decode(m.event_key, 'hex')
+ ON CONFLICT DO NOTHING`, [sourceId, JSON.stringify(manifest)]);
+ }
+ return appended ? publicationId : null;
+}
+
+/**
+ * The event that recorded each input's tier change, for a propagation's cause:
+ * the enclosing batch's own `trust.retiered` when the input lies in its
+ * streams (its key is derived, it is appended at finalization), else the
+ * newest per-subject event or bulk summary naming the input's key.
+ */
+export async function retierInputCauses(tx: BrainEngine, inputs: readonly { table: string; id: number }[]): Promise<Array<{ subject_key: string; event_key: string | null }>> {
+ const resolved = await resolveSubjects(tx, inputs.map(i => ({ ...i, from: null, to: '' })));
+ const batch = currentBeliefBatch();
+ const out: Array<{ subject_key: string; event_key: string | null }> = [];
+ for (const r of resolved) {
+ if (batch && batch.sourceId === r.sourceId && batch.slugs.includes(r.stream)) {
+ out.push({ subject_key: r.key, event_key: eventKeyHex(batch.publicationId, r.key, 'trust.retiered') });
+ continue;
+ }
+ const [row] = await tx.executeRaw<{ key: string }>(`SELECT encode(k.event_key, 'hex') AS key FROM (
+ SELECT e.id, e.event_key FROM belief_events e WHERE e.source_id = $1 AND e.subject_key = $2 AND e.event_type = 'trust.retiered'
+ UNION ALL SELECT e.id, e.event_key FROM belief_retier_manifest m JOIN belief_events e ON e.id = m.summary_event
+ WHERE m.source_id = $1 AND m.subject_key = $2) k ORDER BY k.id DESC LIMIT 1`, [r.sourceId, r.key]);
+ out.push({ subject_key: r.key, event_key: row?.key ?? null });
+ }
+ return out;
+}
diff --git a/src/core/belief/state.ts b/src/core/belief/state.ts
index 6fbee46c8d..a2a8aa2229 100644
--- a/src/core/belief/state.ts
+++ b/src/core/belief/state.ts
@@ -103,7 +103,8 @@ export async function readBeliefState(tx: BrainEngine, sourceId: string, slugs:
transitions: transitions.map(r => ({ id: Number(r.id), from: endpoint(r, 'f')!, to: endpoint(r, 't')!, origin: endpoint(r, 'o'),
link_type: String(r.link_type), kind: String(r.kind), occurred_on: String(r.occurred_on), date_precision: String(r.date_precision),
producer: String(r.producer), line_hash: String(r.line_hash) })),
- writerTier: (pageRows[0]?.writer_tier as string | undefined) || null,
+ writerTier: ((pageRows[0] ?? (await tx.executeRaw<Record<string, unknown>>(`SELECT current_setting('gbrain.write_trust_tier', true) AS writer_tier`))[0])
+ ?.writer_tier as string | undefined) || null,
};
}
diff --git a/src/core/belief/subjects.ts b/src/core/belief/subjects.ts
index 55c2220664..41e2d01b15 100644
--- a/src/core/belief/subjects.ts
+++ b/src/core/belief/subjects.ts
@@ -64,7 +64,7 @@ export function keyedSubjects(ctx: KeyContext, state: RawState, pageVisibility:
const head = rows[0]!;
const value = factValue(head, entity, rows.length);
out.push({ kind: 'fact', key, stream, value, vhash: valueHash(value), tier: head.tier, visibility: head.visibility, rowIds: rows.map(r => r.id),
- rowNum: head.row_num, dbOnly: head.sms == null, claimFp: head.fp, validFrom: head.valid_from, validUntil: head.valid_until,
+ rowNum: head.row_num, dbOnly: head.sms == null || (head.dimension != null && head.row_num == null), claimFp: head.fp, validFrom: head.valid_from, validUntil: head.valid_until,
label: { subject_slug: stream, ...(head.entity_slug && head.entity_slug !== stream ? { entity_slug: head.entity_slug } : {}) } });
}
const pagesById = new Map(state.pages.map(p => [p.id, p]));
diff --git a/src/core/belief/writers.ts b/src/core/belief/writers.ts
new file mode 100644
index 0000000000..d851074baa
--- /dev/null
+++ b/src/core/belief/writers.ts
@@ -0,0 +1,69 @@
+/**
+ * Writer-side helpers of the finalization contract (docs/designs/BELIEF_LEDGER.md
+ * sections 5.1 and 6.2) for transactions outside the publication paths: a
+ * refusal that files its proposal in its own transaction, a database-only
+ * coordinated write, an owner action. Each locks its streams' page keys first
+ * (so the batch's reads and appends happen under them), runs its writes in a
+ * belief batch and writes the commit mark after commit.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { validateSlug } from '../utils.ts';
+import { normalizeDimension } from '../chronicle/ontology.ts';
+import { markBeliefCommits } from './append.ts';
+import { withBeliefBatch, type BeliefBatchOptions } from './ledger.ts';
+
+const validSlug = (slug: string | null | undefined): slug is string => {
+ if (!slug) return false;
+ try { validateSlug(slug); return true; } catch { return false; }
+};
+
+/** The ledger stream slug of each row: a fact's fence page else its entity, a take's page, a page's own slug. */
+export async function beliefStreamSlugs(tx: Pick<BrainEngine, 'executeRaw'>, table: 'facts' | 'takes' | 'pages', ids: readonly number[]): Promise<string[]> {
+ if (!ids.length) return [];
+ const sql = table === 'facts' ? 'SELECT COALESCE(source_markdown_slug, entity_slug) AS slug FROM facts WHERE id = ANY($1::bigint[])'
+ : table === 'takes' ? 'SELECT p.slug FROM takes t JOIN pages p ON p.id = t.page_id WHERE t.id = ANY($1::bigint[])'
+ : 'SELECT slug FROM pages WHERE id = ANY($1::int[])';
+ const rows = await tx.executeRaw<{ slug: string | null }>(sql, [[...ids]]);
+ return [...new Set(rows.map(r => r.slug).filter(validSlug))].sort();
+}
+
+/**
+ * The streams an ontology observation can change: the entity, the new row's
+ * provenance (`source_markdown_slug` is the observation's `source`) and the
+ * provenance of each open stint it may close. Read before the write's lock;
+ * every ontology writer also holds the entity's key, so the open stints do not
+ * change between this read and the write.
+ */
+export async function ontologyStreamSlugs(tx: Pick<BrainEngine, 'executeRaw'>, sourceId: string, entity: string, dimension: string, source: string): Promise<string[]> {
+ const open = await tx.executeRaw<{ slug: string | null }>(`SELECT DISTINCT source_markdown_slug AS slug FROM facts
+ WHERE source_id = $1 AND entity_slug = $2 AND dimension = $3 AND expired_at IS NULL AND valid_until IS NULL`, [sourceId, entity, normalizeDimension(dimension)]);
+ return [...new Set([entity, source, ...open.map(r => r.slug)].filter(validSlug))].sort();
+}
+
+/**
+ * Locks `opts.slugs` and runs `fn` in a belief batch inside `tx`, which must not
+ * hold page keys yet (the keys are taken in lockPageKeys' sorted order).
+ */
+export async function lockedBeliefBatch<T>(tx: BrainEngine, opts: BeliefBatchOptions, fn: () => Promise<T>): Promise<T> {
+ const slugs = [...new Set(opts.slugs.filter(validSlug))];
+ await tx.lockPageKeys(slugs.map(slug => ({ sourceId: opts.sourceId, slug })));
+ return withBeliefBatch(tx, { ...opts, slugs }, fn);
+}
+
+/**
+ * A transaction of its own whose writes the ledger records: `fn` runs in a
+ * locked batch, and the commit mark is written after commit. `wrap` sets the
+ * transaction's attribution around the batch, so the batch reads the writer's
+ * tier.
+ */
+export async function beliefTransaction<T>(engine: BrainEngine, opts: Omit<BeliefBatchOptions, 'report' | 'publicationId'> & { publicationId: string },
+ fn: (tx: BrainEngine) => Promise<T>, wrap: (tx: BrainEngine, run: () => Promise<T>) => Promise<T> = (_tx, run) => run()): Promise<T> {
+ const report = { appended: 0 };
+ const result = await engine.transaction(async tx => {
+ const slugs = [...new Set(opts.slugs.filter(validSlug))];
+ await tx.lockPageKeys(slugs.map(slug => ({ sourceId: opts.sourceId, slug })));
+ return wrap(tx, () => withBeliefBatch(tx, { ...opts, slugs, report }, () => fn(tx)));
+ });
+ if (report.appended) await markBeliefCommits(engine, [opts.publicationId]).catch(() => undefined);
+ return result;
+}
diff --git a/src/core/cycle/phantom-redirect-managed.ts b/src/core/cycle/phantom-redirect-managed.ts
index e4d7febc88..d729739b86 100644
--- a/src/core/cycle/phantom-redirect-managed.ts
+++ b/src/core/cycle/phantom-redirect-managed.ts
@@ -26,6 +26,7 @@ import { serializePageToMarkdown } from '../markdown.ts';
import { logPhantomEvent } from '../facts/phantom-audit.ts';
import { MOVE_WITHDRAWAL_SUBJECT_SQL } from '../facts/withdrawal-schema.ts';
import { recordRenameAlias } from '../page-state/rename-alias.ts';
+import { noteBelief } from '../belief/ledger.ts';
import { preparePageMutation } from '../persistence/page-prepare.ts';
import { maintenancePreflight, submitMaintenanceIntent } from '../persistence/prepared-maintenance.ts';
import { mergePhantomFenceRows, mergePhantomLinks, movePhantomFacts, phantomHasResidue, type RedirectResult } from './phantom-redirect.ts';
@@ -92,10 +93,18 @@ export async function preparePhantomMerge(engine: BrainEngine, row: WriteRequest
// Withdrawals move first so the trigger honors them as the rows take the
// canonical subject; moved rows then match the published fence rows.
await tx.executeRaw(MOVE_WITHDRAWAL_SUBJECT_SQL, [row.source_id, phantomSlug, row.slug]);
+ const phantomLinks = await tx.executeRaw<{ id: number }>('SELECT id FROM links WHERE from_page_id = $1 AND origin_page_id IS NULL', [phantomId]);
+ const phantomFacts = await tx.executeRaw<{ id: number }>('SELECT id FROM facts WHERE source_id = $1 AND source_markdown_slug = $2 AND expired_at IS NULL', [row.source_id, phantomSlug]);
const moved = await movePhantomFacts(tx, row.source_id, phantomSlug, row.slug, rowMap);
const outcome = await page.apply(tx);
await mergePhantomLinks(tx, phantomId, Number(row.page_id));
await recordRenameAlias(tx, row.source_id, phantomSlug, row.slug);
+ // W1 #6783 §3: a merge is not a rename; each assertion that moved to the canonical page is one *.transferred from the phantom's lifetime.
+ const movedFacts = await tx.executeRaw<{ id: number }>('SELECT id FROM facts WHERE id = ANY($1::bigint[]) AND source_markdown_slug = $2 AND expired_at IS NULL',
+ [phantomFacts.map(f => Number(f.id)), row.slug]);
+ const movedLinks = await tx.executeRaw<{ id: number }>('SELECT id FROM links WHERE id = ANY($1::int[]) AND from_page_id = $2', [phantomLinks.map(l => Number(l.id)), Number(row.page_id)]);
+ noteBelief({ kind: 'transferred', fromSlug: phantomSlug, table: 'facts', ids: movedFacts.map(f => Number(f.id)) });
+ noteBelief({ kind: 'transferred', fromSlug: phantomSlug, table: 'links', ids: movedLinks.map(l => Number(l.id)) });
return { ...outcome, facts_moved: moved };
} };
}
diff --git a/src/core/facts/proposal-supersede.ts b/src/core/facts/proposal-supersede.ts
index 3195bd928e..d21ae1f086 100644
--- a/src/core/facts/proposal-supersede.ts
+++ b/src/core/facts/proposal-supersede.ts
@@ -35,6 +35,8 @@ import { maintenanceTransaction } from '../persistence/attribution.ts';
import { withTrustKeep } from '../persistence/context.ts';
import type { PreparedMutation } from '../persistence/coordinator.ts';
import type { WriteRequest } from '../persistence/model.ts';
+import { noteBelief } from '../belief/ledger.ts';
+import { beliefStreamSlugs, lockedBeliefBatch } from '../belief/writers.ts';
export const DECIDE_PROPOSAL_OPERATION = 'decide_proposal';
@@ -171,6 +173,7 @@ async function expireOld(tx: BrainEngine, proposal: PairProposal): Promise<void>
WHERE id = $1 AND source_id = $2 AND expired_at IS NULL RETURNING id`,
[proposal.old_fact_id, proposal.source_id, proposal.new_fact_id]);
if (rows.length !== 1) throw new ProposalConflictError('the old fact changed during accept');
+ noteBelief({ kind: 'superseded', oldId: proposal.old_fact_id, newId: proposal.new_fact_id });
}
/** Record the after state (read back inside the transaction) and move the proposal to accepted. */
@@ -201,6 +204,12 @@ function parseStates(p: PairProposal): { before: SupersedeState; after: Supersed
// Unmanaged path
// ---------------------------------------------------------------------------
+/** W1 #6783 §6.4: an unmanaged accept or undo runs in a belief batch over both facts' streams (the managed path's publication has its own). */
+async function recordedPair(tx: BrainEngine, proposal: PairProposal, action: ProposalAction, fn: () => Promise<void>): Promise<void> {
+ const slugs = await beliefStreamSlugs(tx, 'facts', [proposal.old_fact_id, proposal.new_fact_id]);
+ await lockedBeliefBatch(tx, { sourceId: proposal.source_id, slugs, op: DECIDE_PROPOSAL_OPERATION, remote: false, cause: { proposal: proposal.id, action } }, fn);
+}
+
function publishFile(filePath: string, body: string): void {
const tmp = `${filePath}.tmp`;
assertSourceFilesystemActive();
@@ -254,12 +263,12 @@ async function acceptUnmanaged(engine: BrainEngine, proposal: PairProposal, stor
let published = false;
try {
// The strike edits a managed fence without authoring the page: it keeps its trust tier (#5575 ENG-1).
- await maintenanceTransaction(engine, (tx) => withTrustKeep(tx, ['pages'], async () => {
+ await maintenanceTransaction(engine, (tx) => withTrustKeep(tx, ['pages'], async () => recordedPair(tx, fresh, 'accept', async () => {
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, store);
if (plan && fileBody !== null) { publishFile(filePath!, plan.body); published = true; }
- }));
+ })));
} catch (err) {
if (published) writeFileSync(filePath!, fileBody!, 'utf-8');
throw err;
@@ -291,11 +300,11 @@ async function undoUnmanaged(engine: BrainEngine, proposal: PairProposal, store:
}
let published = false;
try {
- await maintenanceTransaction(engine, (tx) => withTrustKeep(tx, ['pages'], async () => {
+ await maintenanceTransaction(engine, (tx) => withTrustKeep(tx, ['pages'], async () => recordedPair(tx, fresh, 'undo', async () => {
if (plan) await mirrorBody(tx, before.fence!.slug, fresh.source_id, plan.body, fileBody !== null);
await applyUndoDb(tx, fresh, before, after, store);
if (plan && fileBody !== null) { publishFile(filePath!, plan.body); published = true; }
- }));
+ })));
} catch (err) {
if (published) writeFileSync(filePath!, fileBody!, 'utf-8');
throw err;
@@ -328,6 +337,9 @@ export async function prepareProposalMutation(engine: BrainEngine, row: WriteReq
if (!proposal || proposal.source_id !== row.source_id) return done({ id, action, status: 'refused', reason: 'not_found' });
if (proposal.status !== (action === 'accept' ? 'pending' : 'accepted')) return done({ id, action, status: 'refused', reason: proposal.status });
const [oldF, newF] = await Promise.all([loadPairFact(engine, proposal.old_fact_id), loadPairFact(engine, proposal.new_fact_id)]);
+ // The belief ledger records the new fact's tier change in its own stream, so that page key is held too.
+ const newStream = newF?.source_markdown_slug ?? newF?.entity_slug ?? null;
+ const pairKeys = newStream && newStream !== row.slug ? { additionalPageKeys: [{ sourceId: row.source_id, slug: newStream }] } : {};
const unchanged = async (tx: BrainEngine) => {
const current = await store.get(tx, id, true);
const [o, n] = await Promise.all([loadPairFact(tx, proposal.old_fact_id, true), loadPairFact(tx, proposal.new_fact_id, true)]);
@@ -357,7 +369,7 @@ export async function prepareProposalMutation(engine: BrainEngine, row: WriteReq
const page = plan ? await pageFor(plan.body) : undefined;
const fence = (r: ParsedFact, revision: string | null): FenceState => ({ slug: row.slug, row_num: oldF!.row_num!, row: r, page_revision: revision, file: page?.file !== undefined });
const before: SupersedeState = { old: factFields(oldF!), new: factFields(newF!), fence: plan ? fence(plan.before, observedRevision) : null };
- return { observedRevision, file: page?.file, validate: async (tx) => { await unchanged(tx); await page?.validate?.(tx); }, apply: async (tx) => {
+ return { observedRevision, file: page?.file, ...pairKeys, validate: async (tx) => { await unchanged(tx); await page?.validate?.(tx); }, apply: async (tx) => {
// The page projection re-stamps the struck row's expiry from the fence, so the after state is read once it ran.
await expireOld(tx, proposal);
await page?.apply(tx);
@@ -377,7 +389,7 @@ export async function prepareProposalMutation(engine: BrainEngine, row: WriteReq
if (planned === 'changed') return done({ id, action, status: 'refused', reason: 'fence_changed' });
page = await pageFor(planned.body);
}
- return { observedRevision, file: page?.file, validate: async (tx) => { await unchanged(tx); await page?.validate?.(tx); }, apply: async (tx) => {
+ return { observedRevision, file: page?.file, ...pairKeys, validate: async (tx) => { await unchanged(tx); await page?.validate?.(tx); }, apply: async (tx) => {
await page?.apply(tx);
await applyUndoDb(tx, proposal, before, after, store);
return { id, action, status: 'undone' };
diff --git a/src/core/facts/withdrawal.ts b/src/core/facts/withdrawal.ts
index 7ac588c4ac..1865950bdf 100644
--- a/src/core/facts/withdrawal.ts
+++ b/src/core/facts/withdrawal.ts
@@ -6,6 +6,9 @@ import { withdrawnFact, withdrawalFenceBlocks } from './withdrawal-overlay.ts';
import { ambiguousFenceClaims, discoverWithdrawalTargets, withdrawalDiscoveryFailure } from './withdrawal-discovery.ts';
import { dropPurgedFenceRows } from './purge-overlay.ts';
import { privateProvenanceFilterFragment } from '../search/private-visibility.ts';
+import { coverageActive, noteBelief, readLedgerSource, withBeliefBatch } from '../belief/ledger.ts';
+import { createPageVersion } from '../page-state/versions.ts';
+import { validateSlug } from '../utils.ts';
export interface WithdrawalCommit {
withdrawn: boolean;
@@ -48,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 } = {},
+ opts: { requestId?: 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,
@@ -66,42 +69,60 @@ export async function recordFactWithdrawal(
WHERE source_id=$1 AND visibility=$2 AND fact_hash IN ($3,gbrain_fact_fingerprint_v1($5)) AND (subject='*' OR subject=$4) LIMIT 1`,
[sourceId, visibility, fact_hash, subject, fact]);
const affected = existing.length ? [] : await discoverWithdrawalTargets(tx, sourceId, [{ visibility, fact_hash, subject, claim: fact }]).catch(withdrawalDiscoveryFailure);
- await tx.lockPageKeys(affected.map(({ slug }) => ({ sourceId, slug })));
+ // The belief ledger's streams of the facts this withdrawal expires (fence pages and database-only subjects), locked with the pages.
+ const streams = (await tx.executeRaw<{ slug: string }>(`SELECT DISTINCT COALESCE(source_markdown_slug, entity_slug) AS slug FROM facts
+ WHERE source_id=$1 AND visibility=$2 AND gbrain_fact_fingerprint(fact)=$3 AND ($4='*' OR entity_slug=$4) AND expired_at IS NULL
+ AND COALESCE(source_markdown_slug, entity_slug) IS NOT NULL`, [sourceId, visibility, fact_hash, subject]))
+ .map(r => r.slug).filter(slug => { try { validateSlug(slug); return true; } catch { return false; } });
+ const slugs = [...new Set([...affected.map(page => page.slug), ...streams])];
+ await tx.lockPageKeys(slugs.map(slug => ({ sourceId, slug })));
const rows = await tx.executeRaw<{ visibility: string; fact: string; subject: string }>(
`SELECT visibility,fact,COALESCE(entity_slug,'*') AS subject FROM facts WHERE id=$1 AND source_id=$2
AND ($3::boolean=false OR visibility='world')${opts.excludePrivate ? ` AND ${privateProvenanceFilterFragment('facts')}` : ''} FOR UPDATE`, [id, sourceId, worldOnly]);
if (!rows.length) return { withdrawn: false, pages: [] };
const row = rows[0];
- // Scoped to the forgotten row's entity: the same claim about another
- // entity stays active and rememberable. A subjectless fact withdraws
- // source-wide ('*').
- const inserted = await tx.executeRaw(`INSERT INTO fact_withdrawals(source_id,visibility,subject,fact_hash)
- VALUES ($1,$2,$4,gbrain_fact_fingerprint($3)) ON CONFLICT DO NOTHING RETURNING fact_hash`, [sourceId,row.visibility,row.fact,row.subject]);
- await tx.executeRaw(`UPDATE facts SET expired_at=now(),valid_until=LEAST(COALESCE(valid_until,now()),now())
- WHERE source_id=$1 AND visibility=$2 AND gbrain_fact_fingerprint(fact)=gbrain_fact_fingerprint($3)
- AND ($4='*' OR entity_slug=$4) AND expired_at IS NULL`, [sourceId,row.visibility,row.fact,row.subject]);
- if (!inserted.length) return { withdrawn: false, pages: [] };
- // Overnight semantic review (decide review lane): queued with the ledger row so a late commit is never skipped.
- // Not queued when the caller opted out (`semantic_review: false`, also used by review-accepted withdrawals).
- if (opts.semanticReview !== false && reviewWithdrawOn(await tx.getConfig(REVIEW_WITHDRAW_KEY))) {
- await tx.executeRaw(`INSERT INTO decide_review_queue(kind,source_id,a_ref) VALUES ('withdraw',$1,$2) ON CONFLICT DO NOTHING`, [sourceId, String(id)]);
+ const ledger = affected.length ? await readLedgerSource(tx, sourceId) : null;
+ // W1 (docs/designs/BELIEF_LEDGER.md section 10): the pre-withdrawal body stays readable at its revision.
+ if (ledger && coverageActive(ledger.coverage)) {
+ for (const page of affected) {
+ const preimage = await tx.readPageSnapshot(page.slug, { sourceId, includeDeleted: true });
+ if (preimage) await createPageVersion(tx, page.slug, sourceId, preimage);
+ }
}
- // Logical revision and projection invalidation commit with the withdrawal.
- // The revision trigger queues durable rebuild work even for unmanaged calls.
- const pages = affected.length ? await tx.executeRaw<{ id: number; slug: string; knowledge_revision: string }>(
- `UPDATE pages SET knowledge_revision=gen_random_uuid(),text_projection_revision=NULL,embedding_signature=NULL
- WHERE source_id=$1 AND slug=ANY($2::text[]) RETURNING id,slug,knowledge_revision`, [sourceId, affected.map(page => page.slug)]) : [];
- if (pages.length) await tx.executeRaw('DELETE FROM content_chunks WHERE page_id=ANY($1::integer[])', [pages.map(page => page.id)]);
- if (opts.requestId) {
- await tx.executeRaw(`INSERT INTO persistence_effects(request_id,kind,data,source_id,source_incarnation,worktree_id)
- SELECT $1::uuid,k.kind,$3::text::jsonb,s.id,s.incarnation,b.worktree_id
- FROM sources s LEFT JOIN persistence_source_bindings b ON b.source_id=s.id AND b.source_incarnation=s.incarnation
- CROSS JOIN (VALUES ('withdrawal-mirror'),('git'),('embedding')) AS k(kind)
- WHERE s.id=$2 ON CONFLICT(request_id,kind) DO NOTHING`, [opts.requestId, sourceId, JSON.stringify({ version: 2, targets: pages.map(page => ({ slug: page.slug, page_id: page.id, revision: page.knowledge_revision })).sort((a, b) => a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0) })]);
- }
- const committed = pages.map(page => ({ sourceId, slug: page.slug, revision: page.knowledge_revision }));
- for (const invalidate of withdrawalInvalidations) await invalidate(tx, { sourceId, factId: id, subject: row.subject, pages: committed });
- return { withdrawn: true, pages: committed };
+ return withBeliefBatch(tx, { sourceId, slugs, publicationId: opts.requestId ?? 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
+ // source-wide ('*').
+ const inserted = await tx.executeRaw(`INSERT INTO fact_withdrawals(source_id,visibility,subject,fact_hash)
+ VALUES ($1,$2,$4,gbrain_fact_fingerprint($3)) ON CONFLICT DO NOTHING RETURNING fact_hash`, [sourceId,row.visibility,row.fact,row.subject]);
+ const expired = await tx.executeRaw<{ id: number }>(`UPDATE facts SET expired_at=now(),valid_until=LEAST(COALESCE(valid_until,now()),now())
+ WHERE source_id=$1 AND visibility=$2 AND gbrain_fact_fingerprint(fact)=gbrain_fact_fingerprint($3)
+ AND ($4='*' OR entity_slug=$4) AND expired_at IS NULL RETURNING id`, [sourceId,row.visibility,row.fact,row.subject]);
+ noteBelief({ kind: 'withdrawn', factIds: expired.map(r => Number(r.id)) });
+ if (!inserted.length) return { withdrawn: false, pages: [] };
+ // Overnight semantic review (decide review lane): queued with the ledger row so a late commit is never skipped.
+ // Not queued when the caller opted out (`semantic_review: false`, also used by review-accepted withdrawals).
+ if (opts.semanticReview !== false && reviewWithdrawOn(await tx.getConfig(REVIEW_WITHDRAW_KEY))) {
+ await tx.executeRaw(`INSERT INTO decide_review_queue(kind,source_id,a_ref) VALUES ('withdraw',$1,$2) ON CONFLICT DO NOTHING`, [sourceId, String(id)]);
+ }
+ // Logical revision and projection invalidation commit with the withdrawal.
+ // The revision trigger queues durable rebuild work even for unmanaged calls.
+ const pages = affected.length ? await tx.executeRaw<{ id: number; slug: string; knowledge_revision: string }>(
+ `UPDATE pages SET knowledge_revision=gen_random_uuid(),text_projection_revision=NULL,embedding_signature=NULL
+ WHERE source_id=$1 AND slug=ANY($2::text[]) RETURNING id,slug,knowledge_revision`, [sourceId, affected.map(page => page.slug)]) : [];
+ if (pages.length) await tx.executeRaw('DELETE FROM content_chunks WHERE page_id=ANY($1::integer[])', [pages.map(page => page.id)]);
+ if (opts.requestId) {
+ await tx.executeRaw(`INSERT INTO persistence_effects(request_id,kind,data,source_id,source_incarnation,worktree_id)
+ SELECT $1::uuid,k.kind,$3::text::jsonb,s.id,s.incarnation,b.worktree_id
+ FROM sources s LEFT JOIN persistence_source_bindings b ON b.source_id=s.id AND b.source_incarnation=s.incarnation
+ CROSS JOIN (VALUES ('withdrawal-mirror'),('git'),('embedding')) AS k(kind)
+ WHERE s.id=$2 ON CONFLICT(request_id,kind) DO NOTHING`, [opts.requestId, sourceId, JSON.stringify({ version: 2, targets: pages.map(page => ({ slug: page.slug, page_id: page.id, revision: page.knowledge_revision })).sort((a, b) => a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0) })]);
+ }
+ const committed = pages.map(page => ({ sourceId, slug: page.slug, revision: page.knowledge_revision }));
+ for (const invalidate of withdrawalInvalidations) await invalidate(tx, { sourceId, factId: id, subject: row.subject, pages: committed });
+ return { withdrawn: true, pages: committed };
+ });
});
}
diff --git a/src/core/ops/chronicle.ts b/src/core/ops/chronicle.ts
index 60aed64545..573dbf337a 100644
--- a/src/core/ops/chronicle.ts
+++ b/src/core/ops/chronicle.ts
@@ -210,14 +210,22 @@ const ontology_propose: Operation = {
// write serialized on the entity's page key; unmanaged brains write directly.
// #5575: an agent observation never closes a more trusted stint; it is stored contested for the owner (A5).
const { ontologyWriteTrust, contestOntologySupersession } = await import('../trust/supersede-handlers.ts');
- const { maintenanceTransaction } = await import('../persistence/attribution.ts');
const trust = ontologyWriteTrust(ctx);
const guarded = async (engine: typeof ctx.engine, sourceId: string | undefined) => {
const result = await merge(engine, sourceId);
return { ...result, ...await contestOntologySupersession(engine, sourceId ?? 'default', entitySlug, String(p.dimension), result) };
};
- const managed = await coordinatedDatabaseWrite(ctx, 'ontology_propose', entitySlug, [entitySlug], guarded, trust);
- return managed ? managed.value : maintenanceTransaction(ctx.engine, tx => guarded(tx, ctx.sourceId), trust);
+ // W1 #6783 §5.1: the observation's rows live in its provenance's stream and in the closed stint's, so those keys are held too.
+ const { ontologyStreamSlugs, beliefTransaction } = await import('../belief/writers.ts');
+ const { withWriteAttribution } = await import('../persistence/context.ts');
+ const { maintenanceAttribution } = await import('../persistence/attribution.ts');
+ const sourceId = ctx.sourceId ?? 'default';
+ const slugs = await ontologyStreamSlugs(ctx.engine, sourceId, entitySlug, String(p.dimension), typeof p.source === 'string' && p.source ? p.source : 'manual');
+ const managed = await coordinatedDatabaseWrite(ctx, 'ontology_propose', entitySlug, slugs, guarded, trust);
+ if (managed) return managed.value;
+ const attribution = { ...await maintenanceAttribution(ctx.engine), trust };
+ return beliefTransaction(ctx.engine, { sourceId, slugs, publicationId: crypto.randomUUID(), op: 'ontology_propose', remote: ctx.remote !== false },
+ tx => guarded(tx, ctx.sourceId), (tx, run) => withWriteAttribution(tx, attribution, run));
},
cliHints: { name: 'ontology-add', positional: ['entity', 'dimension', 'value'] },
};
diff --git a/src/core/page-state/materialize.ts b/src/core/page-state/materialize.ts
index 0f451a8f4c..10d8c73372 100644
--- a/src/core/page-state/materialize.ts
+++ b/src/core/page-state/materialize.ts
@@ -4,6 +4,8 @@ import { assertInlineBody } from '../page-body/page-shape.ts';
import { assertPageRevision, type PageSnapshot } from './types.ts';
import { withCoordinatedWrite } from '../persistence/context.ts';
import { maintenanceAttribution } from '../persistence/attribution.ts';
+import { coverageActive, readLedgerSource, withBeliefBatch } from '../belief/ledger.ts';
+import { createPageVersion } from './versions.ts';
/** Persist an effective withdrawal overlay without inventing a second logical edit. */
export async function materializePageSnapshot(engine: BrainEngine, snapshot: PageSnapshot): Promise<void> {
@@ -21,9 +23,16 @@ export async function materializePageSnapshot(engine: BrainEngine, snapshot: Pag
// Only database-derived canonical bytes may use the bypass. Callers cannot
// smuggle arbitrary content in the supplied snapshot at an old revision.
const page = current.page;
- await withCoordinatedWrite(tx, [sourceId], () => tx.executeRaw(`UPDATE pages SET compiled_truth=$1,timeline=$2,content_hash=$3
+ // W1 (docs/designs/BELIEF_LEDGER.md section 10): the body this rewrite replaces stays readable at its revision, and the ledger records the view change.
+ const ledger = await readLedgerSource(tx, sourceId);
+ const stored = ledger && coverageActive(ledger.coverage)
+ ? (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' },
+ () => 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, contentHash({ ...page, tags: current.tags }), page.id, current.revision]), attribution);
+ [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 ?? '']);
});
}
diff --git a/src/core/persistence/database-write.ts b/src/core/persistence/database-write.ts
index 8fff2ee3f6..dd6a270997 100644
--- a/src/core/persistence/database-write.ts
+++ b/src/core/persistence/database-write.ts
@@ -1,4 +1,7 @@
+import { randomUUID } from 'node:crypto';
import type { BrainEngine } from '../engine.ts';
+import { withBeliefBatch } from '../belief/ledger.ts';
+import { markBeliefCommits } from '../belief/append.ts';
import { opError, type OperationContext } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
import { assertPersistenceAccepting } from './service.ts';
@@ -32,6 +35,8 @@ export async function coordinatedDatabaseWrite<T>(ctx: OperationContext, operati
}
await initializeLocalPersistence(ctx);
const authority = await submissionAuthority(ctx, operation, sourceId, source.incarnation, authoritySlug);
+ const publicationId = randomUUID();
+ const report = { appended: 0 };
const value = await ctx.engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], async () => {
const [current] = await tx.executeRaw<{ incarnation: string; archived: boolean }>(
'SELECT incarnation,archived FROM sources WHERE id=$1 FOR SHARE', [sourceId]);
@@ -42,7 +47,9 @@ export async function coordinatedDatabaseWrite<T>(ctx: OperationContext, operati
}
await authorizeWrite(tx, authority, operation, authoritySlug, true);
await tx.lockPageKeys(lockSlugs.map(slug => ({ sourceId, slug })));
- return write(tx, sourceId);
+ // W1 finalization contract (docs/designs/BELIEF_LEDGER.md 5.1): the database-only rows this write changes are recorded under the keys it holds.
+ return withBeliefBatch(tx, { sourceId, slugs: lockSlugs, publicationId, op: operation, remote: ctx.remote !== false, report }, () => write(tx, sourceId));
}, { ...principalAttribution(authority.principal), ...(trust ? { trust } : {}) }));
+ if (report.appended) await markBeliefCommits(ctx.engine, [publicationId]).catch(() => undefined);
return { value };
}
diff --git a/src/core/persistence/memory-mutations.ts b/src/core/persistence/memory-mutations.ts
index 0e97637b07..6bc39d465b 100644
--- a/src/core/persistence/memory-mutations.ts
+++ b/src/core/persistence/memory-mutations.ts
@@ -26,6 +26,7 @@ import { isTerminal, type WriteRequest } from './model.ts';
import { prepareMemoryMutation } from './memory-prepare.ts';
import { retryWriteAdmission } from './admission-retry.ts';
import { privateProvenanceFilterFragment, resolveExcludePrivatePages } from '../search/private-visibility.ts';
+import { markBeliefCommits } from '../belief/append.ts';
export { prepareMemoryMutation } from './memory-prepare.ts';
/** Only semantic appends without an explicit caller revision can be recomputed. */
@@ -244,8 +245,10 @@ export async function submitForgetMutation(ctx: OperationContext, operation: 'fo
// Retry the whole withdrawal, so source/principal guards and the connection
// are released before backoff. Admission must not retry a nested savepoint.
let withdrawn: WithdrawalCommit['pages'] = [];
+ const beliefReport = { appended: 0 };
const done = await retryWriteAdmission(requestId, remaining => ctx.engine.transaction(async tx => {
withdrawn = [];
+ beliefReport.appended = 0;
await declareDurablePersistence(tx, `${Math.min(1000, remaining)}ms`, `${remaining}ms`);
// Brain row -> source -> current grant -> counters/request -> sorted page keys -> facts.
// Do not acquire a shared source lock first and upgrade it after admission.
@@ -275,7 +278,7 @@ export async function submitForgetMutation(ctx: OperationContext, operation: 'fo
return withCoordinatedWrite(tx, [sourceId], async () => {
// Even an expired legacy fact acquires a ledger so a stale import cannot
// reactivate it. Internal affected-page identities never enter the receipt.
- withdrawn = (await recordFactWithdrawal(tx, id, sourceId, ctx.remote !== false, { requestId: row.id, semanticReview, excludePrivate })).pages;
+ withdrawn = (await recordFactWithdrawal(tx, id, sourceId, ctx.remote !== false, { requestId: row.id, semanticReview, excludePrivate, beliefReport })).pages;
if (reason) await tx.executeRaw(`UPDATE facts SET context=concat_ws(' | ',NULLIF(context,''),$3::text)
WHERE id=$1 AND source_id=$2`, [id, sourceId, `forgotten: ${reason}`]);
if (operation === 'forget_fact' && fact.expired_at !== null) {
@@ -287,6 +290,7 @@ export async function submitForgetMutation(ctx: OperationContext, operation: 'fo
return completeWrite(tx, row, 'committed', { ...outcome, persistence: { mode: 'database' } });
}, requestAttribution(row));
}), undefined, error => ctx.engine.reconnect({ error }));
+ if (beliefReport.appended && done.state === 'committed') await markBeliefCommits(ctx.engine, [done.id]).catch(() => undefined);
// The commit removed the withdrawn pages' chunks. Rebuild them before
// acknowledging: a CLI process exits without a resident projection worker.
// A failed rebuild stays queued as durable projection work.
diff --git a/src/core/persistence/memory-prepare.ts b/src/core/persistence/memory-prepare.ts
index 38a9dd9dc3..8936b0e816 100644
--- a/src/core/persistence/memory-prepare.ts
+++ b/src/core/persistence/memory-prepare.ts
@@ -28,6 +28,7 @@ import { pageFencesNormalized } from '../fence-repair/report.ts';
import { fenceAppendPendingTier, withPendingFenceRows } from '../eligibility/fence-overlay.ts';
import { withPageTierKept } from '../trust/fence-append.ts';
import { privateProvenanceFilterFragment, resolveExcludePrivatePages } from '../search/private-visibility.ts';
+import { noteBelief } from '../belief/ledger.ts';
function receiptFix(row: WriteRequest): Action {
return row.principal_kind === 'local_cli'
@@ -172,7 +173,10 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteReque
() => preparePageMutation(engine, { ...row, intent: { ...p, content, expected_revision: observedRevision, force: false } }, config, undefined, signal));
if (page.observedRevision !== observedRevision) conflict(row);
}
- return { observedRevision, file: page?.file, ...(page?.exclusiveSources ? { exclusiveSources: page.exclusiveSources } : {}), validate: async tx => { await validate(tx); await page?.validate?.(tx); }, apply: async tx => {
+ // The belief ledger records the superseded fact in its own stream, so that stream's page key is held too.
+ const supersededStream = status === 'superseded' ? decision.candidate!.source_markdown_slug ?? decision.candidate!.entity_slug ?? null : null;
+ const additionalPageKeys = supersededStream && supersededStream !== row.slug ? [{ sourceId: row.source_id, slug: supersededStream }] : undefined;
+ return { observedRevision, file: page?.file, ...(page?.exclusiveSources ? { exclusiveSources: page.exclusiveSources } : {}), ...(additionalPageKeys ? { additionalPageKeys } : {}), validate: async tx => { await validate(tx); await page?.validate?.(tx); }, apply: async tx => {
const pageReceipt = page ? await withPageTierKept(tx, { sourceId: row.source_id, slug: row.slug }, () => page!.apply(tx)) as { size_state?: unknown } | undefined : undefined;
let id: number;
if (rowNum !== undefined) {
@@ -190,8 +194,11 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteReque
const inserted = await tx.insertFact(fact, { source_id: row.source_id }); // gbrain-allow-direct-insert: journaled source-scoped semantic publication for subjectless or unresolved entity memory
id = inserted.id;
}
- if (status === 'superseded') await tx.executeRaw(`UPDATE facts SET expired_at=now(),superseded_by=$3
+ if (status === 'superseded') {
+ await tx.executeRaw(`UPDATE facts SET expired_at=now(),superseded_by=$3
WHERE id=$1 AND source_id=$2 AND expired_at IS NULL`, [decision.candidate!.id, row.source_id, id]);
+ noteBelief({ kind: 'superseded', oldId: Number(decision.candidate!.id), newId: id });
+ }
const contestedBy = contestedOld ? await recordContestedFact(tx, { sourceId: row.source_id, oldId: contestedOld.id,
oldTier: storedTrustTier(contestedOld.trust_tier), newId: id, newTier: writerTier,
guard: replaces !== null ? 'remember.replaces' : contested ? 'conflict_slot' : 'conflict_slot_lexical' }) : null;
diff --git a/src/core/persistence/takes-prepare.ts b/src/core/persistence/takes-prepare.ts
index 3f103bc375..86833f8dad 100644
--- a/src/core/persistence/takes-prepare.ts
+++ b/src/core/persistence/takes-prepare.ts
@@ -28,6 +28,7 @@ import { requestAttribution } from './attribution.ts';
import { withWriteAttribution } from './context.ts';
import { decideTakeWrite, recordFlaggedRow, recordWriteGateHold } from '../write-gate-store.ts';
import { writeGateRejectedError } from '../write-gate.ts';
+import { beliefTransaction } from '../belief/writers.ts';
/** Server-derived values are frozen after replay lookup, before admission. */
export async function normalizeTakesIntent(ctx: OperationContext, params: Record<string, unknown>): Promise<Record<string, unknown>> {
@@ -78,8 +79,11 @@ function fail(error: unknown): never {
* request) and returns the refusal carrying its ref; nothing was removed. A retry reuses the proposal.
*/
async function takeRemovalRequiresOwner(engine: BrainEngine, row: WriteRequest, take: { id: number; tier: TrustTier; rowNum: number }, writer: TrustTier): Promise<OperationError> {
- const [ref] = await engine.transaction(tx => withWriteAttribution(tx, requestAttribution(row), () => contestHeldRows(tx, { sourceId: row.source_id, slug: row.slug,
- table: 'takes', proposer: 'takes_remove', writer, rows: [{ id: take.id, tier: take.tier, change: 'removed' }] })));
+ // W1 #6783 §6.2: the refusal's own transaction records trust.contested on the take.
+ const [ref] = await beliefTransaction(engine, { sourceId: row.source_id, slugs: [row.slug], publicationId: row.id, op: row.operation,
+ remote: row.authority.remote !== false, cause: { refused: 'forget_requires_owner' } }, tx => contestHeldRows(tx, { sourceId: row.source_id, slug: row.slug,
+ table: 'takes', proposer: 'takes_remove', writer, rows: [{ id: take.id, tier: take.tier, change: 'removed' }] }),
+ (tx, run) => withWriteAttribution(tx, { ...requestAttribution(row), trust: requestChannelTrust(row) ?? undefined }, run));
const error = opError('forget_requires_owner', `Take row #${take.rowNum} on ${row.slug} is ${take.tier}; this write cannot remove it. Proposal ${ref} asks the owner.`,
`Do not retry. Tell the user take row #${take.rowNum} on ${row.slug} needs their decision: they can remove it with gbrain trust confirm ${ref} on the brain host.`);
error.fix = tierRaiseFix(['gbrain', 'trust', 'confirm', ref!], 'Removing a take the owner confirmed or curated is their decision; the confirm prompt applies the removal.',
diff --git a/src/core/trust/backfill.ts b/src/core/trust/backfill.ts
index 48944b8573..354fa52754 100644
--- a/src/core/trust/backfill.ts
+++ b/src/core/trust/backfill.ts
@@ -42,6 +42,8 @@ import { opError } from '../ops/contract.ts';
import { CONNECTOR_SOURCE_KINDS } from '../persistence/connector-identity.ts';
import { withCoordinatedWrite, withTrustBackfill } from '../persistence/context.ts';
import { propagateTierLowering } from './propagation.ts';
+import { appendBulkRetier } from '../belief/retier.ts';
+import { markBeliefCommits } from '../belief/append.ts';
import { maintenanceAttribution } from '../persistence/attribution.ts';
import { readManagedMode } from '../persistence/managed-mode.ts';
import { EXTRACT_ATOMS_EXTRACTOR_PREFIX, frontmatterTrustCapsSql } from './channel.ts';
@@ -334,13 +336,21 @@ export async function runTrustBackfill(engine: BrainEngine, opts: TrustBackfillO
if (ids.length === 0) break;
const sources = (await engine.executeRaw<{ source_id: string | null }>(
`SELECT DISTINCT ${src} AS source_id FROM ${from} WHERE x.id = ANY($1::bigint[])`, [ids])).map(r => r.source_id).filter((s): s is string => !!s);
- const apply = (tx: BrainEngine) => withTrustBackfill(tx, async () => (await tx.executeRaw<{ id: number }>(
- `WITH b AS (SELECT x.id, ${trustTierFromRankSql(rule)} AS tier FROM ${from} WHERE x.id = ANY($1::bigint[]))
- UPDATE ${table} t SET trust_tier = b.tier, write_origin = COALESCE(t.write_origin, $2::text::jsonb)
- FROM b WHERE t.id = b.id AND t.trust_tier = 'unknown' AND b.tier <> 'unknown' RETURNING t.id`, [ids, origin])).length);
+ const publications: string[] = [];
+ // W1 #6783 §6.4: each batch's changed subjects are recorded as one summary trust.retiered per stream plus a manifest row each.
+ const apply = (tx: BrainEngine) => withTrustBackfill(tx, async () => {
+ const changed = await tx.executeRaw<{ id: number; tier: string }>(
+ `WITH b AS (SELECT x.id, ${trustTierFromRankSql(rule)} AS tier FROM ${from} WHERE x.id = ANY($1::bigint[]))
+ UPDATE ${table} t SET trust_tier = b.tier, write_origin = COALESCE(t.write_origin, $2::text::jsonb)
+ FROM b WHERE t.id = b.id AND t.trust_tier = 'unknown' AND b.tier <> 'unknown' RETURNING t.id, b.tier`, [ids, origin]);
+ const publication = await appendBulkRetier(tx, changed.map(r => ({ table, id: Number(r.id), from: 'unknown', to: r.tier })), scoped ? 'trust_claim' : 'trust_backfill');
+ if (publication) publications.push(publication);
+ return changed.length;
+ });
updated += await engine.transaction(tx => managedBrain && sources.length
? withCoordinatedWrite(tx, sources, () => apply(tx), attribution)
: apply(tx));
+ if (publications.length) await markBeliefCommits(engine, publications).catch(() => undefined);
after = ids[ids.length - 1]!;
cursor[table] = after;
await saveCursor(engine, cursor, op, key);
@@ -414,11 +424,17 @@ export async function relowerClaimedRows(engine: BrainEngine, opts: { dryRun?: b
if (opts.dryRun || rows.length === 0) continue;
const ids = rows.map(r => Number(r.id));
const sources = [...new Set(rows.map(r => r.source_id))];
- const apply = async (tx: BrainEngine) => (await withTrustBackfill(tx, () => tx.executeRaw<{ id: number }>(
- `WITH b AS (${candidates} AND x.id = ANY($2::bigint[]))
- UPDATE ${table} t SET trust_tier = b.to_tier, write_origin = $3::text::jsonb FROM b WHERE t.id = b.id RETURNING t.id`, [claimed, ids, origin])))
- .map(row => ({ table, id: Number(row.id) }));
+ const publications: string[] = [];
+ const apply = async (tx: BrainEngine) => {
+ const changed = await withTrustBackfill(tx, () => tx.executeRaw<{ id: number; from_tier: string; to_tier: string }>(
+ `WITH b AS (${candidates} AND x.id = ANY($2::bigint[]))
+ UPDATE ${table} t SET trust_tier = b.to_tier, write_origin = $3::text::jsonb FROM b WHERE t.id = b.id RETURNING t.id, b.from_tier, b.to_tier`, [claimed, ids, origin]));
+ const publication = await appendBulkRetier(tx, changed.map(r => ({ table, id: Number(r.id), from: r.from_tier, to: r.to_tier })), 'trust_relower');
+ if (publication) publications.push(publication);
+ return changed.map(row => ({ table, id: Number(row.id) }));
+ };
lowered.push(...await engine.transaction(tx => managedBrain ? withCoordinatedWrite(tx, sources, () => apply(tx), attribution!) : apply(tx)));
+ if (publications.length) await markBeliefCommits(engine, publications).catch(() => undefined);
}
// W1 #6783 §12 (b): after every table is relowered (the dry run reports exactly these rows), what was derived from them follows.
if (lowered.length) await engine.transaction(tx => managedBrain
diff --git a/src/core/trust/held-removals.ts b/src/core/trust/held-removals.ts
index c3a886420e..4b38478bb9 100644
--- a/src/core/trust/held-removals.ts
+++ b/src/core/trust/held-removals.ts
@@ -26,6 +26,8 @@ import { reprojectTimelineRow } from '../persistence/canonical-projections.ts';
import { decisionResult, getTrustProposal, transitionTrustProposal, type TrustDecisionContext, type TrustDecisionResult, type TrustProposalRow } from './proposals.ts';
import { storedTrustTier } from './tier.ts';
import { assertInlineBody } from '../page-body/page-shape.ts';
+import { withBeliefBatch } from '../belief/ledger.ts';
+import { markBeliefCommits } from '../belief/append.ts';
interface HeldPageRow { id: number; page_id: number; source_id: string; slug: string; body_storage: 'inline' | 'segmented' | null; compiled_truth: string; timeline: string | null }
@@ -71,11 +73,15 @@ export async function acceptHeldRemoval(engine: BrainEngine, proposal: TrustProp
const writer = { tier: storedTrustTier(proposal.before_state.writer_tier), origin: { channel: `trust_accept:${proposal.proposer}` } };
const attribution = ctx.decidedBy ? principalAttribution(ctx.decidedBy) : await maintenanceAttribution(engine);
const managed = await managedPersistenceEnabled(engine);
+ const publicationId = crypto.randomUUID();
+ const report = { appended: 0 };
const applied = await engine.transaction(async tx => {
const run = async () => {
await tx.lockPageKeys([{ sourceId: row.source_id, slug: row.slug }]);
if (!await transitionTrustProposal(tx, proposal.id, 'pending', 'accepted', { decidedBy: ctx.decidedBy })) return false;
- await withWriteTrust(tx, writer, async () => {
+ // W1 #6783 §6.2: the accepted removal is the take's retraction, recorded at its preimage tier with the writer's tier beside it.
+ await withWriteTrust(tx, writer, () => withBeliefBatch(tx, { sourceId: row.source_id, slugs: [row.slug], publicationId, op: 'trust_accept', remote: false, report,
+ cause: { proposal: `tp${proposal.id}` } }, async () => {
if (table === 'takes') {
if (fenceRow) await tx.addTakesBatch([takesPreparation.toCanonicalBatchInput(row.page_id, fenceRow)]);
else await tx.executeRaw('DELETE FROM takes WHERE id = $1', [row.id]);
@@ -83,12 +89,13 @@ export async function acceptHeldRemoval(engine: BrainEngine, proposal: TrustProp
await tx.executeRaw('DELETE FROM timeline_entries WHERE id = $1', [row.id]);
await reprojectTimelineRow(tx, row.page_id, body, row.slug, { date: String(row.date), source: row.source as string | null, summary: String(row.summary) });
}
- });
+ }));
await queuePageProjection(tx, row.source_id, row.slug, 'trust_tier_changed');
return true;
};
return managed ? withCoordinatedWrite(tx, [row.source_id], run, attribution) : withWriteAttribution(tx, attribution, run);
});
+ if (report.appended) await markBeliefCommits(engine, [publicationId]).catch(() => undefined);
return applied ? decisionResult(proposal, 'accept', 'accepted', { detail: { [table === 'takes' ? 'take_id' : 'timeline_entry_id']: String(row.id) } })
: decisionResult(proposal, 'accept', 'refused', { reason: (await getTrustProposal(engine, proposal.id))?.status ?? 'not_found' });
}
diff --git a/src/core/trust/owner-actions.ts b/src/core/trust/owner-actions.ts
index c83cf95532..6ee1221111 100644
--- a/src/core/trust/owner-actions.ts
+++ b/src/core/trust/owner-actions.ts
@@ -39,6 +39,7 @@ import { getWriteGateHold, releaseWriteGateHold, type WriteGateHold } from '../w
import { withCoordinatedWrite, withTrustPromotion, withWriteAttribution, withWriteTrust } from '../persistence/context.ts';
import { maintenanceAttribution } from '../persistence/attribution.ts';
import { managedPersistenceEnabled } from '../persistence/ownership.ts';
+import { lockedBeliefBatch } from '../belief/writers.ts';
import {
addTrustAllowRule, getTrustAllowRule, normalizeTrustAllowRule, parseAllowRuleRef, principalLabel, removeTrustAllowRule, type TrustAllowRule,
} from './allow-rules.ts';
@@ -190,12 +191,14 @@ async function publishReleasedFact(tx: BrainEngine, hold: WriteGateHold): Promis
const p = hold.payload;
const str = (v: unknown) => (typeof v === 'string' && v ? v : null);
const trust = { tier: 'user_confirmed' as const, origin: { channel: 'trust_release', request_id: hold.request_id ?? undefined } };
- const write = () => withTrustPromotion(tx, 'user_confirmed', () => withWriteTrust(tx, trust, () => tx.insertFact({ // gbrain-allow-direct-insert: owner release of a held fact (CEO-9), inside the owner's coordinated transaction
+ // W1 #6783 §5.1: the released fact is recorded in its subject's stream, under that slug's page key.
+ const write = () => withTrustPromotion(tx, 'user_confirmed', () => withWriteTrust(tx, trust, () => lockedBeliefBatch(tx, { sourceId: hold.source_id,
+ slugs: str(p.entity_slug) ? [String(p.entity_slug)] : [], op: 'trust_release', remote: false, cause: { hold: `wh${hold.id}` } }, () => tx.insertFact({ // gbrain-allow-direct-insert: owner release of a held fact (CEO-9), inside the owner's coordinated transaction
fact: String(p.fact ?? ''), kind: (str(p.kind) ?? 'fact') as never, entity_slug: str(p.entity_slug), visibility: (p.visibility === 'world' ? 'world' : 'private'),
source: str(p.source) ?? `trust release h${hold.id}`, context: str(p.context), source_session: str(p.source_session), confidence: 1,
valid_from: str(p.valid_from) ? new Date(String(p.valid_from)) : new Date(), valid_until: str(p.valid_until) ? new Date(String(p.valid_until)) : null,
embedding: null, embedding_model: null,
- }, { source_id: hold.source_id })));
+ }, { source_id: hold.source_id }))));
if (await managedPersistenceEnabled(tx)) await withCoordinatedWrite(tx, [hold.source_id], write, await maintenanceAttribution(tx));
else await withWriteAttribution(tx, await maintenanceAttribution(tx), write);
}
diff --git a/src/core/trust/page-handlers.ts b/src/core/trust/page-handlers.ts
index bd5838d1c9..c1973ac454 100644
--- a/src/core/trust/page-handlers.ts
+++ b/src/core/trust/page-handlers.ts
@@ -44,6 +44,8 @@ import {
} from './proposals.ts';
import { compareTrust, effectiveWriteTrust, storedTrustTier, type TrustTier, type WriteTrust } from './tier.ts';
import { propagateTierLowering } from './propagation.ts';
+import { beliefStreamSlugs, lockedBeliefBatch } from '../belief/writers.ts';
+import { markBeliefCommits } from '../belief/append.ts';
/** The journaled operation that publishes an owner page action on a managed brain. */
export const TRUST_OWNER_PAGE_OPERATION = 'trust_owner_page';
@@ -128,7 +130,9 @@ export async function setRowTier(engine: BrainEngine, input: {
}): Promise<boolean> {
const attribution = await attributionFor(engine, input.by);
const enabled = await managed(engine);
- return engine.transaction(async tx => {
+ const publicationId = randomUUID();
+ const report = { appended: 0 };
+ const changed = await engine.transaction(async tx => {
const run = async () => {
if (input.expect && !(await input.expect(tx))) return false;
const [prior] = await tx.executeRaw<{ trust_tier: string }>(`SELECT trust_tier FROM ${input.table} WHERE id = $1`, [input.id]);
@@ -144,8 +148,14 @@ export async function setRowTier(engine: BrainEngine, input: {
await input.also?.(tx);
return true;
};
- return enabled ? withCoordinatedWrite(tx, [input.sourceId], run, attribution) : withWriteAttribution(tx, attribution, run);
+ // W1 #6783 §6.4: the tier change is recorded as trust.retiered in the row's stream, under its page key.
+ const slugs = await beliefStreamSlugs(tx, input.table, [input.id]);
+ const recorded = () => lockedBeliefBatch(tx, { sourceId: input.sourceId, slugs, publicationId, op: 'trust_set_tier', report,
+ cause: { owner_decision: { tier: input.tier, ...input.note } } }, run);
+ return enabled ? withCoordinatedWrite(tx, [input.sourceId], recorded, attribution) : withWriteAttribution(tx, attribution, recorded);
});
+ if (report.appended) await markBeliefCommits(engine, [publicationId]).catch(() => undefined);
+ return changed;
}
export interface PageActionInput {
diff --git a/src/core/trust/propagation.ts b/src/core/trust/propagation.ts
index baae65dec1..66ebc2fd6a 100644
--- a/src/core/trust/propagation.ts
+++ b/src/core/trust/propagation.ts
@@ -17,6 +17,7 @@
import type { BrainEngine } from '../engine.ts';
import { derivedRowsFrom, type DerivationRef } from '../facts/derivation-inputs.ts';
import { readManagedMode } from '../persistence/managed-mode.ts';
+import { appendRetierEvents, retierInputCauses } from '../belief/retier.ts';
import { compareTrust, storedTrustTier, trustRankSql, trustTierFromRankSql, type TrustTier } from './tier.ts';
const TIERED = ['facts', 'takes', 'pages', 'timeline_entries'] as const;
@@ -82,5 +83,7 @@ export async function propagateTierLowering(tx: BrainEngine, inputs: readonly De
}
const { queueTierProjection } = await import('./page-write.ts');
for (const row of lowered) if (row.table !== 'timeline_entries') await queueTierProjection(tx, row.table, row.id);
+ // W1 #6783 §6.3: each lowered dependent gets its own trust.retiered, citing the inputs' events as its cause.
+ if (lowered.length) await appendRetierEvents(tx, lowered, { op: 'trust.propagation', inputs: await retierInputCauses(tx, inputs.map(i => ({ table: i.table, id: Number(i.id) }))) });
return lowered;
}
diff --git a/src/core/trust/supersede-handlers.ts b/src/core/trust/supersede-handlers.ts
index 486111b9ff..f5ce0362b9 100644
--- a/src/core/trust/supersede-handlers.ts
+++ b/src/core/trust/supersede-handlers.ts
@@ -11,7 +11,9 @@
* (ids and tiers only, never claim text). The checked supersede's own
* before/after record lives in after_state.supersede.
*/
+import { randomUUID } from 'node:crypto';
import type { BrainEngine } from '../engine.ts';
+import { beliefStreamSlugs, beliefTransaction } from '../belief/writers.ts';
import {
applyProposalAction, type PairProposal, type PairProposalStore, type ProposalActionResult,
} from '../facts/proposal-supersede.ts';
@@ -92,10 +94,13 @@ export async function recordContestedTake(tx: BrainEngine, input: { sourceId: st
* meaning is untouched: nothing was expired. A retry reuses the same proposal.
*/
export async function forgetRequiresOwner(engine: BrainEngine, input: { sourceId: string; factId: number; factTier: TrustTier; writerTier: TrustTier; principal: Principal; reason: string | null }): Promise<OperationError> {
- const { id } = await engine.transaction(tx => withWriteAttribution(tx, { requestId: null, principal: input.principal }, () => insertTrustProposal(tx, {
+ // W1 #6783 §6.2: the refusal's own transaction records trust.contested on the fact, so a refused request still leaves a record.
+ const trust = effectiveWriteTrust({ channel: input.writerTier, origin: { channel: 'mcp:forget' } });
+ const { id } = await beliefTransaction(engine, { sourceId: input.sourceId, slugs: await beliefStreamSlugs(engine, 'facts', [input.factId]),
+ publicationId: randomUUID(), op: 'forget', remote: true, cause: { refused: 'forget_requires_owner' } }, tx => insertTrustProposal(tx, {
action: 'forget', sourceId: input.sourceId, target: { table: 'facts', id: input.factId }, proposer: 'remote_forget',
before: { guard: 'remote_forget', fact: { id: input.factId, tier: input.factTier }, writer_tier: input.writerTier, ...(input.reason ? { has_reason: true } : {}) },
- })));
+ }), (tx, run) => withWriteAttribution(tx, { requestId: null, principal: input.principal, trust }, run));
const ref = trustProposalRef(id);
// Frozen MEMORY_VERBS v1 pair: `error` stays scope_denied, `code` is the canonical forget_requires_owner.
const error = verbError('scope_denied',
diff --git a/test/belief-ledger-trust.test.ts b/test/belief-ledger-trust.test.ts
new file mode 100644
index 0000000000..8ecace9225
--- /dev/null
+++ b/test/belief-ledger-trust.test.ts
@@ -0,0 +1,424 @@
+/**
+ * Belief ledger trust, withdrawal and database-only writer probes
+ * (docs/designs/BELIEF_LEDGER.md section 11: 8, 20, 23, 24, 25, 26, 28, plus
+ * forget's withdrawal events and preimages, section 10). Each asserts exact
+ * event types, keys, tiers and values on PGLite and on Postgres when
+ * DATABASE_URL is set, and each has a forced probe: a deliberately broken
+ * emitter that must make the assertion fail.
+ *
+ * The brain is a managed one whose probe source is database-only (no
+ * worktree), so remote agent writes, owner decisions and database-only writes
+ * all run through their production paths.
+ */
+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { operationsByName } from '../src/core/operations.ts';
+import { mintLegacyToken } from '../src/core/token-mint.ts';
+import { registerLocalWriter, readLocalWriter } from '../src/core/persistence/identity.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import type { Principal } from '../src/core/persistence/model.ts';
+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
+import { withCoordinatedWrite, withTrustBackfill, withTrustPromotion } from '../src/core/persistence/context.ts';
+import { listTrustProposals } from '../src/core/trust/proposals.ts';
+import { decideTrustProposal } from '../src/core/trust/decide.ts';
+import { recordDerivationInputs } from '../src/core/facts/derivation-inputs.ts';
+import { setRowTier } from '../src/core/trust/page-handlers.ts';
+import { runTrustBackfill } from '../src/core/trust/backfill.ts';
+import { enableBeliefLedger } from '../src/core/belief/coverage.ts';
+import { __setBeliefEmitterFaultForTests, type BeliefEventDraft } from '../src/core/belief/append.ts';
+import { lifetimeRef, pageKey } from '../src/core/belief/keys.ts';
+import { LEGACY_EMBEDDING_CONFIG } from './helpers/legacy-embedding-config.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { 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';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-belief-trust-'));
+const quiet = { info() {}, warn() {}, error() {} };
+const owner = { confirmation: { via: 'tty' as const } };
+
+afterEach(() => __setBeliefEmitterFaultForTests(null));
+afterAll(() => rmSync(home, { recursive: true, force: true }));
+
+interface Brain { engine: BrainEngine; sourceId: string; remote: OperationContext; local: OperationContext }
+
+const run = (ctx: OperationContext, op: string, params: Record<string, unknown>) =>
+ operationsByName[op]!.handler(ctx, { request_id: randomUUID(), ...params }) as Promise<Record<string, any>>;
+const refusal = (promise: Promise<unknown>) => promise.then(() => null, (error: unknown) => error as { code?: string; message: string });
+const lastId = async (b: Brain) => Number((await b.engine.executeRaw<{ id: number | null }>('SELECT max(id) AS id FROM belief_events WHERE source_id = $1', [b.sourceId]))[0]?.id ?? 0);
+/** The events `fn` appended. */
+async function since(b: Brain, fn: () => Promise<unknown>): Promise<BeliefEvent[]> {
+ const mark = await lastId(b);
+ await fn();
+ return readEvents(b.engine, b.sourceId, mark);
+}
+const coordinated = (b: Brain, fn: (tx: BrainEngine) => Promise<unknown>) =>
+ b.engine.transaction(tx => withCoordinatedWrite(tx, [b.sourceId], () => fn(tx), TEST_WRITE_ATTRIBUTION));
+/** The owner confirms a row (CEO-9), through the promotion seam. */
+const confirm = (b: Brain, table: string, id: number) =>
+ coordinated(b, tx => withTrustPromotion(tx, 'user_confirmed', () => tx.executeRaw(`UPDATE ${table} SET trust_tier='user_confirmed' WHERE id=$1`, [id])));
+/** A row classified operator_curated through the deterministic backfill seam (CEO-10). */
+const curate = (b: Brain, table: string, id: number) => coordinated(b, async tx => {
+ await withTrustPromotion(tx, 'user_confirmed', () => tx.executeRaw(`UPDATE ${table} SET trust_tier='unknown' WHERE id=$1`, [id]));
+ await withTrustBackfill(tx, () => tx.executeRaw(`UPDATE ${table} SET trust_tier='operator_curated' WHERE id=$1`, [id]));
+});
+const pageId = async (b: Brain, slug: string) => Number((await b.engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id=$1 AND slug=$2', [b.sourceId, slug]))[0]!.id);
+const factId = async (b: Brain, claim: string) => Number((await b.engine.executeRaw<{ id: number }>(
+ 'SELECT id FROM facts WHERE source_id=$1 AND fact=$2 AND expired_at IS NULL ORDER BY id DESC LIMIT 1', [b.sourceId, claim]))[0]!.id);
+const takeRows = async (b: Brain, slug: string) => b.engine.executeRaw<{ id: number; row_num: number; claim: string; active: boolean; trust_tier: string }>(
+ 'SELECT id::int AS id, row_num, claim, active, trust_tier FROM takes WHERE page_id=$1 ORDER BY row_num', [await pageId(b, slug)]);
+const content = async (b: Brain, slug: string) => operationsByName.get_page!.handler(b.local, { slug, include_content: true }) as Promise<Record<string, any>>;
+/** The newest event naming `key`, before this point. */
+const latest = async (b: Brain, key: string) => (await readEvents(b.engine, b.sourceId)).filter(e => e.subject_key === key).at(-1)!;
+const parts = (e: BeliefEvent) => JSON.parse(e.subject_key) as unknown[];
+const fault = (fn: (drafts: BeliefEventDraft[]) => BeliefEventDraft[]) => __setBeliefEmitterFaultForTests(fn);
+const dropType = (type: string, kind?: string) => (drafts: BeliefEventDraft[]) => drafts.filter(d => d.eventType !== type || (kind !== undefined && d.subjectKind !== kind));
+const retype = (from: string, to: string) => (drafts: BeliefEventDraft[]) => drafts.map(d => d.eventType === from ? { ...d, eventType: to } : d);
+
+for (const engineCase of testBackends().map(beliefEngineCase)) {
+ describe(`belief ledger trust and identity writers (${engineCase.name})`, () => {
+ let engine: BrainEngine;
+ let close: (() => Promise<void>) | undefined;
+ beforeAll(async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: {} });
+ if (engineCase.databaseUrl) ({ engine, close } = await isolatedPersistencePostgres(engineCase.databaseUrl));
+ else { const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engine = lite; }
+ }), 120_000);
+ afterAll(async () => { resetGateway(); await disposePersistenceConsumer(engine); if (close) await close(); else await engine.disconnect(); });
+
+ /** A database-only source with active coverage, a local CLI context and a remote agent token. */
+ async function brain(opts: { enable?: boolean } = {}): Promise<Brain> {
+ const sourceId = `belief-trust-${randomUUID().slice(0, 8)}`;
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);
+ await registerLocalWriter(engine, 'cli');
+ const minted = await mintLegacyToken(engine, { name: `token-${sourceId}`, scopes: ['read', 'write'], sourceGrant: [sourceId], takesHolders: ['world'] });
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ await readLocalWriter(engine, 'cli');
+ if (opts.enable !== false) await enableBeliefLedger(engine, sourceId);
+ const base = { engine, config: { engine: engine.kind, embedding_disabled: true }, sourceId, dryRun: false, logger: quiet };
+ return { engine, sourceId,
+ remote: { ...base, remote: true, transport: 'http', takesHoldersAllowList: ['world'],
+ auth: { token: '', clientId: minted.id, principal: { kind: 'legacy_token', id: minted.id } as Principal, sourceId, allowedSources: [sourceId], scopes: ['read', 'write'] } } as unknown as OperationContext,
+ local: { ...base, remote: false } as unknown as OperationContext };
+ }
+ const withHome = (fn: () => Promise<void>) => () => withEnv({ GBRAIN_HOME: home }, fn);
+
+ test('forget: fact.withdrawn and page.view_changed with the pre-withdrawal body kept as a version; materialization is a second view change', 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 published = (await readEvents(b.engine, b.sourceId)).find(e => e.event_type === 'page.published')!;
+ const lifetime = published.page_lifetime!;
+ const before = String((await content(b, slug)).revision);
+ const staff = await factId(b, 'Acme has ten staff');
+ const check = (events: BeliefEvent[]) => {
+ const forget = events.filter(e => e.cause.op === 'forget');
+ expect(shape(forget)).toEqual(['page:page.view_changed', 'fact:fact.withdrawn']);
+ expect(forget[0]!.value).toMatchObject({ revision_before: before });
+ expect(forget[0]!.subject_key).toBe(pageKey(lifetime));
+ expect(parts(forget[1]!).slice(0, 3)).toEqual(['f', lifetimeRef(lifetime), 2]);
+ expect(forget[1]!).toMatchObject({ value: null, trust_tier: 'agent_written', page_lifetime: lifetime });
+ return forget;
+ };
+ const mark = await lastId(b);
+ await run(b.local, 'forget', { id: String(staff) });
+ const forget = check(await readEvents(b.engine, b.sourceId, mark));
+ const after = String(forget[0]!.value!.revision_after);
+ expect(after).not.toBe(before);
+ // The effect worker materializes the body at the withdrawal's revision: one more view change, and its preimage version.
+ const materialized = await waitForValue(async () => (await readEvents(b.engine, b.sourceId, mark)).find(e => e.cause.op === 'withdrawal_materialize'),
+ { timeoutMs: 30_000, label: 'withdrawal materialization' });
+ expect(materialized).toMatchObject({ event_type: 'page.view_changed', subject_key: pageKey(lifetime), value: { materialized: true, revision_before: after, revision_after: after } });
+ const versions = await b.engine.executeRaw<{ knowledge_revision: string; compiled_truth: string }>(
+ 'SELECT knowledge_revision::text AS knowledge_revision, compiled_truth FROM page_versions WHERE page_id=$1 ORDER BY id', [await pageId(b, slug)]);
+ expect(versions.map(v => v.knowledge_revision)).toEqual([before, after]);
+ expect(versions[0]!.compiled_truth).toContain('Acme has ten staff');
+ // Forced probe: an emitter that records the withdrawal as a plain retraction is caught.
+ fault(retype('fact.withdrawn', 'fact.retracted'));
+ const seed = await factId(b, 'Acme raised a seed round');
+ const forced = await since(b, () => run(b.local, 'forget', { id: String(seed) }));
+ expect(() => check(forced)).toThrow();
+ }), 120_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';
+ await run(b.local, 'put_page', { slug, content: beliefPage({ facts: ['Acme raised a seed round', 'Acme has ten staff'] }) });
+ await run(b.local, 'takes_add', { slug, claim: 'Acme will win its market', kind: 'bet', holder: 'world', weight: 0.6 });
+ const staff = await factId(b, 'Acme has ten staff');
+ await confirm(b, 'facts', staff);
+ const staffKey = (await readEvents(b.engine, b.sourceId)).find(e => e.event_type === 'page.published')!;
+ const lifetime = staffKey.page_lifetime!;
+ const contested = (events: BeliefEvent[], kind: string, ref: string) => {
+ const e = events.find(x => x.event_type === 'trust.contested' && x.subject_kind === kind);
+ expect(e).toBeDefined();
+ expect(e!).toMatchObject({ trust_tier: 'user_confirmed', writer_tier: 'agent_written', value: null });
+ expect(e!.cause.proposal).toBe(ref);
+ return e!;
+ };
+ // A lower-tier rewrite that drops the confirmed fence row: the row stays, the event names it, nothing retracts it.
+ const current = await operationsByName.get_page!.handler(b.remote, { slug, include_content: true }) as Record<string, any>;
+ const edited = String(current.content).split('\n').filter(line => !line.includes('Acme has ten staff')).join('\n');
+ let put: Record<string, any> = {};
+ const fence = await since(b, async () => { put = await run(b.remote, 'put_page', { slug, content: edited, expected_revision: current.revision }); });
+ const ref = put.contested?.proposal_ref ?? put.contested?.proposal_refs?.[0];
+ expect(ref).toMatch(/^tp\d+$/);
+ const fenceEvent = contested(fence, 'fact', ref);
+ expect(parts(fenceEvent).slice(0, 3)).toEqual(['f', lifetimeRef(lifetime), 2]);
+ expect(fence.filter(e => e.subject_key === fenceEvent.subject_key).map(e => e.event_type)).toEqual(['trust.contested']);
+ // remember.replaces of a confirmed database-only fact.
+ const old = await run(b.local, 'remember', { fact: 'Bob example likes tea', provenance: 'owner', entity: 'people/bob-example' });
+ await confirm(b, 'facts', Number(old.id));
+ let agent: Record<string, any> = {};
+ const remember = await since(b, async () => { agent = await run(b.remote, 'remember', { fact: 'Bob example likes coffee', provenance: 'web', entity: 'people/bob-example', replaces: String(old.id) }); });
+ expect(shape(remember)).toEqual(['fact:trust.contested', 'fact:fact.asserted']);
+ const rememberEvent = contested(remember, 'fact', agent.contested.proposal_ref);
+ expect(rememberEvent.cause.guard).toBe('remember.replaces');
+ expect(remember[1]!).toMatchObject({ trust_tier: 'agent_written', value: { fact: 'Bob example likes coffee' } });
+ // takes_supersede of a confirmed take: contested plus the new take asserted.
+ const [take] = await takeRows(b, slug);
+ await confirm(b, 'takes', take!.id);
+ let superseded: Record<string, any> = {};
+ const takes = await since(b, async () => { superseded = await run(b.remote, 'takes_supersede', { slug, row_num: take!.row_num, claim: 'Acme will lose its market' }); });
+ expect(shape(takes).sort()).toEqual(['page:page.published', 'take:take.asserted', 'take:trust.contested']);
+ expect(contested(takes, 'take', superseded.contested.proposal_ref).cause.guard).toBe('takes_supersede');
+ expect(takes.find(e => e.event_type === 'take.asserted')!.value).toMatchObject({ claim: 'Acme will lose its market' });
+ // A refused remote forget: its own transaction records the contest, and nothing is withdrawn.
+ let refused: { code?: string; message: string } | null = null;
+ const forget = await since(b, async () => { refused = await refusal(run(b.remote, 'forget', { id: String(old.id) })); });
+ expect(refused!.message).toContain('forget_requires_owner');
+ const forgetRef = /Proposal (tp\d+)/.exec(refused!.message)![1]!;
+ expect(shape(forget)).toEqual(['fact:trust.contested']);
+ expect(contested(forget, 'fact', forgetRef).cause).toMatchObject({ guard: 'remote_forget', refused: 'forget_requires_owner' });
+ expect(forget[0]!.subject_key).toBe(rememberEvent.subject_key);
+ // Forced probe: an emitter that drops trust.contested is caught on each path.
+ fault(dropType('trust.contested'));
+ const another = await run(b.local, 'remember', { fact: 'Bob example likes jazz', provenance: 'owner', entity: 'people/bob-example' });
+ await confirm(b, 'facts', Number(another.id));
+ const forcedForget = await since(b, () => refusal(run(b.remote, 'forget', { id: String(another.id) })));
+ expect(() => contested(forcedForget, 'fact', 'tp0')).toThrow();
+ const forcedRemember = await since(b, () => run(b.remote, 'remember', { fact: 'Bob example likes rock', provenance: 'web', entity: 'people/bob-example', replaces: String(another.id) }));
+ expect(() => expect(shape(forcedRemember)).toEqual(['fact:trust.contested', 'fact:fact.asserted'])).toThrow();
+ }), 180_000);
+
+ test('probes 24 and 28: every destructive path on a more trusted take or row leaves it, files a proposal and appends trust.contested; only the owner accept retracts', withHome(async () => {
+ const b = await brain();
+ const slug = 'people/gina-example';
+ await run(b.local, 'put_page', { slug, content: `${beliefPage({ type: 'person', title: 'Gina', facts: ['Gina lives in Lisbon'] })}\n## Timeline\n\n- **2026-01-05** | note — Gina joined acme-example\n Joined as an advisor.\n` });
+ for (const claim of ['Gina will join acme-example', 'Gina moves to Lisbon', 'Gina ships the beta', 'Gina runs a marathon']) {
+ await run(b.local, 'takes_add', { slug, claim, kind: 'bet', holder: 'world', weight: 0.6 });
+ }
+ const takes = await takeRows(b, slug);
+ for (const take of takes) await confirm(b, 'takes', take.id);
+ await confirm(b, 'facts', await factId(b, 'Gina lives in Lisbon'));
+ const [timeline] = await b.engine.executeRaw<{ id: number }>('SELECT id::int AS id FROM timeline_entries WHERE page_id=$1', [await pageId(b, slug)]);
+ await confirm(b, 'timeline_entries', timeline!.id);
+ // One agent rewrite: take 1 omitted, take 2 replaced in place, take 3 struck (active = false), the fact row omitted, the timeline detail replaced.
+ const current = await content(b, slug);
+ const edited = String(current.content).split('\n').filter(line => !line.includes('Gina will join acme-example') && !line.includes('Gina lives in Lisbon'))
+ .join('\n').replace('Gina moves to Lisbon', 'Gina moves to Porto').replace('| Gina ships the beta |', '| ~~Gina ships the beta~~ |')
+ .replace('Joined as an advisor.', 'Joined as CTO.');
+ let put: Record<string, any> = {};
+ const rewrite = await since(b, async () => { put = await run(b.local, 'put_page', { slug, content: edited, expected_revision: current.revision }); });
+ const refs: string[] = put.contested?.proposal_refs ?? [];
+ const proposals = await listTrustProposals(b.engine, { sourceId: b.sourceId });
+ const proposalOf = (table: string, id: number) => proposals.find(p => p.target_table === table && p.target_id === id);
+ const changes = [[takes[0]!.id, 'removed'], [takes[1]!.id, 'replaced'], [takes[2]!.id, 'deactivated']] as const;
+ const check = (events: BeliefEvent[]) => {
+ expect(events.filter(e => e.subject_kind === 'take').map(e => e.event_type)).toEqual(['trust.contested', 'trust.contested', 'trust.contested']);
+ expect(events.some(e => e.event_type === 'take.retracted' || e.event_type === 'fact.retracted' || e.event_type === 'take.revised')).toBe(false);
+ for (const [id, change] of changes) {
+ const proposal = proposalOf('takes', id)!;
+ expect(proposal.before_state).toMatchObject({ change });
+ expect(events.find(e => e.subject_kind === 'take' && e.cause.proposal === `tp${proposal.id}`)).toMatchObject({ trust_tier: 'user_confirmed', writer_tier: 'agent_written' });
+ }
+ const fact = events.find(e => e.subject_kind === 'fact')!;
+ expect(fact).toMatchObject({ event_type: 'trust.contested', trust_tier: 'user_confirmed' });
+ expect(fact.cause.proposal).toBe(`tp${proposals.find(p => p.target_table === 'facts')!.id}`);
+ };
+ check(rewrite);
+ expect(refs.length).toBeGreaterThanOrEqual(4);
+ // The rows are unchanged, and the timeline row (not a ledger subject) keeps its proposal with no event.
+ expect((await takeRows(b, slug)).map(t => [t.id, t.claim, t.active, t.trust_tier])).toEqual(takes.map(t => [t.id, t.claim, true, 'user_confirmed']));
+ expect(proposalOf('timeline_entries', timeline!.id)!.before_state).toMatchObject({ change: 'detail_changed' });
+ expect(rewrite.some(e => e.cause.proposal === `tp${proposalOf('timeline_entries', timeline!.id)!.id}`)).toBe(false);
+ // An explicit remote takes_remove of a confirmed take: refused in its own transaction, which records the contest.
+ let refused: { code?: string; message: string } | null = null;
+ const removal = await since(b, async () => { refused = await refusal(run(b.remote, 'takes_remove', { slug, row_num: takes[3]!.row_num })); });
+ expect(refused!.code).toBe('forget_requires_owner');
+ expect(shape(removal)).toEqual(['take:trust.contested']);
+ const removalProposal = (await listTrustProposals(b.engine, { sourceId: b.sourceId })).find(p => p.target_table === 'takes' && p.target_id === takes[3]!.id)!;
+ expect(removalProposal).toMatchObject({ action: 'forget', proposer: 'takes_remove' });
+ expect(removal[0]!.cause).toMatchObject({ guard: 'takes_remove', refused: 'forget_requires_owner', proposal: `tp${removalProposal.id}` });
+ expect(removal[0]!).toMatchObject({ trust_tier: 'user_confirmed', writer_tier: 'agent_written' });
+ // The owner's accept applies the removal: only now does the take retract, at its preimage tier.
+ const removed = proposalOf('takes', takes[0]!.id)!;
+ const accepted = await since(b, async () => { expect((await decideTrustProposal(b.engine, removed.id, 'accept', owner)).status).toBe('accepted'); });
+ const retracted = accepted.filter(e => e.event_type === 'take.retracted');
+ expect(retracted).toHaveLength(1);
+ expect(retracted[0]!).toMatchObject({ trust_tier: 'user_confirmed', writer_tier: 'agent_written', value: null, cause: { proposal: `tp${removed.id}` } });
+ // Forced probe: an emitter that turns a contest into a completed retraction is caught.
+ fault(retype('trust.contested', 'take.retracted'));
+ await run(b.local, 'takes_add', { slug, claim: 'Gina writes a book', kind: 'bet', holder: 'world', weight: 0.6 });
+ const added = (await takeRows(b, slug)).find(t => t.claim === 'Gina writes a book')!;
+ await confirm(b, 'takes', added.id);
+ const again = await content(b, slug);
+ const forced = await since(b, () => run(b.local, 'put_page', { slug, content: String(again.content).split('\n').filter(l => !l.includes('Gina writes a book')).join('\n'), expected_revision: again.revision }));
+ expect(forced.some(e => e.event_type === 'take.retracted')).toBe(true);
+ expect(() => expect(forced.filter(e => e.subject_kind === 'take').map(e => e.event_type)).toEqual(['trust.contested'])).toThrow();
+ }), 180_000);
+
+ test('probe 23: destructive events carry the preimage tier and a separate writer_tier; a baseline link event carries trust_tier unknown', withHome(async () => {
+ const b = await brain({ enable: false });
+ await run(b.local, 'put_page', { slug: 'people/alice-example', content: beliefPage({ type: 'person', title: 'Alice Example' }) });
+ await run(b.local, 'put_page', { slug: 'companies/huge-example', content: beliefPage({ prose: 'Long prose. '.repeat(100_000), links: ['people/alice-example'] }) });
+ const baseline = await since(b, () => enableBeliefLedger(b.engine, b.sourceId));
+ const link = baseline.filter(e => e.subject_kind === 'link' && e.slug === 'companies/huge-example');
+ expect(link.map(e => [e.event_type, e.trust_tier, e.tier_basis, e.writer_tier])).toEqual([['baseline', 'unknown', 'unknown', null]]);
+ const slug = 'companies/acme-example';
+ await run(b.local, 'put_page', { slug, content: beliefPage({ facts: ['Acme raised a seed round'] }) });
+ await run(b.local, 'takes_add', { slug, claim: 'Acme will win its market', kind: 'bet', holder: 'world', weight: 0.6 });
+ const [take] = await takeRows(b, slug);
+ // Rows below the writer: the owner lowered them, so the agent's removal is not contested and the tiers differ.
+ expect(await setRowTier(b.engine, { table: 'takes', id: take!.id, sourceId: b.sourceId, tier: 'external_untrusted' })).toBe(true);
+ expect(await setRowTier(b.engine, { table: 'pages', id: await pageId(b, slug), sourceId: b.sourceId, tier: 'external_untrusted' })).toBe(true);
+ const check = (events: BeliefEvent[], type: string) => {
+ const e = events.find(x => x.event_type === type)!;
+ expect(e).toBeDefined();
+ expect([e.trust_tier, e.writer_tier, e.tier_basis, e.value?.revision_before === undefined ? e.value : 'page']).toEqual(['external_untrusted', 'agent_written', 'row', type === 'take.retracted' ? null : 'page']);
+ };
+ const retract = await since(b, () => run(b.local, 'takes_remove', { slug, row_num: take!.row_num }));
+ check(retract, 'take.retracted');
+ const deleted = await since(b, async () => run(b.local, 'delete_page', { slug, expected_revision: (await content(b, slug)).revision }));
+ expect(shape(deleted)).toEqual(['page:page.deleted']);
+ check(deleted, 'page.deleted');
+ // Forced probes: an emitter that drops the writer tier, or stamps a baseline link with the scanner's tier, is caught.
+ fault(drafts => drafts.map(d => ({ ...d, writerTier: null })));
+ await run(b.local, 'put_page', { slug: 'companies/other-example', content: beliefPage({ title: 'Other Example' }) });
+ await setRowTier(b.engine, { table: 'pages', id: await pageId(b, 'companies/other-example'), sourceId: b.sourceId, tier: 'external_untrusted' });
+ const forced = await since(b, async () => run(b.local, 'delete_page', { slug: 'companies/other-example', expected_revision: (await content(b, 'companies/other-example')).revision }));
+ expect(() => check(forced, 'page.deleted')).toThrow();
+ fault(drafts => drafts.map(d => d.subjectKind === 'link' ? { ...d, trustTier: 'agent_written', tierBasis: 'writer' as const } : d));
+ const rebaseline = await since(b, async () => { const { disableBeliefLedger } = await import('../src/core/belief/coverage.ts'); await disableBeliefLedger(b.engine, b.sourceId); await enableBeliefLedger(b.engine, b.sourceId); });
+ expect(() => expect(rebaseline.filter(e => e.subject_kind === 'link').map(e => [e.event_type, e.trust_tier, e.tier_basis])).toEqual([['baseline', 'unknown', 'unknown']])).toThrow();
+ }), 180_000);
+
+ test('probe 25: a lowered input lowers each dependent with its own trust.retiered citing the input\'s event; a raised input promotes none', withHome(async () => {
+ const b = await brain();
+ const slug = 'notes/kiko-example';
+ await run(b.local, 'put_page', { slug, content: beliefPage({ type: 'note', title: 'Kiko', prose: 'Kiko runs the lab.' }) });
+ const input = await pageId(b, slug);
+ await curate(b, 'pages', input);
+ const fact = await run(b.local, 'remember', { fact: 'Kiko runs the lab', provenance: 'notes', entity: 'people/kiko-example' });
+ const derived = Number(fact.id);
+ await curate(b, 'facts', derived);
+ await coordinated(b, tx => recordDerivationInputs(tx, { table: 'facts', id: derived, sourceId: b.sourceId }, [{ table: 'pages', id: input }]));
+ const check = (events: BeliefEvent[], to: string) => {
+ const page = events.find(e => e.subject_kind === 'page' && e.event_type === 'trust.retiered')!;
+ const dependent = events.find(e => e.subject_kind === 'fact' && e.event_type === 'trust.retiered')!;
+ expect(page.value).toEqual({ from: 'operator_curated', to });
+ expect(dependent).toMatchObject({ slug: 'people/kiko-example', trust_tier: to, value: { from: 'operator_curated', to } });
+ expect(dependent.cause).toEqual({ op: 'trust.propagation', inputs: [{ subject_key: page.subject_key, event_key: page.event_key }] });
+ expect(dependent.publication_id).toBe(page.publication_id);
+ };
+ const lowered = await since(b, () => setRowTier(b.engine, { table: 'pages', id: input, sourceId: b.sourceId, tier: 'external_untrusted' }));
+ expect(shape(lowered).sort()).toEqual(['fact:trust.retiered', 'page:trust.retiered']);
+ check(lowered, 'external_untrusted');
+ const raised = await since(b, () => setRowTier(b.engine, { table: 'pages', id: input, sourceId: b.sourceId, tier: 'user_confirmed', ceiling: 'user_confirmed' }));
+ expect(shape(raised)).toEqual(['page:trust.retiered']);
+ expect(raised[0]!.value).toEqual({ from: 'external_untrusted', to: 'user_confirmed' });
+ // Forced probe: an emitter that drops the dependent's event is caught.
+ await curate(b, 'facts', derived);
+ await curate(b, 'pages', input);
+ fault(dropType('trust.retiered', 'fact'));
+ const forced = await since(b, () => setRowTier(b.engine, { table: 'pages', id: input, sourceId: b.sourceId, tier: 'external_untrusted' }));
+ expect(() => check(forced, 'external_untrusted')).toThrow();
+ }), 180_000);
+
+ test('probe 26: a bulk trust backfill appends one summary trust.retiered per stream and batch, and a manifest row for every changed subject', 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 facts = [await factId(b, 'Acme raised a seed round'), await factId(b, 'Acme has ten staff')];
+ const page = await pageId(b, slug);
+ await coordinated(b, async tx => {
+ await tx.executeRaw(`UPDATE pages SET trust_tier='unknown' WHERE id=$1`, [page]);
+ await tx.executeRaw(`UPDATE facts SET trust_tier='unknown' WHERE id=ANY($1::bigint[])`, [facts]);
+ });
+ const lifetime = (await readEvents(b.engine, b.sourceId)).find(e => e.event_type === 'page.published' && e.slug === slug)!.page_lifetime!;
+ const check = async (events: BeliefEvent[]) => {
+ const summaries = events.filter(e => e.event_type === 'trust.retiered');
+ expect(summaries.every(e => e.subject_kind === 'page' && e.value!.summary === true && e.cause.manifest === true && e.cause.op === 'trust_claim')).toBe(true);
+ expect(summaries.map(e => [e.slug, e.subject_key, e.value!.subjects])).toEqual([[slug, pageKey(lifetime), 1], [slug, pageKey(lifetime), 2]]);
+ expect(new Set(summaries.map(e => `${e.publication_id}:${e.slug}`)).size).toBe(summaries.length);
+ const manifest = await b.engine.executeRaw<{ summary_event: number; subject_kind: string; subject_key: string; from_tier: string; to_tier: string }>(
+ `SELECT summary_event::int AS summary_event, subject_kind, subject_key, from_tier, to_tier FROM belief_retier_manifest WHERE source_id=$1 AND summary_event = ANY($2::bigint[])`,
+ [b.sourceId, summaries.map(e => e.id)]);
+ for (const summary of summaries) expect(manifest.filter(m => m.summary_event === summary.id)).toHaveLength(Number(summary.value!.subjects));
+ const tiers = new Map((await b.engine.executeRaw<{ id: number; trust_tier: string }>(`SELECT id::int AS id, trust_tier FROM facts WHERE id=ANY($1::bigint[])`, [facts])).map(r => [r.id, r.trust_tier]));
+ const [pageTier] = await b.engine.executeRaw<{ trust_tier: string }>('SELECT trust_tier FROM pages WHERE id=$1', [page]);
+ const subject = (m: { subject_key: string }) => (JSON.parse(m.subject_key) as unknown[])[1];
+ expect(manifest.map(m => [m.subject_kind, m.subject_kind === 'page' ? m.subject_key : subject(m), m.from_tier, m.to_tier]).sort()).toEqual([
+ ['fact', lifetimeRef(lifetime), 'unknown', tiers.get(facts[0]!)], ['fact', lifetimeRef(lifetime), 'unknown', tiers.get(facts[1]!)],
+ ['page', pageKey(lifetime), 'unknown', pageTier!.trust_tier]].sort());
+ expect(new Set(manifest.filter(m => m.subject_kind === 'fact').map(m => m.subject_key)).size).toBe(2);
+ };
+ const events = await since(b, () => runTrustBackfill(b.engine, { sources: [b.sourceId], log: () => undefined }));
+ await check(events);
+ // Forced probe: an emitter that drops the summaries leaves no manifest, which is caught.
+ await coordinated(b, tx => tx.executeRaw(`UPDATE facts SET trust_tier='unknown' WHERE id=ANY($1::bigint[])`, [facts]));
+ await coordinated(b, tx => tx.executeRaw(`UPDATE pages SET trust_tier='unknown' WHERE id=$1`, [page]));
+ fault(dropType('trust.retiered'));
+ const forced = await since(b, () => runTrustBackfill(b.engine, { sources: [b.sourceId], log: () => undefined }));
+ await expect(check(forced)).rejects.toThrow();
+ }), 180_000);
+
+ test('probe 20: ontology stints with identical claim text are distinct keys; an agent observation against a confirmed stint is contested', withHome(async () => {
+ const b = await brain();
+ const entity = 'people/lena-example';
+ const observe = (ctx: OperationContext, value: string, validFrom: string) => run(ctx, 'ontology_propose', { entity, dimension: 'role', value, valid_from: validFrom, source: 'notes', visibility: 'world' });
+ const asserted = await since(b, async () => {
+ await observe(b.local, 'advisor', '2024-01-01');
+ await observe(b.local, 'founder', '2025-01-01');
+ await observe(b.local, 'advisor', '2023-01-01');
+ });
+ const check = (events: BeliefEvent[]) => {
+ const advisor = events.filter(e => e.event_type === 'fact.asserted' && e.value?.value === 'advisor');
+ expect(advisor).toHaveLength(2);
+ const [a, c] = advisor.map(parts);
+ expect(a!.slice(0, 5)).toEqual(c!.slice(0, 5));
+ expect(a![0]).toBe('o');
+ expect([a![5], c![5]].sort()).toEqual(['2023-01-01T00:00:00.000Z', '2024-01-01T00:00:00.000Z']);
+ expect(advisor[0]!.value!.fact).toBe(advisor[1]!.value!.fact);
+ };
+ check(asserted);
+ const founder = asserted.find(e => e.value?.value === 'founder')!;
+ const [stint] = await b.engine.executeRaw<{ id: number }>(`SELECT id::int AS id FROM facts WHERE source_id=$1 AND entity_slug=$2 AND value='founder'`, [b.sourceId, entity]);
+ await confirm(b, 'facts', stint!.id);
+ let result: Record<string, any> = {};
+ const contest = await since(b, async () => { result = await observe(b.remote, 'investor', '2026-01-01'); });
+ expect(result.contested?.proposal_ref).toMatch(/^tp\d+$/);
+ const contested = contest.find(e => e.event_type === 'trust.contested')!;
+ expect(contested).toMatchObject({ subject_key: founder.subject_key, trust_tier: 'user_confirmed', writer_tier: 'agent_written', cause: { guard: 'ontology', proposal: result.contested.proposal_ref } });
+ expect(contest.filter(e => e.subject_key === founder.subject_key).map(e => e.event_type)).toEqual(['trust.contested']);
+ // Forced probe: an emitter that keys stints without their start collapses them, which is caught.
+ fault(drafts => drafts.map(d => d.subjectKey.startsWith('["o"') ? { ...d, subjectKey: JSON.stringify((JSON.parse(d.subjectKey) as unknown[]).slice(0, 5)) } : d));
+ const forced = await since(b, async () => {
+ await observe(b.local, 'mentor', '2020-01-01');
+ await observe(b.local, 'advisor', '2019-01-01');
+ await observe(b.local, 'advisor', '2018-01-01');
+ });
+ expect(() => check(forced)).toThrow();
+ }), 180_000);
+ });
+}
diff --git a/test/helpers/belief-ledger.ts b/test/helpers/belief-ledger.ts
index 9176ef4cc1..d65f8a15ae 100644
--- a/test/helpers/belief-ledger.ts
+++ b/test/helpers/belief-ledger.ts
@@ -42,7 +42,8 @@ export interface BeliefBrain {
export const beliefEngineCase = (name: TestBackend): { name: TestBackend; databaseUrl?: string } =>
name === 'postgres' ? { name, databaseUrl: requirePostgresTestDatabase() } : { name };
-async function readEvents(engine: BrainEngine, sourceId: string, afterId = 0): Promise<BeliefEvent[]> {
+/** A source's events after `afterId`, in id order (for probes that build their own brain). */
+export async function readEvents(engine: BrainEngine, sourceId: string, afterId = 0): Promise<BeliefEvent[]> {
const rows = await engine.executeRaw<BeliefEvent>(`SELECT id, source_id, source_incarnation::text AS source_incarnation, page_lifetime::text AS page_lifetime,
slug, subject_kind, subject_key, event_type, origin, trust_tier, writer_tier, tier_basis, visibility, publication_id::text AS publication_id, ord,
recorded_at, value, value_hash, prior_hash, state_hash, cause, claim_fp, purged, redacted_fields, encode(event_key, 'hex') AS event_key