Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
W1 belief ledger core: schema (v249), finalization contract on single and grouped publication, coverage baseline
garrytan555d486c50d3
diff --git a/scripts/build-schema.ts b/scripts/build-schema.tsindex fed80f5157..cfc0337a0c 100644--- a/scripts/build-schema.ts+++ b/scripts/build-schema.ts@@ -46,6 +46,7 @@ import { PINNED_QUESTIONS_SCHEMA_SQL } from '../src/core/questions/schema.ts';import { CORE_EDIT_NOTICES_SCHEMA_SQL } from '../src/core/core-memory-schema.ts';import { FACT_PURGE_LOOKUP_INDEX_SQL, MEMORY_PURGE_SCHEMA_SQL } from '../src/core/facts/purge-schema.ts';import { WRITE_GATE_SCHEMA_SQL } from '../src/core/write-gate-schema.ts';+import { BELIEF_LEDGER_SCHEMA_SQL } from '../src/core/belief/schema.ts';const REPO = resolve(import.meta.dir, '..');export const SCHEMA_SQL_PATH = 'src/schema.sql';@@ -111,6 +112,7 @@ export const FRAGMENTS: readonly Fragment[] = [{ source: 'src/core/facts/purge-schema.ts', expr: 'FACT_PURGE_LOOKUP_INDEX_SQL', postgres: FACT_PURGE_LOOKUP_INDEX_SQL, pglite: FACT_PURGE_LOOKUP_INDEX_SQL },{ source: 'src/core/write-gate-schema.ts', expr: 'WRITE_GATE_SCHEMA_SQL', postgres: WRITE_GATE_SCHEMA_SQL, pglite: WRITE_GATE_SCHEMA_SQL },{ source: 'src/core/questions/schema.ts', expr: 'PINNED_QUESTIONS_SCHEMA_SQL', postgres: PINNED_QUESTIONS_SCHEMA_SQL, pglite: PINNED_QUESTIONS_SCHEMA_SQL },+ { source: 'src/core/belief/schema.ts', expr: 'BELIEF_LEDGER_SCHEMA_SQL', postgres: BELIEF_LEDGER_SCHEMA_SQL, pglite: BELIEF_LEDGER_SCHEMA_SQL },];const fragmentLabel = (f: Fragment) => `${f.source} (${f.expr})`;diff --git a/src/core/belief/append.ts b/src/core/belief/append.tsnew file mode 100644index 0000000000..e8d314d2ce--- /dev/null+++ b/src/core/belief/append.ts@@ -0,0 +1,150 @@+/**+ * The one ledger insert (docs/designs/BELIEF_LEDGER.md sections 5.2, 6.5).+ * Every appender (publication finalization, baseline, reconcile, backfill,+ * purge, restore replay) builds drafts and calls `appendBeliefEvents` inside+ * its own transaction. Before the insert it enforces this table's own+ * tombstones and the redaction register: an asserting event for a purged+ * fingerprint is written as a redacted skeleton, and a carrying field under an+ * active suppression is written as the redaction marker until an owner release.+ */+import type { BrainEngine } from '../engine.ts';+import { OWNER_TIER_FLOOR, TRUST_TIER_RANK, isTrustTier } from '../trust/tier.ts';+import { CARRYING_FIELDS, REDACTION_MARKER, canonicalJson, eventKeyHex, fieldHash, valueHash } from './keys.ts';++export type BeliefOrigin = 'live' | 'unmanaged' | 'baseline' | 'backfill' | 'reconcile';+export interface BeliefEventDraft {+ sourceId: string; incarnation: string; lifetime: string | null; slug: string;+ subjectKind: 'page' | 'fact' | 'take' | 'link' | 'link_transition' | 'coverage';+ subjectKey: string; eventType: string; trustTier: string; writerTier?: string | null; tierBasis?: 'row' | 'writer' | 'unknown';+ visibility: string; value: Record<string, unknown> | null; priorHash?: string | null; stateHash: string;+ cause: Record<string, unknown>; claimFp?: string | null; sourceTime?: string | null; validFrom?: string | null; validUntil?: string | null;+ /** Purge skeletons and backfill rows under a derived.hidden suppression. */+ purged?: boolean;+ /** Ordering bucket inside one publication: stream slug, then kind rank, then key. */+ stream?: string;+}+export interface AppendContext {+ publicationId: string; origin: BeliefOrigin;+ /** Writer of this transaction: an owner release needs a trusted local write at or above OWNER_TIER_FLOOR. */+ writerTier?: string | null; remote?: boolean;+ /** Skip the tombstone and register reads when the source never had a purge (begin's probe). */+ purgesPossible?: boolean;+}++const KIND_RANK: Record<string, number> = { coverage: 0, page: 1, fact: 2, take: 3, link: 4, link_transition: 5 };+const ASSERTING = /\.(asserted|revised|resolved|unresolved|adopted|transferred)$|^baseline$|^reconcile$/;++export function orderDrafts(drafts: BeliefEventDraft[]): BeliefEventDraft[] {+ return [...drafts].sort((a, b) => (a.stream ?? a.slug).localeCompare(b.stream ?? b.slug) || KIND_RANK[a.subjectKind]! - KIND_RANK[b.subjectKind]!+ || (a.subjectKey < b.subjectKey ? -1 : a.subjectKey > b.subjectKey ? 1 : 0) || a.eventType.localeCompare(b.eventType));+}++const isOwnerWrite = (ctx: AppendContext) => ctx.remote === false && isTrustTier(ctx.writerTier)+ && TRUST_TIER_RANK[ctx.writerTier] >= TRUST_TIER_RANK[OWNER_TIER_FLOOR];++/** Tombstoned fingerprints among the drafts' asserting events (fact_purges/take_purges match rules, subject '*' included). */+async function tombstoned(tx: BrainEngine, sourceId: string, drafts: BeliefEventDraft[]): Promise<Set<string>> {+ const facts = drafts.filter(d => d.subjectKind === 'fact' && d.claimFp && ASSERTING.test(d.eventType));+ const takes = drafts.filter(d => d.subjectKind === 'take' && d.claimFp && ASSERTING.test(d.eventType));+ if (!facts.length && !takes.length) return new Set();+ const rows = await tx.executeRaw<{ fp: string }>(`SELECT fact_hash AS fp FROM fact_purges WHERE source_id = $1 AND fact_hash = ANY($2::text[])+ UNION SELECT claim_hash AS fp FROM take_purges WHERE source_id = $1 AND claim_hash = ANY($3::text[])`,+ [sourceId, facts.map(d => d.claimFp!), takes.map(d => d.claimFp!)]);+ return new Set(rows.map(r => r.fp));+}++interface Suppression { id: number; subject_key: string; field: string; purge_request: string; field_hash: string; released_hash: string | null }++/**+ * Applies the redaction register to the drafts' carrying fields and records+ * releases and successor copies. Returns each draft's redacted field list.+ */+async function applyRedactions(tx: BrainEngine, sourceId: string, drafts: BeliefEventDraft[], ctx: AppendContext): Promise<Map<BeliefEventDraft, string[]>> {+ const redacted = new Map<BeliefEventDraft, string[]>();+ const carrying = drafts.filter(d => d.value && CARRYING_FIELDS[d.subjectKind]?.some(f => typeof d.value![f] === 'string' && d.value![f] !== ''));+ if (!carrying.length) return redacted;+ const predecessors = carrying.map(d => (d.cause.replaces ?? d.cause.from_key) as string | undefined).filter((k): k is string => !!k);+ const hashes = carrying.flatMap(d => CARRYING_FIELDS[d.subjectKind]!.map(f => d.value![f]).filter((v): v is string => typeof v === 'string' && v !== '').map(fieldHash));+ const rows = await tx.executeRaw<Suppression>(`SELECT id, subject_key, field, purge_request::text AS purge_request, field_hash, released_hash+ FROM belief_redactions WHERE source_id = $1 AND (subject_key = ANY($2::text[]) OR field_hash = ANY($3::text[]))`,+ [sourceId, [...carrying.map(d => d.subjectKey), ...predecessors], hashes]);+ if (!rows.length) return redacted;+ const owner = isOwnerWrite(ctx);+ for (const draft of carrying) {+ const predecessor = (draft.cause.replaces ?? draft.cause.from_key) as string | undefined;+ for (const field of CARRYING_FIELDS[draft.subjectKind]!) {+ const text = draft.value![field];+ if (typeof text !== 'string' || text === '') continue;+ const hash = fieldHash(text);+ const own = rows.filter(r => r.field === field && r.subject_key === draft.subjectKey);+ const inherited = predecessor ? rows.filter(r => r.field === field && r.subject_key === predecessor && r.released_hash == null) : [];+ const copied = rows.filter(r => r.field === field && r.field_hash === hash && r.released_hash == null && r.subject_key !== draft.subjectKey);+ for (const s of [...inherited, ...copied]) {+ if (own.some(o => o.purge_request === s.purge_request)) continue;+ const [row] = await tx.executeRaw<{ id: number }>(`INSERT INTO belief_redactions (source_id, subject_key, field, purge_request, field_hash)+ VALUES ($1, $2, $3, $4::uuid, $5) RETURNING id`, [sourceId, draft.subjectKey, field, s.purge_request, s.field_hash]);+ own.push({ ...s, id: Number(row!.id), subject_key: draft.subjectKey, released_hash: null });+ }+ if (!own.length) continue;+ if (own.every(s => s.released_hash === hash)) continue;+ if (owner) {+ await tx.executeRaw('UPDATE belief_redactions SET released_by = $2::uuid, released_hash = $3 WHERE id = ANY($1::bigint[])',+ [own.map(s => s.id), ctx.publicationId, hash]);+ continue;+ }+ draft.value = { ...draft.value!, [field]: REDACTION_MARKER(own[0]!.purge_request) };+ redacted.set(draft, [...redacted.get(draft) ?? [], field]);+ }+ }+ return redacted;+}++export async function appendBeliefEvents(tx: BrainEngine, drafts: BeliefEventDraft[], ctx: AppendContext): Promise<number> {+ if (!drafts.length) return 0;+ const ordered = orderDrafts(drafts);+ const sourceId = ordered[0]!.sourceId;+ const purgedFps = ctx.purgesPossible === false ? new Set<string>() : await tombstoned(tx, sourceId, ordered);+ const redactions = ctx.purgesPossible === false ? new Map<BeliefEventDraft, string[]>() : await applyRedactions(tx, sourceId, ordered, ctx);+ const rows = ordered.map((d, ord) => {+ const purged = d.purged === true || (!!d.claimFp && purgedFps.has(d.claimFp) && ASSERTING.test(d.eventType));+ const value = purged ? null : d.value;+ return {+ event_key: eventKeyHex(ctx.publicationId, d.subjectKey, d.eventType), source_id: d.sourceId, source_incarnation: d.incarnation,+ page_lifetime: d.lifetime, slug: d.slug, subject_kind: d.subjectKind, subject_key: d.subjectKey, event_type: d.eventType, origin: ctx.origin,+ trust_tier: d.trustTier, writer_tier: d.writerTier && d.writerTier !== d.trustTier ? d.writerTier : null, tier_basis: d.tierBasis ?? 'row',+ visibility: d.visibility, publication_id: ctx.publicationId, ord, source_time: d.sourceTime ?? null, valid_from: d.validFrom ?? null,+ valid_until: d.validUntil ?? null, value: value == null ? null : canonicalJson(value), value_hash: value == null ? null : valueHash(value),+ prior_hash: d.priorHash ?? null, state_hash: d.stateHash, cause: canonicalJson(d.cause), claim_fp: d.claimFp ?? null, purged,+ redacted_fields: redactions.get(d) ?? null,+ };+ });+ const inserted = await tx.executeRaw<{ id: number }>(`INSERT INTO belief_events (event_key, source_id, source_incarnation, page_lifetime, slug, subject_kind,+ subject_key, event_type, origin, trust_tier, writer_tier, tier_basis, visibility, publication_id, ord, source_time, valid_from, valid_until,+ value, value_hash, prior_hash, state_hash, cause, claim_fp, purged, redacted_fields)+ SELECT decode(r.event_key, 'hex'), r.source_id, r.source_incarnation::uuid, r.page_lifetime::uuid, r.slug, r.subject_kind, r.subject_key, r.event_type,+ r.origin, r.trust_tier, r.writer_tier, r.tier_basis, r.visibility, r.publication_id::uuid, r.ord, r.source_time::timestamptz,+ r.valid_from::timestamptz, r.valid_until::timestamptz, r.value::jsonb, r.value_hash, r.prior_hash, r.state_hash, r.cause::jsonb, r.claim_fp,+ r.purged, r.redacted_fields+ FROM jsonb_to_recordset($1::text::jsonb) AS r(event_key text, source_id text, source_incarnation text, page_lifetime text, slug text,+ subject_kind text, subject_key text, event_type text, origin text, trust_tier text, writer_tier text, tier_basis text, visibility text,+ publication_id text, ord integer, source_time text, valid_from text, valid_until text, value text, value_hash text, prior_hash text,+ state_hash text, cause text, claim_fp text, purged boolean, redacted_fields text[])+ ORDER BY r.ord+ ON CONFLICT (event_key) DO NOTHING RETURNING id`, [JSON.stringify(rows)]);+ return inserted.length;+}++/**+ * The post-commit observation (section 5.3): `observed_at` is clock_timestamp()+ * in the statement that reads the committed event, never below its recorded_at.+ * Called after commit by each appender; readers that find an unmarked committed+ * publication call it too. A group's members share one statement and one time.+ */+export async function markBeliefCommits(engine: Pick<BrainEngine, 'executeRaw'>, publicationIds: readonly string[]): Promise<void> {+ if (!publicationIds.length) return;+ await engine.executeRaw(`INSERT INTO belief_commit_marks (publication_id, observed_at)+ SELECT e.publication_id, clock_timestamp() FROM belief_events e+ WHERE e.publication_id = ANY($1::uuid[])+ GROUP BY e.publication_id HAVING max(e.recorded_at) <= clock_timestamp()+ ON CONFLICT (publication_id) DO NOTHING`, [[...publicationIds]]);+}diff --git a/src/core/belief/coverage.ts b/src/core/belief/coverage.tsnew file mode 100644index 0000000000..1204cbeda7--- /dev/null+++ b/src/core/belief/coverage.ts@@ -0,0 +1,113 @@+/**+ * Coverage intervals and the activation baseline (docs/designs/BELIEF_LEDGER.md+ * section 7.1). `enableBeliefLedger` appends `coverage.started`, then baselines+ * each page under its own page key (one snapshot `baseline` event, or one per+ * subject for a page over 1 MiB) and each database-only subject under its slug+ * key, then appends `coverage.complete`, whose recorded_at is the source's+ * watermark. A run is resumable: a page whose baseline for the current run+ * exists is skipped. `disableBeliefLedger` appends `coverage.stopped`; the next+ * enable starts a new interval with a new baseline.+ */+import { randomUUID } from 'node:crypto';+import type { BrainEngine } from '../engine.ts';+import { COVERAGE_KEY, pageKey } from './keys.ts';+import { appendBeliefEvents, markBeliefCommits, type BeliefEventDraft } from './append.ts';+import { coverageActive, currentStateHash, readLedgerSource } from './ledger.ts';+import { keyedSubjects, type Subject } from './subjects.ts';++export interface CoverageRun { runId: string; resumed: boolean; pages: number; dbOnlySubjects: number; complete: boolean; certified: boolean }+const BASELINE_BATCH = 200;++/** The latest coverage event of the source's current incarnation. */+export async function latestCoverage(engine: BrainEngine, sourceId: string): Promise<{ type: string; run: string | null; recorded_at: string; id: number } | null> {+ const [row] = await engine.executeRaw<{ event_type: string; run: string | null; recorded_at: string; id: number }>(`SELECT e.event_type, e.cause->>'run' AS run, e.recorded_at, e.id+ FROM belief_events e JOIN sources s ON s.id = e.source_id AND s.incarnation = e.source_incarnation+ WHERE e.source_id = $1 AND e.subject_kind = 'coverage' AND e.subject_key = $2 ORDER BY e.id DESC LIMIT 1`, [sourceId, COVERAGE_KEY]);+ return row ? { type: row.event_type, run: row.run, recorded_at: new Date(row.recorded_at).toISOString(), id: Number(row.id) } : null;+}++async function appendCoverage(engine: BrainEngine, sourceId: string, eventType: string, cause: Record<string, unknown>): Promise<void> {+ const publicationId = randomUUID();+ await engine.transaction(async tx => {+ const source = await readLedgerSource(tx, sourceId);+ if (!source) throw new Error(`source not found: ${sourceId}`);+ await tx.executeRaw('SELECT id FROM sources WHERE id = $1 FOR UPDATE', [sourceId]);+ await appendBeliefEvents(tx, [{ sourceId, incarnation: source.incarnation, lifetime: null, slug: '', subjectKind: 'coverage', subjectKey: COVERAGE_KEY,+ eventType, trustTier: 'unknown', tierBasis: 'unknown', visibility: 'world', value: null, stateHash: '', cause: { op: eventType, ...cause } }],+ { publicationId, origin: 'live', purgesPossible: false });+ });+ await markBeliefCommits(engine, [publicationId]);+}++/** One page's baseline under its key, in the same form as a creation snapshot (or per subject when over 1 MiB). */+async function baselinePage(engine: BrainEngine, sourceId: string, slug: string, runId: string): Promise<boolean> {+ const publicationId = randomUUID();+ const appended = await engine.transaction(async tx => {+ await tx.lockPageKeys([{ sourceId, slug }]);+ const source = await readLedgerSource(tx, sourceId);+ if (!source || !coverageActive(source.coverage)) return 0;+ const { hash, state, lifetimes } = await currentStateHash(tx, sourceId, source.incarnation, slug);+ const page = state.pages.find(p => p.slug === slug);+ const subjects = keyedSubjects({ incarnation: source.incarnation, lifetimes, pagesBySlug: new Map(page ? [[slug, page]] : []) }, state,+ id => state.pages.find(p => p.id === id)?.visible === false ? 'private' : 'world').filter(s => s.stream === slug);+ const lifetime = page ? lifetimes.get(page.id)! : null;+ const cause = { op: 'baseline', run: runId };+ const drafts: BeliefEventDraft[] = [];+ const perSubject = (list: Subject[]) => list.map((s): BeliefEventDraft => ({ sourceId, incarnation: source.incarnation, lifetime: s.dbOnly && !page ? null : lifetime,+ slug, stream: slug, subjectKind: s.kind, subjectKey: s.key, eventType: 'baseline', trustTier: s.kind === 'link' || s.kind === 'link_transition' ? 'unknown' : s.tier,+ tierBasis: s.kind === 'link' || s.kind === 'link_transition' ? 'unknown' : 'row', visibility: s.visibility, value: s.value, stateHash: hash,+ claimFp: s.claimFp, validFrom: s.validFrom, validUntil: s.validUntil, cause: { ...cause, ...(s.rowNum != null ? { row: s.rowNum } : {}), label: s.label } }));+ if (page) {+ const bound = subjects.filter(s => !s.dbOnly);+ const counts = { facts: bound.filter(s => s.kind === 'fact').length, takes: bound.filter(s => s.kind === 'take').length,+ links: bound.filter(s => s.kind === 'link').length, link_transitions: bound.filter(s => s.kind === 'link_transition').length };+ drafts.push({ sourceId, incarnation: source.incarnation, lifetime, slug, stream: slug, subjectKind: 'page', subjectKey: pageKey(lifetime!), eventType: 'baseline',+ trustTier: page.tier, visibility: page.visible ? 'world' : 'private', value: { revision_after: page.revision, snapshot: !page.large, counts, ...(page.deleted ? { deleted: true } : {}) },+ stateHash: hash, cause });+ if (page.large) drafts.push(...perSubject(bound));+ }+ drafts.push(...perSubject(subjects.filter(s => s.dbOnly)));+ return appendBeliefEvents(tx, drafts, { publicationId, origin: 'baseline', purgesPossible: source.purgesPossible });+ });+ if (appended) await markBeliefCommits(engine, [publicationId]);+ return appended > 0;+}++/** Slugs of the source still lacking a baseline in this run: live and soft-deleted pages, then page-less database-only fact subjects. */+async function pendingSlugs(engine: BrainEngine, sourceId: string, runId: string, after: string): Promise<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+ ) 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);+}++export async function enableBeliefLedger(engine: BrainEngine, sourceId: string): Promise<CoverageRun> {+ const latest = await latestCoverage(engine, sourceId);+ const resumed = latest?.type === 'coverage.started' && !!latest.run;+ const runId = resumed ? latest!.run! : randomUUID();+ if (latest?.type === 'coverage.complete' || latest?.type === 'coverage.restored') {+ const source = await readLedgerSource(engine, sourceId);+ return { runId: latest.run ?? '', resumed: true, pages: 0, dbOnlySubjects: 0, complete: true, certified: !!source?.managed };+ }+ if (!resumed) await appendCoverage(engine, sourceId, 'coverage.started', { run: runId });+ let pages = 0;+ let after = '';+ for (;;) {+ const slugs = await pendingSlugs(engine, sourceId, runId, after);+ if (!slugs.length) break;+ for (const slug of slugs) if (await baselinePage(engine, sourceId, slug, runId)) pages++;+ after = slugs[slugs.length - 1]!;+ }+ const source = await readLedgerSource(engine, sourceId);+ await appendCoverage(engine, sourceId, 'coverage.complete', { run: runId, certified: !!source?.managed });+ return { runId, resumed, pages, dbOnlySubjects: 0, complete: true, certified: !!source?.managed };+}++export async function disableBeliefLedger(engine: BrainEngine, sourceId: string): Promise<boolean> {+ const latest = await latestCoverage(engine, sourceId);+ if (!latest || latest.type === 'coverage.stopped') return false;+ await appendCoverage(engine, sourceId, 'coverage.stopped', { run: latest.run });+ return true;+}diff --git a/src/core/belief/keys.ts b/src/core/belief/keys.tsnew file mode 100644index 0000000000..fe66317956--- /dev/null+++ b/src/core/belief/keys.ts@@ -0,0 +1,57 @@+/**+ * Logical subject keys and hashes of the belief ledger (docs/designs/BELIEF_LEDGER.md+ * section 3). A key never contains a row id: page-backed slug components are+ * serialized as the page lifetime (`L:<uuid>`), a slug that names no page as+ * `S:<source_incarnation>:<slug>`. Append, replay, subject lookup and state_hash+ * all use this one serialization.+ */+import { createHash } from 'node:crypto';++/** The fact fingerprint version the key carries (gbrain_fact_fingerprint, re-versioned once). */+export const FACT_FP_VERSION = 2;+export const COVERAGE_KEY = '["coverage"]';+/** The carrying fields a purge can redact, per subject kind (section 6.5). */+export const CARRYING_FIELDS: Readonly<Record<string, readonly string[]>> = { fact: ['context'], take: ['resolved_source'], link: ['context'] };+export const REDACTION_MARKER = (purgeRequest: string) => `[redacted: purge ${purgeRequest}]`;++export type SubjectRef = string;+export const lifetimeRef = (lifetime: string): SubjectRef => `L:${lifetime}`;+export const slugRef = (incarnation: string, slug: string): SubjectRef => `S:${incarnation}:${slug}`;+export const isSlugRef = (ref: SubjectRef) => ref.startsWith('S:');++export const pageKey = (lifetime: string) => JSON.stringify(['p', lifetimeRef(lifetime)]);+export const factKey = (subject: SubjectRef, fingerprint: string, visibility: string) => JSON.stringify(['f', subject, FACT_FP_VERSION, fingerprint, visibility]);+export const ontologyKey = (entity: SubjectRef, dimension: string, valueHash: string, origin: SubjectRef | null, validFrom: string | null) =>+ JSON.stringify(['o', entity, dimension, valueHash, origin, validFrom]);+export const takeKey = (lifetime: string, claimHash: string, ordinal: number) => JSON.stringify(['t', lifetimeRef(lifetime), claimHash, ordinal]);+export const linkKey = (from: SubjectRef, to: SubjectRef, linkType: string, linkSource: string | null, origin: SubjectRef | null) =>+ JSON.stringify(['l', from, to, linkType, linkSource, origin]);+export const transitionKey = (link: string, kind: string, occurredOn: string, producer: string) => JSON.stringify(['lt', JSON.parse(link), kind, occurredOn, producer]);+export const heldKey = (kind: string, fingerprint: string) => JSON.stringify(['h', kind, fingerprint]);++/** Replace the subject component of a fact key (adoption moves `S:` to `L:`). */+export function factKeySubject(key: string): { subject: SubjectRef; rest: string } | null {+ const parsed = JSON.parse(key) as unknown[];+ if (parsed[0] !== 'f') return null;+ return { subject: String(parsed[1]), rest: JSON.stringify(parsed.slice(2)) };+}++export function sha256Hex(text: string): string {+ return createHash('sha256').update(text).digest('hex');+}++/** Canonical JSON: object keys sorted at every depth, so equal values hash equally. */+export function canonicalJson(value: unknown): string {+ if (value === null || typeof value !== 'object') return JSON.stringify(value ?? null);+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;+ const entries = Object.entries(value as Record<string, unknown>).filter(([, v]) => v !== undefined).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`).join(',')}}`;+}++export const valueHash = (value: unknown) => sha256Hex(canonicalJson(value));+export const takeClaimHash = (claim: string, kind: string, holder: string) => sha256Hex(canonicalJson([claim, kind, holder]));+export const fieldHash = (text: string) => sha256Hex(`field:${text}`);++/** event_key = sha256(publication_id ‖ subject_key ‖ event_type), hex for transport, BYTEA at rest. */+export const eventKeyHex = (publicationId: string, subjectKey: string, eventType: string) =>+ sha256Hex(`${publicationId}\u0000${subjectKey}\u0000${eventType}`);diff --git a/src/core/belief/ledger.ts b/src/core/belief/ledger.tsnew file mode 100644index 0000000000..c68a131c8b--- /dev/null+++ b/src/core/belief/ledger.ts@@ -0,0 +1,361 @@+/**+ * The finalization contract (docs/designs/BELIEF_LEDGER.md section 5.1).+ *+ * Every transaction that commits canonical state wraps its projections in+ * `withBeliefBatch`: the batch reads the logical state of its streams under the+ * page keys the transaction already holds, runs the projections, reads the+ * state again, and `finalizeBeliefEvents` appends one event per logical key+ * whose canonical value changed, last, before the terminal receipt. Guards+ * that decide inside the projections (contest, hold) and identity code paths+ * report through `noteBelief`, so their events exist whether or not any row+ * changed. The batch is inert, and costs one source read, when the source has+ * no active coverage (`gbrain beliefs enable`).+ */+import { AsyncLocalStorage } from 'node:async_hooks';+import { randomUUID } from 'node:crypto';+import type { BrainEngine } from '../engine.ts';+import { assertHeldPageKeys } from '../page-state/guards.ts';+import { COVERAGE_KEY, heldKey, pageKey, sha256Hex, canonicalJson, factKeySubject, slugRef } from './keys.ts';+import { readBeliefState, readFactsById, type RawPage, type RawState } from './state.ts';+import { keyedSubjects, keyFact, pageNeeds, type KeyContext, type Subject } from './subjects.ts';+import { endLifetime, mintLifetime, readOpenLifetimes, renameLifetime, resolveLifetimes } from './lifetimes.ts';+import { appendBeliefEvents, type BeliefEventDraft, type BeliefOrigin } from './append.ts';++export type BeliefNote =+ | { kind: 'contested'; table: string; rowId: number; proposalId: number; guard: string }+ | { kind: 'held'; holdKind: string; fingerprint: string; holdId: number; slug: string; tier: string; valueHash: string }+ | { 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[] };++export interface BeliefBatchOptions {+ sourceId: string;+ /** Stream slugs; every one must be a page key the transaction holds. */+ slugs: readonly string[];+ /** persistence_requests.id for journaled writes; a fresh UUID per transaction otherwise. */+ publicationId?: string | null;+ op: string;+ /** Overrides the managed/unmanaged origin (an unmanaged projection point passes 'unmanaged'). */+ origin?: BeliefOrigin;+ /** A revision change is `page.published` unless the writer names it (revert). */+ pageEventType?: 'page.reverted' | 'page.view_changed' | 'page.merged';+ /** The event for a page row that is gone after the transaction: purge or retention, else `page.deleted`. */+ hardDeleteEvent?: 'page.purged' | 'page.expired';+ /** Request authority: an owner release of a redaction needs a trusted local (remote = false) write. */+ remote?: boolean;+ cause?: Record<string, unknown>;+ /** Filled by the batch: how many events it appended, so the caller marks the commit only when there is one. */+ report?: { appended: number };+}++interface Batch {+ opts: BeliefBatchOptions; publicationId: string; incarnation: string; managed: boolean; purgesPossible: boolean;+ pre: RawState; notes: BeliefNote[];+}++const store = new AsyncLocalStorage<Batch>();++/** A guard or identity path reports a decision to the enclosing batch; a no-op outside one. */+export function noteBelief(note: BeliefNote): void {+ store.getStore()?.notes.push(note);+}++/** 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,+ (SELECT e.event_type FROM belief_events e WHERE e.source_id = s.id AND e.subject_kind = 'coverage' AND e.subject_key = $2+ AND e.source_incarnation = s.incarnation ORDER BY e.id DESC LIMIT 1) AS coverage,+ COALESCE((SELECT b.enabled FROM persistence_brain b WHERE b.singleton = 1), false) AS managed,+ (s.purge_epoch > 0 OR EXISTS (SELECT 1 FROM fact_purges WHERE source_id = s.id) OR EXISTS (SELECT 1 FROM take_purges WHERE source_id = s.id)+ OR EXISTS (SELECT 1 FROM page_purges WHERE source_id = s.id)) AS purges+ FROM sources s WHERE s.id = $1`, [sourceId, COVERAGE_KEY]);+ if (!row) return null;+ return { incarnation: String(row.incarnation), purgeEpoch: Number(row.purge_epoch), coverage: (row.coverage as string | null) ?? null,+ managed: row.managed === true, purgesPossible: row.purges === true };+}++export const coverageActive = (coverage: string | null) => coverage != null && coverage !== 'coverage.stopped';++async function beginBeliefBatch(tx: BrainEngine, opts: BeliefBatchOptions): Promise<Batch | null> {+ const source = await readLedgerSource(tx, opts.sourceId);+ if (!source || !coverageActive(source.coverage)) return null;+ assertHeldPageKeys(tx, opts.slugs.map(slug => ({ sourceId: opts.sourceId, slug })));+ const pre = await readBeliefState(tx, opts.sourceId, opts.slugs);+ return { opts, publicationId: opts.publicationId ?? randomUUID(), incarnation: source.incarnation, managed: source.managed,+ purgesPossible: source.purgesPossible, pre, notes: [] };+}++/** Runs `fn` (the transaction's projections) inside a belief batch and appends its events after it. */+export async function withBeliefBatch<T>(tx: BrainEngine, opts: BeliefBatchOptions, fn: () => Promise<T>): Promise<T> {+ const batch = await beginBeliefBatch(tx, opts);+ if (!batch) return fn();+ const result = await store.run(batch, fn);+ const appended = await finalizeBeliefEvents(tx, batch);+ if (opts.report) opts.report.appended += appended;+ return result;+}++interface Stream { slug: string; pre: RawPage | null; post: RawPage | null }++/** Stream pages matched by id across the transaction: renames, recreates and hard deletes. */+function matchStreams(slugs: readonly string[], pre: RawState, post: RawState): Stream[] {+ const preById = new Map(pre.pages.map(p => [p.id, p]));+ const postIds = new Set(post.pages.map(p => p.id));+ const streams: Stream[] = [];+ const used = new Set<number>();+ for (const page of post.pages) {+ const same = preById.get(page.id);+ const other = same ? null : pre.pages.find(p => p.slug === page.slug && !postIds.has(p.id)) ?? null;+ if (same) used.add(same.id);+ if (other) { used.add(other.id); streams.push({ slug: page.slug, pre: other, post: null }); }+ streams.push({ slug: page.slug, pre: same ?? null, post: page });+ }+ for (const page of pre.pages) if (!used.has(page.id)) streams.push({ slug: page.slug, pre: page, post: null });+ for (const slug of slugs) if (!streams.some(s => s.slug === slug || s.pre?.slug === slug)) streams.push({ slug, pre: null, post: null });+ return streams;+}++/** Ends, renames and mints the stream pages' lifetimes; returns page id -> lifetime for both sides. */+async function streamLifetimes(tx: BrainEngine, sourceId: string, incarnation: string, streams: Stream[]): Promise<Map<number, string>> {+ const out = new Map<number, string>();+ const pairs = streams.flatMap(s => [s.pre, s.post]).filter((p): p is RawPage => !!p).map(p => ({ incarnation, slug: p.slug }));+ const open = await readOpenLifetimes(tx, pairs);+ const openAt = (slug: string) => open.get(`${incarnation}\u0000${slug}`) ?? null;+ const fits = (row: { page_id: number | null } | null, id: number) => !!row && (row.page_id == null || row.page_id === id);+ const mint = (page: RawPage) => mintLifetime(tx, { sourceId, incarnation, slug: page.slug, pageId: page.id });+ for (const { pre, post } of streams) {+ if (!pre || post) continue;+ const row = openAt(pre.slug);+ const lifetime = fits(row, pre.id) ? row!.page_lifetime : await mint(pre);+ out.set(pre.id, lifetime);+ await endLifetime(tx, lifetime);+ }+ for (const { pre, post } of streams) {+ if (!post) continue;+ const row = openAt(pre?.slug ?? post.slug);+ if (pre && pre.slug !== post.slug) {+ const target = openAt(post.slug);+ if (target && target.page_lifetime !== row?.page_lifetime) await endLifetime(tx, target.page_lifetime);+ if (fits(row, post.id)) { await renameLifetime(tx, row!.page_lifetime, post.slug, post.id); out.set(post.id, row!.page_lifetime); }+ else out.set(post.id, await mint(post));+ continue;+ }+ if (row && row.page_id === post.id) { out.set(post.id, row.page_lifetime); continue; }+ if (pre && row && row.page_id == null) { out.set(post.id, row.page_lifetime); continue; }+ if (row) await endLifetime(tx, row.page_lifetime);+ out.set(post.id, await mint(post));+ }+ return out;+}++const tierOrUnknown = (tier: string | null | undefined) => tier || 'unknown';++function stateHashOf(page: RawPage | null, lifetime: string | null, subjects: Subject[]): string {+ const live = page && !page.deleted;+ return sha256Hex(canonicalJson({+ page: page ? { lifetime, deleted: page.deleted, revision: page.revision, visible: page.visible, tier: page.tier } : null,+ subjects: subjects.filter(s => live || s.dbOnly).map(s => [s.kind, s.key, s.vhash, s.tier]).sort((a, b) => (a.join('\u0000') < b.join('\u0000') ? -1 : 1)),+ }));+}++function changeType(kind: Subject['kind'], before: Subject, after: Subject): string | null {+ if (before.vhash === after.vhash) return null;+ if (kind === 'take') {+ const resolution = ['resolved_at', 'resolved_outcome', 'resolved_value', 'resolved_unit', 'resolved_source', 'resolved_by', 'resolved_quality']+ .some(f => canonicalJson(before.value[f]) !== canonicalJson(after.value[f]));+ const resolvedAfter = after.value.resolved_at != null || after.value.resolved_quality != null;+ if (resolution) return resolvedAfter ? 'take.resolved' : 'take.unresolved';+ return 'take.revised';+ }+ if (kind === 'link_transition') return 'link.transition_revised';+ return `${kind}.revised`;+}+const assertType = (kind: Subject['kind']) => kind === 'link_transition' ? 'link.transition_added' : `${kind}.asserted`;+const retractType = (kind: Subject['kind']) => kind === 'link_transition' ? 'link.transition_removed' : `${kind}.retracted`;++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[];+}++/** Subject events of one stream side: asserted/retracted/revised, adoption, replacement links, retiering. */+function subjectDrafts(d: DiffContext, slug: string, before: Subject[], after: Subject[]): BeliefEventDraft[] {+ const { batch, writerTier } = d;+ const withdrawn = new Set(batch.notes.flatMap(n => n.kind === 'withdrawn' ? n.factIds : []));+ const superseded = new Map(batch.notes.flatMap(n => n.kind === 'superseded' ? [[n.oldId, n.newId] as const] : []));+ const purged = new Map(batch.notes.flatMap(n => n.kind === 'purged' ? n.ids.map(id => [`${n.table}:${id}`, n.request] as const) : []));+ const out: BeliefEventDraft[] = [];+ const preMap = new Map(before.map(s => [`${s.kind}\u0000${s.key}`, s]));+ const postMap = new Map(after.map(s => [`${s.kind}\u0000${s.key}`, s]));+ const draft = (s: Subject, eventType: string, value: Record<string, unknown> | null, prior: Subject | null, extra: Record<string, unknown> = {}) => {+ const link = s.kind === 'link' || s.kind === 'link_transition';+ out.push({ sourceId: d.opts.sourceId, incarnation: batch.incarnation, lifetime: d.lifetimeAt(slug), slug, stream: slug,+ subjectKind: s.kind, subjectKey: s.key, eventType, trustTier: link ? writerTier : s.tier, writerTier: link ? null : writerTier,+ tierBasis: link ? 'writer' : 'row', visibility: s.visibility, value, priorHash: prior?.vhash ?? null, stateHash: d.streamHash(slug),+ 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 fresh = [...postMap].filter(([id]) => !preMap.has(id)).map(([, s]) => s);+ const adoptedFrom = new Map<Subject, Subject>();+ for (const s of fresh) {+ const parts = s.kind === 'fact' ? factKeySubject(s.key) : null;+ if (!parts || parts.subject.startsWith('S:')) continue;+ const source = removed.find(r => r.kind === 'fact' && factKeySubject(r.key)?.subject === slugRef(batch.incarnation, slug) && factKeySubject(r.key)?.rest === parts.rest);+ if (source) adoptedFrom.set(s, source);+ }+ const adoptedSources = new Set(adoptedFrom.values());+ const replacedBy = new Map<Subject, Subject>();+ for (const r of removed) {+ if ((r.kind !== 'fact' && r.kind !== 'take') || r.rowNum == null || adoptedSources.has(r)) continue;+ const successor = fresh.find(s => s.kind === r.kind && s.rowNum === r.rowNum && !adoptedFrom.has(s));+ if (successor) replacedBy.set(r, successor);+ }+ for (const r of removed) {+ if (adoptedSources.has(r)) continue;+ const purgeRequest = r.rowIds.map(id => purged.get(`${r.kind === 'take' ? 'takes' : 'facts'}:${id}`)).find(Boolean);+ const supersededBy = r.kind === 'fact' ? r.rowIds.map(id => superseded.get(id)).find(v => v !== undefined) : undefined;+ const type = purgeRequest ? `${r.kind}.purged` : r.kind === 'fact' && r.rowIds.some(id => withdrawn.has(id)) ? 'fact.withdrawn'+ : supersededBy !== undefined ? 'fact.superseded' : retractType(r.kind);+ const successorKey = supersededBy != null ? d.postSubjects.find(s => s.kind === 'fact' && s.rowIds.includes(supersededBy))?.key : replacedBy.get(r)?.key;+ draft(r, type, null, r, { ...(successorKey ? { replaced_by: successorKey } : {}), ...(purgeRequest ? { purge_request: purgeRequest } : {}) });+ }+ for (const s of fresh) {+ 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];+ draft(s, assertType(s.kind), s.value, null, replaced ? { replaces: replaced.key } : {});+ }+ for (const [id, s] of postMap) {+ const prior = preMap.get(id);+ if (!prior) 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);+ }+ return out;+}++/** The page event of one page stream; `true` when the page's own subjects end or begin with it (no per-subject events). */+function pageDrafts(d: DiffContext, stream: Stream, lifetime: string, after: Subject[], push: (draft: BeliefEventDraft) => void): boolean {+ const { pre: p0, post: p1 } = stream;+ const page = p1 ?? p0!;+ const base = { sourceId: d.opts.sourceId, incarnation: d.batch.incarnation, lifetime, slug: page.slug, stream: page.slug, subjectKind: 'page' as const,+ subjectKey: pageKey(lifetime), writerTier: d.writerTier, visibility: page.visible ? 'world' : 'private', stateHash: d.streamHash(page.slug), cause: d.cause() };+ const emit = (eventType: string, value: Record<string, unknown>, tier: string) => push({ ...base, eventType, trustTier: tier, value });+ if (p0 && !p1) {+ emit(d.opts.hardDeleteEvent ?? 'page.deleted', { revision_before: p0.revision, hard: true }, p0.tier);+ return true;+ }+ if (!p0 && p1) {+ const counts = { facts: after.filter(s => s.kind === 'fact').length, takes: after.filter(s => s.kind === 'take').length,+ links: after.filter(s => s.kind === 'link').length, link_transitions: after.filter(s => s.kind === 'link_transition').length };+ emit('page.published', { revision_before: null, revision_after: p1.revision, snapshot: !p1.large, counts, ...(p1.deleted ? { deleted: true } : {}) }, p1.tier);+ return !p1.large;+ }+ let silenced = false;+ if (p0!.slug !== p1!.slug) emit('page.renamed', { old_slug: p0!.slug, new_slug: p1!.slug }, p1!.tier);+ if (!p0!.deleted && p1!.deleted) { emit('page.deleted', { revision_before: p0!.revision, revision_after: p1!.revision }, p0!.tier); silenced = true; }+ 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);+ if (p0!.tier !== p1!.tier) emit('trust.retiered', { from: p0!.tier, to: p1!.tier }, p1!.tier);+ return silenced || (p0!.deleted && p1!.deleted);+}++/** Appends the batch's events, last in its transaction. */+export async function finalizeBeliefEvents(tx: BrainEngine, batch: Batch): Promise<number> {+ const { opts, pre } = batch;+ const post = await readBeliefState(tx, opts.sourceId, opts.slugs, pre.pages.map(p => p.id));+ const streams = matchStreams(opts.slugs, pre, post);+ const added = streams.filter(s => s.post && !opts.slugs.includes(s.post.slug)).map(s => ({ sourceId: opts.sourceId, slug: s.post!.slug }));+ if (added.length) assertHeldPageKeys(tx, added);+ const writerTier = tierOrUnknown(post.writerTier ?? pre.writerTier);+ const lifetimes = await streamLifetimes(tx, opts.sourceId, batch.incarnation, streams);+ const contestedFactIds = batch.notes.flatMap(n => n.kind === 'contested' && n.table === 'facts' ? [n.rowId] : []);+ const extraFacts = await readFactsById(tx, contestedFactIds.filter(id => !post.facts.some(f => f.id === id) && !pre.facts.some(f => f.id === id)));+ const needs = [...pageNeeds(opts.sourceId, batch.incarnation, pre), ...pageNeeds(opts.sourceId, batch.incarnation, post),+ ...extraFacts.flatMap(f => f.entity_page_id != null && f.entity_slug ? [{ sourceId: opts.sourceId, incarnation: batch.incarnation, slug: f.entity_slug, pageId: f.entity_page_id }] : [])]+ .filter(n => !lifetimes.has(n.pageId));+ for (const [id, lifetime] of await resolveLifetimes(tx, needs)) lifetimes.set(id, lifetime);+ const visibilityIn = (state: RawState) => (pageId: number) => state.pages.find(p => p.id === pageId)?.visible === false ? 'private' : 'world';+ const ctx = (side: 'pre' | 'post'): KeyContext => ({ incarnation: batch.incarnation, lifetimes,+ pagesBySlug: new Map(streams.flatMap(s => { const p = side === 'pre' ? s.pre : s.post; return p ? [[p.slug, p] as const] : []; })) });+ const preSubjects = keyedSubjects(ctx('pre'), pre, visibilityIn(pre));+ const postSubjects = keyedSubjects(ctx('post'), post, visibilityIn(post));+ 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,+ cause: (extra = {}) => ({ op: opts.op, ...(opts.publicationId ? { request: opts.publicationId } : {}), ...opts.cause, ...extra }) };+ const drafts: BeliefEventDraft[] = [];++ for (const stream of streams) {+ const page = stream.post ?? stream.pre;+ if (!page) continue;+ const before = stream.pre ? preSubjects.filter(s => !s.dbOnly && s.stream === stream.pre!.slug) : [];+ const after = stream.post ? postSubjects.filter(s => !s.dbOnly && s.stream === stream.post!.slug) : [];+ const silenced = pageDrafts(d, stream, lifetimes.get(page.id)!, after, draft => drafts.push(draft));+ if (!silenced) drafts.push(...subjectDrafts(d, page.slug, before, after));+ }+ const dbSlugs = new Set([...preSubjects, ...postSubjects].filter(s => s.dbOnly).map(s => s.stream));+ for (const slug of dbSlugs) drafts.push(...subjectDrafts(d, slug, preSubjects.filter(s => s.dbOnly && s.stream === slug), postSubjects.filter(s => s.dbOnly && s.stream === slug)));++ for (const note of batch.notes) {+ if (note.kind === 'contested') drafts.push(...contestedDraft(d, note, { pre, post, preSubjects, postSubjects, extraFacts, lifetimes }));+ else if (note.kind === 'held') {+ const page = postPageAt(note.slug);+ drafts.push({ sourceId: opts.sourceId, incarnation: batch.incarnation, lifetime: lifetimeAt(note.slug), slug: note.slug, stream: note.slug,+ subjectKind: note.holdKind === 'take' ? 'take' : 'fact', subjectKey: heldKey(note.holdKind, note.fingerprint), eventType: 'trust.held',+ trustTier: note.tier, tierBasis: 'writer', visibility: page && !page.visible ? 'private' : 'world', value: { value_hash: note.valueHash },+ stateHash: streamHash(note.slug), cause: d.cause({ hold: `wh${note.holdId}` }) });+ }+ }+ return appendBeliefEvents(tx, drafts, { publicationId: batch.publicationId, origin: opts.origin ?? (batch.managed ? 'live' : 'unmanaged'),+ writerTier, remote: opts.remote, purgesPossible: batch.purgesPossible });+}++/** `trust.contested` on the held row's key: its tier as trust_tier, the challenger's as writer_tier (section 6.1). */+function contestedDraft(d: DiffContext, note: Extract<BeliefNote, { kind: 'contested' }>, s: { pre: RawState; post: RawState; preSubjects: Subject[];+ postSubjects: Subject[]; extraFacts: Awaited<ReturnType<typeof readFactsById>>; lifetimes: Map<number, string> }): BeliefEventDraft[] {+ const cause = d.cause({ proposal: `tp${note.proposalId}`, guard: note.guard });+ const base = { sourceId: d.opts.sourceId, incarnation: d.batch.incarnation, eventType: 'trust.contested', writerTier: d.writerTier, value: null };+ if (note.table === 'pages') {+ const page = s.post.pages.find(p => p.id === note.rowId) ?? s.pre.pages.find(p => p.id === note.rowId);+ if (!page) return [];+ return [{ ...base, lifetime: s.lifetimes.get(page.id)!, slug: page.slug, stream: page.slug, subjectKind: 'page', subjectKey: pageKey(s.lifetimes.get(page.id)!),+ trustTier: page.tier, visibility: page.visible ? 'world' : 'private', stateHash: d.streamHash(page.slug), cause }];+ }+ if (note.table !== 'facts' && note.table !== 'takes') return [];+ const kind = note.table === 'facts' ? 'fact' : 'take';+ const subject = [...s.postSubjects, ...s.preSubjects].find(x => x.kind === kind && x.rowIds.includes(note.rowId));+ if (subject) return [{ ...base, lifetime: d.lifetimeAt(subject.stream), slug: subject.stream, stream: subject.stream, subjectKind: kind, subjectKey: subject.key,+ trustTier: subject.tier, visibility: subject.visibility, claimFp: subject.claimFp, stateHash: d.streamHash(subject.stream), cause }];+ const fact = kind === 'fact' ? s.extraFacts.find(f => f.id === note.rowId) : undefined;+ if (!fact) return [];+ const stream = fact.sms ?? fact.entity_slug ?? '';+ const key = keyFact({ incarnation: d.batch.incarnation, lifetimes: s.lifetimes, pagesBySlug: new Map(s.post.pages.map(p => [p.slug, p])) }, fact).key;+ return [{ ...base, lifetime: d.lifetimeAt(stream), slug: stream, stream, subjectKind: 'fact', subjectKey: key, trustTier: fact.tier,+ visibility: fact.visibility, claimFp: fact.fp, stateHash: d.streamHash(stream), cause }];+}++/** The current belief-set hash of one stream, for the doctor drift check and reconcile. */+export async function currentStateHash(tx: BrainEngine, sourceId: string, incarnation: string, slug: string): Promise<{ hash: string; state: RawState; lifetimes: Map<number, string> }> {+ const state = await readBeliefState(tx, sourceId, [slug]);+ const lifetimes = await resolveLifetimes(tx, pageNeeds(sourceId, incarnation, state));+ const page = state.pages.find(p => p.slug === slug) ?? null;+ const ctx: KeyContext = { incarnation, lifetimes, pagesBySlug: new Map(page ? [[slug, page]] : []) };+ const subjects = keyedSubjects(ctx, state, id => state.pages.find(p => p.id === id)?.visible === false ? 'private' : 'world').filter(s => s.stream === slug);+ return { hash: stateHashOf(page, page ? lifetimes.get(page.id)! : null, subjects), state, lifetimes };+}++export { stateHashOf };++/** The batch options of one journaled page publication (single or group member). */+export function publicationBeliefOptions(row: { id: string; source_id: string; slug: string; operation: string; authority: { remote?: boolean } },+ additionalKeys: readonly { sourceId: string; slug: string }[] = [], report?: { appended: number }): BeliefBatchOptions {+ return { sourceId: row.source_id, slugs: [...new Set([row.slug, ...additionalKeys.filter(k => k.sourceId === row.source_id).map(k => k.slug)])],+ publicationId: row.id, op: row.operation, remote: row.authority.remote !== false,+ ...(row.operation === 'revert_version' ? { pageEventType: 'page.reverted' as const } : {}), ...(report ? { report } : {}) };+}diff --git a/src/core/belief/lifetimes.ts b/src/core/belief/lifetimes.tsnew file mode 100644index 0000000000..4ea8fe628e--- /dev/null+++ b/src/core/belief/lifetimes.ts@@ -0,0 +1,61 @@+/**+ * Page lifetimes (docs/designs/BELIEF_LEDGER.md section 3): the ledger's page+ * identity. Minted at a page's first need (its creation, baseline, or first+ * appearance as a link endpoint or entity), kept across a rename, ended by a+ * hard delete or a recreate at the same slug. `page_id` is a hint only: a+ * lifetime whose hint no longer matches the page at its slug belonged to a+ * page an untracked writer replaced, so it is ended and a new one minted.+ */+import { randomUUID } from 'node:crypto';+import type { BrainEngine } from '../engine.ts';++export interface PageRefNeed { sourceId: string; incarnation: string; slug: string; pageId: number }+interface LifetimeRow { page_lifetime: string; source_incarnation: string; slug: string; page_id: number | null }++const pairKey = (incarnation: string, slug: string) => `${incarnation}\u0000${slug}`;++export async function readOpenLifetimes(tx: BrainEngine, needs: readonly { incarnation: string; slug: string }[]): Promise<Map<string, LifetimeRow>> {+ if (!needs.length) return new Map();+ const rows = await tx.executeRaw<LifetimeRow>(`SELECT l.page_lifetime::text AS page_lifetime, l.source_incarnation::text AS source_incarnation, l.slug, l.page_id+ FROM belief_page_lifetimes l JOIN unnest($1::uuid[], $2::text[]) AS n(i, s) ON l.source_incarnation = n.i AND l.slug = n.s+ WHERE l.ended_at IS NULL`, [needs.map(n => n.incarnation), needs.map(n => n.slug)]);+ return new Map(rows.map(row => [pairKey(row.source_incarnation, row.slug), { ...row, page_id: row.page_id == null ? null : Number(row.page_id) }]));+}++export async function endLifetime(tx: BrainEngine, lifetime: string): Promise<void> {+ await tx.executeRaw('UPDATE belief_page_lifetimes SET ended_at = clock_timestamp() WHERE page_lifetime = $1::uuid AND ended_at IS NULL', [lifetime]);+}++export async function mintLifetime(tx: BrainEngine, need: PageRefNeed): Promise<string> {+ const lifetime = randomUUID();+ const [row] = await tx.executeRaw<{ page_lifetime: string }>(`INSERT INTO belief_page_lifetimes (page_lifetime, source_id, source_incarnation, slug, page_id)+ VALUES ($1::uuid, $2, $3::uuid, $4, $5) ON CONFLICT (source_incarnation, slug) WHERE ended_at IS NULL DO NOTHING RETURNING page_lifetime::text AS page_lifetime`,+ [lifetime, need.sourceId, need.incarnation, need.slug, need.pageId]);+ if (row) return row.page_lifetime;+ const [existing] = await tx.executeRaw<{ page_lifetime: string }>(`SELECT page_lifetime::text AS page_lifetime FROM belief_page_lifetimes+ WHERE source_incarnation = $1::uuid AND slug = $2 AND ended_at IS NULL`, [need.incarnation, need.slug]);+ return existing!.page_lifetime;+}++export async function renameLifetime(tx: BrainEngine, lifetime: string, slug: string, pageId: number): Promise<void> {+ await tx.executeRaw('UPDATE belief_page_lifetimes SET slug = $2, page_id = $3 WHERE page_lifetime = $1::uuid', [lifetime, slug, pageId]);+}++/**+ * The open lifetime of each needed page, minting where none is open and+ * replacing one whose page hint names a different page. Pages the caller does+ * not hold the key of can be resolved here: minting is idempotent under the+ * open-lifetime unique index.+ */+export async function resolveLifetimes(tx: BrainEngine, needs: readonly PageRefNeed[]): Promise<Map<number, string>> {+ const unique = [...new Map(needs.map(n => [n.pageId, n])).values()];+ const open = await readOpenLifetimes(tx, unique);+ const out = new Map<number, string>();+ for (const need of unique) {+ const row = open.get(pairKey(need.incarnation, need.slug));+ if (row && (row.page_id == null || row.page_id === need.pageId)) { out.set(need.pageId, row.page_lifetime); continue; }+ if (row) await endLifetime(tx, row.page_lifetime);+ out.set(need.pageId, await mintLifetime(tx, need));+ }+ return out;+}diff --git a/src/core/belief/schema.ts b/src/core/belief/schema.tsnew file mode 100644index 0000000000..1e8569a6dc--- /dev/null+++ b/src/core/belief/schema.ts@@ -0,0 +1,99 @@+/**+ * Belief ledger DDL (W1, docs/designs/BELIEF_LEDGER.md section 8), shared by+ * the migration and both schema blobs (src/schema.sql region; `bun run build:schema`).+ *+ * `sources.purge_epoch` is migration-only (BELIEF_SOURCE_COLUMNS_SQL), like the+ * trust-tier columns, so fresh and upgraded brains share column ordinals.+ */++const RLS = (table: string) => `DO $rls$ BEGIN+ IF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN+ ALTER TABLE ${table} ENABLE ROW LEVEL SECURITY;+ END IF;+END $rls$;`;++export const BELIEF_LEDGER_TABLES = ['belief_events', 'belief_page_lifetimes', 'belief_commit_marks', 'belief_retier_manifest', 'belief_redactions'] as const;++export const BELIEF_LEDGER_SCHEMA_SQL = `+CREATE TABLE IF NOT EXISTS belief_events (+ id BIGSERIAL PRIMARY KEY,+ event_key BYTEA NOT NULL UNIQUE,+ source_id TEXT NOT NULL,+ source_incarnation UUID NOT NULL,+ page_lifetime UUID,+ slug TEXT NOT NULL,+ subject_kind TEXT NOT NULL CHECK (subject_kind IN ('page','fact','take','link','link_transition','coverage')),+ subject_key TEXT NOT NULL,+ event_type TEXT NOT NULL,+ origin TEXT NOT NULL DEFAULT 'live' CHECK (origin IN ('live','unmanaged','baseline','backfill','reconcile')),+ trust_tier TEXT NOT NULL,+ writer_tier TEXT,+ tier_basis TEXT NOT NULL DEFAULT 'row' CHECK (tier_basis IN ('row','writer','unknown')),+ visibility TEXT NOT NULL,+ publication_id UUID NOT NULL,+ ord INTEGER NOT NULL,+ recorded_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),+ source_time TIMESTAMPTZ,+ valid_from TIMESTAMPTZ,+ valid_until TIMESTAMPTZ,+ value JSONB,+ value_hash TEXT,+ prior_hash TEXT,+ state_hash TEXT NOT NULL,+ cause JSONB NOT NULL,+ claim_fp TEXT,+ purged BOOLEAN NOT NULL DEFAULT false,+ redacted_fields TEXT[]+);+CREATE INDEX IF NOT EXISTS belief_events_page ON belief_events (source_id, slug, id);+CREATE INDEX IF NOT EXISTS belief_events_subject ON belief_events (source_id, subject_kind, subject_key, id);+CREATE INDEX IF NOT EXISTS belief_events_recorded ON belief_events (recorded_at);+CREATE INDEX IF NOT EXISTS belief_events_claim_fp ON belief_events (source_id, claim_fp) WHERE claim_fp IS NOT NULL;+CREATE INDEX IF NOT EXISTS belief_events_lifetime ON belief_events (page_lifetime, id) WHERE page_lifetime IS NOT NULL;+CREATE INDEX IF NOT EXISTS belief_events_publication ON belief_events (publication_id);+${RLS('belief_events')}+CREATE TABLE IF NOT EXISTS belief_page_lifetimes (+ page_lifetime UUID PRIMARY KEY,+ source_id TEXT NOT NULL,+ source_incarnation UUID NOT NULL,+ slug TEXT NOT NULL,+ page_id INTEGER,+ started_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),+ ended_at TIMESTAMPTZ+);+CREATE UNIQUE INDEX IF NOT EXISTS belief_page_lifetimes_open ON belief_page_lifetimes (source_incarnation, slug) WHERE ended_at IS NULL;+CREATE INDEX IF NOT EXISTS belief_page_lifetimes_slug ON belief_page_lifetimes (source_id, slug);+${RLS('belief_page_lifetimes')}+CREATE TABLE IF NOT EXISTS belief_commit_marks (+ publication_id UUID PRIMARY KEY,+ observed_at TIMESTAMPTZ NOT NULL+);+${RLS('belief_commit_marks')}+CREATE TABLE IF NOT EXISTS belief_retier_manifest (+ summary_event BIGINT NOT NULL,+ source_id TEXT NOT NULL,+ subject_kind TEXT NOT NULL,+ subject_key TEXT NOT NULL,+ from_tier TEXT,+ to_tier TEXT NOT NULL,+ PRIMARY KEY (summary_event, subject_kind, subject_key)+);+${RLS('belief_retier_manifest')}+CREATE TABLE IF NOT EXISTS belief_redactions (+ id BIGSERIAL PRIMARY KEY,+ source_id TEXT NOT NULL,+ subject_key TEXT NOT NULL,+ field TEXT NOT NULL,+ purge_request UUID NOT NULL,+ field_hash TEXT NOT NULL,+ released_by UUID,+ released_hash TEXT,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+);+CREATE INDEX IF NOT EXISTS belief_redactions_subject ON belief_redactions (source_id, subject_key, field);+CREATE INDEX IF NOT EXISTS belief_redactions_field_hash ON belief_redactions (source_id, field_hash);+${RLS('belief_redactions')}+`;++/** Migration-only: purge serializes on this counter; the ledger refuses a payload prepared under an older epoch. */+export const BELIEF_SOURCE_COLUMNS_SQL = `ALTER TABLE sources ADD COLUMN IF NOT EXISTS purge_epoch BIGINT NOT NULL DEFAULT 0;`;diff --git a/src/core/belief/state.ts b/src/core/belief/state.tsnew file mode 100644index 0000000000..6fbee46c8d--- /dev/null+++ b/src/core/belief/state.ts@@ -0,0 +1,138 @@+/**+ * Raw canonical state of belief streams (docs/designs/BELIEF_LEDGER.md sections 3-4).+ *+ * A stream is one slug of one source: its page, the fence facts it projects+ * (`source_markdown_slug`), the database-only facts about it (`entity_slug`+ * with no `source_markdown_slug`), its takes, and the links and link+ * transitions whose origin (else from) page it is. The finalization contract+ * reads it under the publication's page keys before and after the transaction's+ * projections and diffs the two on logical keys, so projection churn (rows+ * rewritten with identical values, renumbered, re-inserted) yields no event.+ */+import type { BrainEngine } from '../engine.ts';+import { pipelined } from '../page-state/transactions.ts';+import { privatePagesFilterFragment } from '../search/private-visibility.ts';+import { PAGE_INLINE_MAX_BYTES } from '../page-size-policy.ts';++export interface RawPage {+ id: number; slug: string; deleted: boolean; revision: string; content_hash: string | null; tier: string;+ visible: boolean; large: boolean; incarnation: string;+}+export interface RawFact {+ id: number; entity_slug: string | null; sms: string | null; entity_page_id: number | null; fact: string; fp: string;+ kind: string; visibility: string; notability: string; context: string | null; confidence: number;+ valid_from: string | null; valid_until: string | null; claim_metric: string | null; claim_value: number | null;+ claim_unit: string | null; claim_period: string | null; event_type: string | null; dimension: string | null;+ value: string | null; value_hash: string | null; row_num: number | null; tier: string;+}+export interface RawTake {+ id: number; page_id: number; row_num: number; claim: string; claim_fp: string; kind: string; holder: string; weight: number;+ since_date: string | null; until_date: string | null; source: string | null; active: boolean;+ resolved_at: string | null; resolved_outcome: boolean | null; resolved_value: number | null; resolved_unit: string | null;+ resolved_source: string | null; resolved_by: string | null; resolved_quality: string | null; tier: string;+}+export interface RawEndpoint { id: number; slug: string; source_id: string; incarnation: string }+export interface RawLink {+ id: number; from: RawEndpoint; to: RawEndpoint; origin: RawEndpoint | null; link_type: string; link_source: string | null;+ context: string; origin_field: string | null; link_kind: string | null; resolution_type: string | null; assertion_tense: string | null;+}+export interface RawTransition {+ id: number; from: RawEndpoint; to: RawEndpoint; origin: RawEndpoint | null; link_type: string; kind: string;+ occurred_on: string; date_precision: string; producer: string; line_hash: string;+}+export interface RawState { pages: RawPage[]; facts: RawFact[]; takes: RawTake[]; links: RawLink[]; transitions: RawTransition[]; writerTier: string | null }++const iso = (value: unknown): string | null => value == null ? null : new Date(value as string).toISOString();+const num = (value: unknown): number | null => value == null ? null : Number(value);++const ENDPOINT = (alias: string, as: string) =>+ `${alias}.id AS ${as}_id, ${alias}.slug AS ${as}_slug, ${alias}.source_id AS ${as}_source, ${as}s.incarnation::text AS ${as}_inc`;+const endpoint = (row: Record<string, unknown>, as: string): RawEndpoint | null => row[`${as}_id`] == null ? null+ : { id: Number(row[`${as}_id`]), slug: String(row[`${as}_slug`]), source_id: String(row[`${as}_source`]), incarnation: String(row[`${as}_inc`]) };++/**+ * One pipeline of five reads. `slugs` select the stream pages and the facts+ * keyed to them; `pageIds` add pages by id (a renamed page is found at its new+ * slug); `factIds`/`takeIds` add rows a guard named that live in another stream.+ */+export async function readBeliefState(tx: BrainEngine, sourceId: string, slugs: readonly string[], pageIds: readonly number[] = []): Promise<RawState> {+ const pageRows = await tx.executeRaw<Record<string, unknown>>(`SELECT p.id, p.slug, p.deleted_at IS NOT NULL AS deleted, p.knowledge_revision::text AS revision,+ p.content_hash, p.trust_tier, (${privatePagesFilterFragment('p')}) AS visible, s.incarnation::text AS incarnation,+ (p.body_storage = 'segmented' OR octet_length(COALESCE(p.compiled_truth,'')) + octet_length(COALESCE(p.timeline,'')) > ${PAGE_INLINE_MAX_BYTES}) AS large,+ current_setting('gbrain.write_trust_tier', true) AS writer_tier+ FROM pages p JOIN sources s ON s.id = p.source_id+ WHERE p.source_id = $1 AND (p.slug = ANY($2::text[]) OR p.id = ANY($3::int[]))`, [sourceId, [...slugs], [...pageIds]]);+ const pages: RawPage[] = pageRows.map(r => ({ id: Number(r.id), slug: String(r.slug), deleted: r.deleted === true, revision: String(r.revision),+ content_hash: (r.content_hash as string | null) ?? null, tier: String(r.trust_tier), visible: r.visible === true, large: r.large === true,+ incarnation: String(r.incarnation) }));+ const ids = pages.map(p => p.id);+ const allSlugs = [...new Set([...slugs, ...pages.map(p => p.slug)])];+ const [facts, takes, links, transitions] = await pipelined(tx, [+ () => tx.executeRaw<Record<string, unknown>>(`SELECT f.id, f.entity_slug, f.source_markdown_slug AS sms, pe.id AS entity_page_id, f.fact,+ gbrain_fact_fingerprint(f.fact) AS fp, f.kind, f.visibility, f.notability, f.context, f.confidence::text AS confidence,+ f.valid_from, f.valid_until, f.claim_metric, f.claim_value::text AS claim_value, f.claim_unit, f.claim_period, f.event_type,+ f.dimension, f.value, f.value_hash, f.row_num, f.trust_tier+ FROM facts f LEFT JOIN pages pe ON pe.source_id = f.source_id AND pe.slug = f.entity_slug+ WHERE f.source_id = $1 AND f.expired_at IS NULL+ AND (f.source_markdown_slug = ANY($2::text[]) OR (f.source_markdown_slug IS NULL AND f.entity_slug = ANY($2::text[])))`, [sourceId, allSlugs]),+ () => ids.length ? tx.executeRaw<Record<string, unknown>>(`SELECT k.id, k.page_id, k.row_num, k.claim, gbrain_fact_fingerprint(k.claim) AS claim_fp,+ k.kind, k.holder, k.weight::text AS weight, k.since_date, k.until_date, k.source, k.active, k.resolved_at, k.resolved_outcome,+ k.resolved_value::text AS resolved_value, k.resolved_unit, k.resolved_source, k.resolved_by, k.resolved_quality, k.trust_tier+ FROM takes k WHERE k.page_id = ANY($1::int[])`, [ids]) : Promise.resolve([]),+ () => ids.length ? tx.executeRaw<Record<string, unknown>>(`SELECT l.id, ${ENDPOINT('f', 'f')}, ${ENDPOINT('t', 't')}, ${ENDPOINT('o', 'o')},+ l.link_type, l.link_source, l.context, l.origin_field, l.link_kind, l.resolution_type, l.assertion_tense+ FROM links l JOIN pages f ON f.id = l.from_page_id JOIN sources fs ON fs.id = f.source_id+ JOIN pages t ON t.id = l.to_page_id JOIN sources ts ON ts.id = t.source_id+ LEFT JOIN pages o ON o.id = l.origin_page_id LEFT JOIN sources os ON os.id = o.source_id+ WHERE l.origin_page_id = ANY($1::int[]) OR (l.origin_page_id IS NULL AND l.from_page_id = ANY($1::int[]))`, [ids]) : Promise.resolve([]),+ () => ids.length ? tx.executeRaw<Record<string, unknown>>(`SELECT x.id, ${ENDPOINT('f', 'f')}, ${ENDPOINT('t', 't')}, ${ENDPOINT('o', 'o')},+ x.link_type, x.kind, x.occurred_on::text AS occurred_on, x.date_precision, x.producer, x.line_hash+ FROM link_transitions x JOIN pages f ON f.id = x.from_page_id JOIN sources fs ON fs.id = f.source_id+ JOIN pages t ON t.id = x.to_page_id JOIN sources ts ON ts.id = t.source_id+ LEFT JOIN pages o ON o.id = x.origin_page_id LEFT JOIN sources os ON os.id = o.source_id+ WHERE x.origin_page_id = ANY($1::int[]) OR (x.origin_page_id IS NULL AND x.from_page_id = ANY($1::int[]))`, [ids]) : Promise.resolve([]),+ ]) as Array<Record<string, unknown>[]>;+ return {+ pages,+ facts: facts.map(toFact),+ takes: takes.map(toTake),+ links: links.map(r => ({ id: Number(r.id), from: endpoint(r, 'f')!, to: endpoint(r, 't')!, origin: endpoint(r, 'o'), link_type: String(r.link_type),+ link_source: (r.link_source as string | null) ?? null, context: String(r.context ?? ''), origin_field: (r.origin_field as string | null) ?? null,+ link_kind: (r.link_kind as string | null) ?? null, resolution_type: (r.resolution_type as string | null) ?? null,+ assertion_tense: (r.assertion_tense as string | null) ?? null })),+ 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,+ };+}++/** Rows by id, for a guard event whose row lives outside the batch's streams. */+export async function readFactsById(tx: BrainEngine, ids: readonly number[]): Promise<RawFact[]> {+ if (!ids.length) return [];+ const rows = await tx.executeRaw<Record<string, unknown>>(`SELECT f.id, f.entity_slug, f.source_markdown_slug AS sms, pe.id AS entity_page_id, f.fact,+ gbrain_fact_fingerprint(f.fact) AS fp, f.kind, f.visibility, f.notability, f.context, f.confidence::text AS confidence,+ f.valid_from, f.valid_until, f.claim_metric, f.claim_value::text AS claim_value, f.claim_unit, f.claim_period, f.event_type,+ f.dimension, f.value, f.value_hash, f.row_num, f.trust_tier+ FROM facts f LEFT JOIN pages pe ON pe.source_id = f.source_id AND pe.slug = f.entity_slug WHERE f.id = ANY($1::bigint[])`, [[...ids]]);+ return rows.map(toFact);+}++function toFact(r: Record<string, unknown>): RawFact {+ return { id: Number(r.id), entity_slug: (r.entity_slug as string | null) ?? null, sms: (r.sms as string | null) ?? null,+ entity_page_id: num(r.entity_page_id), fact: String(r.fact), fp: String(r.fp), kind: String(r.kind), visibility: String(r.visibility),+ notability: String(r.notability), context: (r.context as string | null) ?? null, confidence: Number(r.confidence),+ valid_from: iso(r.valid_from), valid_until: iso(r.valid_until), claim_metric: (r.claim_metric as string | null) ?? null,+ claim_value: num(r.claim_value), claim_unit: (r.claim_unit as string | null) ?? null, claim_period: (r.claim_period as string | null) ?? null,+ event_type: (r.event_type as string | null) ?? null, dimension: (r.dimension as string | null) ?? null, value: (r.value as string | null) ?? null,+ value_hash: (r.value_hash as string | null) ?? null, row_num: num(r.row_num), tier: String(r.trust_tier) };+}++function toTake(r: Record<string, unknown>): RawTake {+ return { id: Number(r.id), page_id: Number(r.page_id), row_num: Number(r.row_num), claim: String(r.claim), claim_fp: String(r.claim_fp),+ kind: String(r.kind), holder: String(r.holder), weight: Number(r.weight), since_date: (r.since_date as string | null) ?? null,+ until_date: (r.until_date as string | null) ?? null, source: (r.source as string | null) ?? null, active: r.active === true,+ resolved_at: iso(r.resolved_at), resolved_outcome: (r.resolved_outcome as boolean | null) ?? null, resolved_value: num(r.resolved_value),+ resolved_unit: (r.resolved_unit as string | null) ?? null, resolved_source: (r.resolved_source as string | null) ?? null,+ resolved_by: (r.resolved_by as string | null) ?? null, resolved_quality: (r.resolved_quality as string | null) ?? null, tier: String(r.trust_tier) };+}diff --git a/src/core/belief/subjects.ts b/src/core/belief/subjects.tsnew file mode 100644index 0000000000..55c2220664--- /dev/null+++ b/src/core/belief/subjects.ts@@ -0,0 +1,130 @@+/**+ * Keyed belief subjects of a raw stream state (docs/designs/BELIEF_LEDGER.md+ * sections 3-4). Row ids and fence positions are payload: they ride along to+ * correlate guard notes and replacements inside one transaction, never in a key.+ */+import { factKey, linkKey, ontologyKey, takeKey, takeClaimHash, transitionKey, valueHash, lifetimeRef, slugRef, type SubjectRef } from './keys.ts';+import type { RawEndpoint, RawFact, RawPage, RawState, RawTake } from './state.ts';++export type SubjectKind = 'fact' | 'take' | 'link' | 'link_transition';+export interface Subject {+ kind: SubjectKind; key: string; stream: string; value: Record<string, unknown>; vhash: string; tier: string; visibility: string;+ rowIds: number[]; rowNum: number | null; dbOnly: boolean; claimFp: string | null; validFrom: string | null; validUntil: string | null;+ label: Record<string, unknown>;+}++export interface KeyContext {+ incarnation: string;+ /** page id -> page lifetime, for every page the state names. */+ lifetimes: ReadonlyMap<number, string>;+ /** Stream pages of this side by slug. */+ pagesBySlug: ReadonlyMap<string, RawPage>;+}++const pageRef = (ctx: KeyContext, id: number | null | undefined, slug: string | null): SubjectRef | null => {+ if (id != null && ctx.lifetimes.has(id)) return lifetimeRef(ctx.lifetimes.get(id)!);+ return slug == null ? null : slugRef(ctx.incarnation, slug);+};+const endpointRef = (ctx: KeyContext, e: RawEndpoint | null): SubjectRef | null => e == null ? null+ : ctx.lifetimes.has(e.id) ? lifetimeRef(ctx.lifetimes.get(e.id)!) : slugRef(e.incarnation, e.slug);++export function factValue(f: RawFact, entity: SubjectRef | null, count: number): Record<string, unknown> {+ return { fact: f.fact, kind: f.kind, notability: f.notability, context: f.context, confidence: f.confidence, valid_from: f.valid_from,+ valid_until: f.valid_until, claim_metric: f.claim_metric, claim_value: f.claim_value, claim_unit: f.claim_unit, claim_period: f.claim_period,+ event_type: f.event_type, value: f.value, ...(f.sms != null ? { entity } : {}), ...(count > 1 ? { count } : {}) };+}++export function takeValue(t: RawTake): Record<string, unknown> {+ return { claim: t.claim, kind: t.kind, holder: t.holder, weight: t.weight, since_date: t.since_date, until_date: t.until_date, source: t.source,+ active: t.active, resolved_at: t.resolved_at, resolved_outcome: t.resolved_outcome, resolved_value: t.resolved_value, resolved_unit: t.resolved_unit,+ resolved_source: t.resolved_source, resolved_by: t.resolved_by, resolved_quality: t.resolved_quality };+}++/** One fact row keyed: claim facts by (subject, fp, visibility); ontology observations by their stint identity. */+export function keyFact(ctx: KeyContext, f: RawFact): { key: string; stream: string; entity: SubjectRef | null } {+ const stream = f.sms ?? f.entity_slug ?? '';+ const subjectPage = ctx.pagesBySlug.get(stream);+ const subject = pageRef(ctx, subjectPage?.id, stream)!;+ const entity = pageRef(ctx, f.entity_page_id, f.entity_slug);+ if (f.dimension != null) return { stream, entity, key: ontologyKey(entity ?? subject, f.dimension, f.value_hash ?? '', f.sms == null ? null : subject, f.valid_from) };+ return { stream, entity, key: factKey(subject, f.fp, f.visibility) };+}++export function keyedSubjects(ctx: KeyContext, state: RawState, pageVisibility: (pageId: number) => string): Subject[] {+ const out: Subject[] = [];+ const facts = new Map<string, { rows: RawFact[]; stream: string; entity: SubjectRef | null }>();+ for (const f of state.facts) {+ const { key, stream, entity } = keyFact(ctx, f);+ const group = facts.get(key) ?? { rows: [], stream, entity };+ group.rows.push(f);+ facts.set(key, group);+ }+ for (const [key, { rows, stream, entity }] of facts) {+ rows.sort((a, b) => (a.row_num ?? Infinity) - (b.row_num ?? Infinity) || a.id - b.id);+ 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,+ 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]));+ const byClaim = new Map<string, RawTake[]>();+ for (const t of state.takes) {+ const group = `${t.page_id}\u0000${takeClaimHash(t.claim, t.kind, t.holder)}`;+ byClaim.set(group, [...byClaim.get(group) ?? [], t]);+ }+ for (const [group, rows] of byClaim) {+ rows.sort((a, b) => (a.since_date ?? '').localeCompare(b.since_date ?? '') || a.row_num - b.row_num);+ const claimHash = group.split('\u0000')[1]!;+ rows.forEach((t, ordinal) => {+ const page = pagesById.get(t.page_id)!;+ const value = takeValue(t);+ out.push({ kind: 'take', key: takeKey(ctx.lifetimes.get(t.page_id)!, claimHash, ordinal), stream: page.slug, value, vhash: valueHash(value),+ tier: t.tier, visibility: pageVisibility(t.page_id), rowIds: [t.id], rowNum: t.row_num, dbOnly: false, claimFp: t.claim_fp,+ validFrom: null, validUntil: null, label: { slug: page.slug } });+ });+ }+ for (const l of state.links) {+ const streamPage = l.origin ?? l.from;+ const key = linkKey(endpointRef(ctx, l.from)!, endpointRef(ctx, l.to)!, l.link_type, l.link_source, endpointRef(ctx, l.origin));+ // The context snippet is carried text, not belief: a prose edit around a link rewrites it without changing the+ // assertion, so it rides in the event value (purge redacts it there) but not in the value the diff compares.+ const identity = { origin_field: l.origin_field, link_kind: l.link_kind, resolution_type: l.resolution_type, assertion_tense: l.assertion_tense };+ const value = { ...identity, context: l.context };+ out.push({ kind: 'link', key, stream: streamPage.slug, value, vhash: valueHash(identity), tier: '', visibility: pageVisibility(streamPage.id), rowIds: [l.id],+ rowNum: null, dbOnly: false, claimFp: null, validFrom: null, validUntil: null,+ label: { from: [l.from.source_id, l.from.slug], to: [l.to.source_id, l.to.slug], ...(l.origin ? { origin: [l.origin.source_id, l.origin.slug] } : {}) } });+ }+ for (const x of state.transitions) {+ const streamPage = x.origin ?? x.from;+ const link = linkKey(endpointRef(ctx, x.from)!, endpointRef(ctx, x.to)!, x.link_type, null, endpointRef(ctx, x.origin));+ const value = { date_precision: x.date_precision, line_hash: x.line_hash };+ out.push({ kind: 'link_transition', key: transitionKey(link, x.kind, x.occurred_on, x.producer), stream: streamPage.slug, value, vhash: valueHash(value),+ tier: '', visibility: pageVisibility(streamPage.id), rowIds: [x.id], rowNum: null, dbOnly: false, claimFp: null, validFrom: null, validUntil: null,+ label: { from: [x.from.source_id, x.from.slug], to: [x.to.source_id, x.to.slug] } });+ }+ return dedupeLinks(out);+}++/** Two link rows can serialize to one key only through the NULLS NOT DISTINCT unique; keep the first. */+function dedupeLinks(subjects: Subject[]): Subject[] {+ const seen = new Set<string>();+ return subjects.filter(s => {+ if (s.kind === 'fact' || s.kind === 'take') return true;+ const id = `${s.kind}\u0000${s.key}`;+ if (seen.has(id)) return false;+ seen.add(id);+ return true;+ });+}++/** Every page a state's keys need a lifetime for: stream pages, link endpoints and origins, fact entities. */+export function pageNeeds(sourceId: string, incarnation: string, state: RawState): Array<{ sourceId: string; incarnation: string; slug: string; pageId: number }> {+ const needs: Array<{ sourceId: string; incarnation: string; slug: string; pageId: number }> = [];+ for (const p of state.pages) needs.push({ sourceId, incarnation, slug: p.slug, pageId: p.id });+ for (const f of state.facts) if (f.entity_page_id != null && f.entity_slug) needs.push({ sourceId, incarnation, slug: f.entity_slug, pageId: f.entity_page_id });+ for (const l of [...state.links, ...state.transitions]) {+ for (const e of [l.from, l.to, l.origin]) if (e) needs.push({ sourceId: e.source_id, incarnation: e.incarnation, slug: e.slug, pageId: e.id });+ }+ return needs;+}diff --git a/src/core/page-state/guards.ts b/src/core/page-state/guards.tsindex 1f1e3c317c..281b99abe2 100644--- a/src/core/page-state/guards.ts+++ b/src/core/page-state/guards.ts@@ -88,6 +88,20 @@ function holds(held: HeldPageKeys | null, id: string): boolean {for (; held; held = held.parent) if (held.keys.has(id)) return true;return false;}+/**+ * Fails closed unless `engine` is a transaction that already holds every key+ * (the belief ledger's finalization contract, docs/designs/BELIEF_LEDGER.md+ * section 5.3). It never takes a lock: one taken late, outside lockPageKeys'+ * sorted acquisition, can deadlock.+ */+export function assertHeldPageKeys(engine: object, keys: readonly PageKey[]): void {+ const held = (engine as { _heldPageKeys?: HeldPageKeys | null })._heldPageKeys ?? null;+ const missing = keys.filter(key => { const id = pageGuardKey(key); return id === null || !holds(held, id); });+ if (missing.length) {+ throw Object.assign(new Error(`belief ledger append requires held page keys: ${missing.map(k => `${k.sourceId}/${k.slug}`).join(', ')}`), { code: 'belief_page_key_not_held' });+ }+}+/** lockPageKeys for keys this transaction does not hold yet; invalid keys still reach its checks. */export async function lockUnheldPageKeys(engine: Pick<BrainEngine, 'executeRaw'> & { kind?: string }, held: HeldPageKeys, keys: readonly PageKey[]): Promise<void> {const pending = keys.filter(key => { const id = pageGuardKey(key); return id === null || !holds(held, id); });diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.tsindex 82763bc51b..4289bd0c2c 100644--- a/src/core/persistence/coordinator.ts+++ b/src/core/persistence/coordinator.ts@@ -44,6 +44,8 @@ import { withdrawalFailureDetail } from '../facts/withdrawal.ts';import { faultPoint, withFaultPoints } from './fault-points.ts';import { recordPublicationFenceTrend } from '../fence-repair/census-store.ts';import { segmentWriteScope } from '../page-body/ingest.ts';+import { publicationBeliefOptions, withBeliefBatch } from '../belief/ledger.ts';+import { markBeliefCommits } from '../belief/append.ts';interface PreparedMutationBase {sourceExclusive?: boolean;@@ -281,6 +283,7 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, prlet afterCommitDue = false;const skill = prepared.target === 'skill_bundle';const files = skill ? prepared.files ?? [] : prepared.file ? [prepared.file] : [];+ const beliefReport = { appended: 0 };try {assertMutationProtocol(row);if ((row.target_kind ?? 'page') !== (prepared.target ?? 'page') || (skill ? !!prepared.file || !files.length : prepared.files !== undefined)) {@@ -421,7 +424,10 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, prawait hooks.boundary?.('after_publication', row);}prepared.postimage = undefined;- const outcome = await withCoordinatedWrite(tx, [row.source_id], () => prepared.apply(tx, snapshot), publicationAttribution(row, prepared.trust));+ // W1 finalization contract (docs/designs/BELIEF_LEDGER.md 5.1): the ledger append is the last canonical write before the receipt.+ const apply = () => prepared.apply(tx, snapshot);+ const outcome = await withCoordinatedWrite(tx, [row.source_id], skill ? apply+ : () => withBeliefBatch(tx, publicationBeliefOptions(row, prepared.additionalPageKeys, beliefReport), apply), publicationAttribution(row, prepared.trust));if (!skill) await classifyUnboundPage(tx, row);if (prepared.databaseOnlyReason === 'mirror_read_only') await classifyMirrorPage(tx, row);const final = skill ? null : await publicationPostimage(tx, row, prepared);@@ -434,6 +440,7 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, prreturn committed;});await hooks.boundary?.('after_commit', done);+ if (beliefReport.appended && done.state === 'committed') await markBeliefCommits(engine, [row.id]).catch(() => undefined);if (recovery) await clearResolvedRecovery(engine, row.id, done);afterCommitDue = done.state === 'committed';return done;diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.tsindex de5a9a902f..97b2383c16 100644--- a/src/core/persistence/group-publish.ts+++ b/src/core/persistence/group-publish.ts@@ -72,6 +72,8 @@ import { assertMutationProtocol } from './protocol.ts';import { writeSwitchOn } from './switches.ts';import { importGroupReads, type ImportGroupReads } from './import-reads.ts';import { withScreeningPaths } from './screening-paths.ts';+import { publicationBeliefOptions, withBeliefBatch } from '../belief/ledger.ts';+import { markBeliefCommits } from '../belief/append.ts';/** A `put_pages` or managed import group publishes at most this many pages per transaction, so one commit stays a few seconds long. */export const PAGE_BATCH_GROUP_MAX = 8;@@ -211,6 +213,7 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], prhooks: GroupHooks = {}, lane: LaneState | null = null, transaction: TransactionRunner = fn => publicationTransaction(engine, fn)): Promise<{ done: WriteRequest[] | null; requeued: string[]; reason?: GroupFailure }> {const head = rows[0];const none: { done: null; requeued: string[]; reason?: GroupFailure } = { done: null, requeued: [] };+ const beliefReport = { appended: 0 };if (!head?.worktree_id || rows.some((row, i) => row.worktree_id !== head.worktree_id || row.source_id !== head.source_id || !groupable(row, prepared[i]!)|| rows.length > 1 && singleWrite(row))) return none;const binding = await getWorktreeBinding(engine, head.source_id, hostId);@@ -342,7 +345,7 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], prif (attribute) await setMemberAttribution(tx, publicationAttribution(row, member.trust));}member.postimage = undefined;- const outcome = await member.apply(tx, snapshot);+ const outcome = await withBeliefBatch(tx, publicationBeliefOptions(row, member.additionalPageKeys, beliefReport), () => member.apply(tx, snapshot));await classifyUnboundPage(tx, row);if (member.databaseOnlyReason === 'mirror_read_only') await classifyMirrorPage(tx, row);const final = await publicationPostimage(tx, row, member);@@ -366,6 +369,8 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], prreturn done;});committed = true;+ // One post-commit observation for every member (docs/designs/BELIEF_LEDGER.md 5.3).+ if (beliefReport.appended) await markBeliefCommits(engine, done.map(row => row.id)).catch(() => undefined);for (const row of done) await seam('after_commit', row);hooks.committed?.(done);if (recorded.size) {diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.tsindex 1eee44e278..f659e6fad9 100644--- a/src/core/pglite-schema.generated.ts+++ b/src/core/pglite-schema.generated.ts@@ -2427,6 +2427,106 @@ DO \$rls\$ BEGINEND IF;END \$rls\$;+-- Belief ledger (W1, docs/designs/BELIEF_LEDGER.md): append-only canonical audit state.+CREATE TABLE IF NOT EXISTS belief_events (+ id BIGSERIAL PRIMARY KEY,+ event_key BYTEA NOT NULL UNIQUE,+ source_id TEXT NOT NULL,+ source_incarnation UUID NOT NULL,+ page_lifetime UUID,+ slug TEXT NOT NULL,+ subject_kind TEXT NOT NULL CHECK (subject_kind IN ('page','fact','take','link','link_transition','coverage')),+ subject_key TEXT NOT NULL,+ event_type TEXT NOT NULL,+ origin TEXT NOT NULL DEFAULT 'live' CHECK (origin IN ('live','unmanaged','baseline','backfill','reconcile')),+ trust_tier TEXT NOT NULL,+ writer_tier TEXT,+ tier_basis TEXT NOT NULL DEFAULT 'row' CHECK (tier_basis IN ('row','writer','unknown')),+ visibility TEXT NOT NULL,+ publication_id UUID NOT NULL,+ ord INTEGER NOT NULL,+ recorded_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),+ source_time TIMESTAMPTZ,+ valid_from TIMESTAMPTZ,+ valid_until TIMESTAMPTZ,+ value JSONB,+ value_hash TEXT,+ prior_hash TEXT,+ state_hash TEXT NOT NULL,+ cause JSONB NOT NULL,+ claim_fp TEXT,+ purged BOOLEAN NOT NULL DEFAULT false,+ redacted_fields TEXT[]+);+CREATE INDEX IF NOT EXISTS belief_events_page ON belief_events (source_id, slug, id);+CREATE INDEX IF NOT EXISTS belief_events_subject ON belief_events (source_id, subject_kind, subject_key, id);+CREATE INDEX IF NOT EXISTS belief_events_recorded ON belief_events (recorded_at);+CREATE INDEX IF NOT EXISTS belief_events_claim_fp ON belief_events (source_id, claim_fp) WHERE claim_fp IS NOT NULL;+CREATE INDEX IF NOT EXISTS belief_events_lifetime ON belief_events (page_lifetime, id) WHERE page_lifetime IS NOT NULL;+CREATE INDEX IF NOT EXISTS belief_events_publication ON belief_events (publication_id);+DO \$rls\$ BEGIN+ IF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN+ ALTER TABLE belief_events ENABLE ROW LEVEL SECURITY;+ END IF;+END \$rls\$;+CREATE TABLE IF NOT EXISTS belief_page_lifetimes (+ page_lifetime UUID PRIMARY KEY,+ source_id TEXT NOT NULL,+ source_incarnation UUID NOT NULL,+ slug TEXT NOT NULL,+ page_id INTEGER,+ started_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),+ ended_at TIMESTAMPTZ+);+CREATE UNIQUE INDEX IF NOT EXISTS belief_page_lifetimes_open ON belief_page_lifetimes (source_incarnation, slug) WHERE ended_at IS NULL;+CREATE INDEX IF NOT EXISTS belief_page_lifetimes_slug ON belief_page_lifetimes (source_id, slug);+DO \$rls\$ BEGIN+ IF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN+ ALTER TABLE belief_page_lifetimes ENABLE ROW LEVEL SECURITY;+ END IF;+END \$rls\$;+CREATE TABLE IF NOT EXISTS belief_commit_marks (+ publication_id UUID PRIMARY KEY,+ observed_at TIMESTAMPTZ NOT NULL+);+DO \$rls\$ BEGIN+ IF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN+ ALTER TABLE belief_commit_marks ENABLE ROW LEVEL SECURITY;+ END IF;+END \$rls\$;+CREATE TABLE IF NOT EXISTS belief_retier_manifest (+ summary_event BIGINT NOT NULL,+ source_id TEXT NOT NULL,+ subject_kind TEXT NOT NULL,+ subject_key TEXT NOT NULL,+ from_tier TEXT,+ to_tier TEXT NOT NULL,+ PRIMARY KEY (summary_event, subject_kind, subject_key)+);+DO \$rls\$ BEGIN+ IF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN+ ALTER TABLE belief_retier_manifest ENABLE ROW LEVEL SECURITY;+ END IF;+END \$rls\$;+CREATE TABLE IF NOT EXISTS belief_redactions (+ id BIGSERIAL PRIMARY KEY,+ source_id TEXT NOT NULL,+ subject_key TEXT NOT NULL,+ field TEXT NOT NULL,+ purge_request UUID NOT NULL,+ field_hash TEXT NOT NULL,+ released_by UUID,+ released_hash TEXT,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+);+CREATE INDEX IF NOT EXISTS belief_redactions_subject ON belief_redactions (source_id, subject_key, field);+CREATE INDEX IF NOT EXISTS belief_redactions_field_hash ON belief_redactions (source_id, field_hash);+DO \$rls\$ BEGIN+ IF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN+ ALTER TABLE belief_redactions ENABLE ROW LEVEL SECURITY;+ END IF;+END \$rls\$;+`;export function getPGLiteSchema(diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.tsindex c4cac01d35..5b823bf045 100644--- a/src/core/schema-embedded.generated.ts+++ b/src/core/schema-embedded.generated.ts@@ -3182,4 +3182,106 @@ DO \$rls\$ BEGINEND IF;END \$rls\$;-- END GENERATED from src/core/questions/schema.ts (PINNED_QUESTIONS_SCHEMA_SQL)++-- Belief ledger (W1, docs/designs/BELIEF_LEDGER.md): append-only canonical audit state.+-- BEGIN GENERATED from src/core/belief/schema.ts (BELIEF_LEDGER_SCHEMA_SQL). Edit that file, then run: bun run build:schema+CREATE TABLE IF NOT EXISTS belief_events (+ id BIGSERIAL PRIMARY KEY,+ event_key BYTEA NOT NULL UNIQUE,+ source_id TEXT NOT NULL,+ source_incarnation UUID NOT NULL,+ page_lifetime UUID,+ slug TEXT NOT NULL,+ subject_kind TEXT NOT NULL CHECK (subject_kind IN ('page','fact','take','link','link_transition','coverage')),+ subject_key TEXT NOT NULL,+ event_type TEXT NOT NULL,+ origin TEXT NOT NULL DEFAULT 'live' CHECK (origin IN ('live','unmanaged','baseline','backfill','reconcile')),+ trust_tier TEXT NOT NULL,+ writer_tier TEXT,+ tier_basis TEXT NOT NULL DEFAULT 'row' CHECK (tier_basis IN ('row','writer','unknown')),+ visibility TEXT NOT NULL,+ publication_id UUID NOT NULL,+ ord INTEGER NOT NULL,+ recorded_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),+ source_time TIMESTAMPTZ,+ valid_from TIMESTAMPTZ,+ valid_until TIMESTAMPTZ,+ value JSONB,+ value_hash TEXT,+ prior_hash TEXT,+ state_hash TEXT NOT NULL,+ cause JSONB NOT NULL,+ claim_fp TEXT,+ purged BOOLEAN NOT NULL DEFAULT false,+ redacted_fields TEXT[]+);+CREATE INDEX IF NOT EXISTS belief_events_page ON belief_events (source_id, slug, id);+CREATE INDEX IF NOT EXISTS belief_events_subject ON belief_events (source_id, subject_kind, subject_key, id);+CREATE INDEX IF NOT EXISTS belief_events_recorded ON belief_events (recorded_at);+CREATE INDEX IF NOT EXISTS belief_events_claim_fp ON belief_events (source_id, claim_fp) WHERE claim_fp IS NOT NULL;+CREATE INDEX IF NOT EXISTS belief_events_lifetime ON belief_events (page_lifetime, id) WHERE page_lifetime IS NOT NULL;+CREATE INDEX IF NOT EXISTS belief_events_publication ON belief_events (publication_id);+DO \$rls\$ BEGIN+ IF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN+ ALTER TABLE belief_events ENABLE ROW LEVEL SECURITY;+ END IF;+END \$rls\$;+CREATE TABLE IF NOT EXISTS belief_page_lifetimes (+ page_lifetime UUID PRIMARY KEY,+ source_id TEXT NOT NULL,+ source_incarnation UUID NOT NULL,+ slug TEXT NOT NULL,+ page_id INTEGER,+ started_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),+ ended_at TIMESTAMPTZ+);+CREATE UNIQUE INDEX IF NOT EXISTS belief_page_lifetimes_open ON belief_page_lifetimes (source_incarnation, slug) WHERE ended_at IS NULL;+CREATE INDEX IF NOT EXISTS belief_page_lifetimes_slug ON belief_page_lifetimes (source_id, slug);+DO \$rls\$ BEGIN+ IF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN+ ALTER TABLE belief_page_lifetimes ENABLE ROW LEVEL SECURITY;+ END IF;+END \$rls\$;+CREATE TABLE IF NOT EXISTS belief_commit_marks (+ publication_id UUID PRIMARY KEY,+ observed_at TIMESTAMPTZ NOT NULL+);+DO \$rls\$ BEGIN+ IF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN+ ALTER TABLE belief_commit_marks ENABLE ROW LEVEL SECURITY;+ END IF;+END \$rls\$;+CREATE TABLE IF NOT EXISTS belief_retier_manifest (+ summary_event BIGINT NOT NULL,+ source_id TEXT NOT NULL,+ subject_kind TEXT NOT NULL,+ subject_key TEXT NOT NULL,+ from_tier TEXT,+ to_tier TEXT NOT NULL,+ PRIMARY KEY (summary_event, subject_kind, subject_key)+);+DO \$rls\$ BEGIN+ IF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN+ ALTER TABLE belief_retier_manifest ENABLE ROW LEVEL SECURITY;+ END IF;+END \$rls\$;+CREATE TABLE IF NOT EXISTS belief_redactions (+ id BIGSERIAL PRIMARY KEY,+ source_id TEXT NOT NULL,+ subject_key TEXT NOT NULL,+ field TEXT NOT NULL,+ purge_request UUID NOT NULL,+ field_hash TEXT NOT NULL,+ released_by UUID,+ released_hash TEXT,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+);+CREATE INDEX IF NOT EXISTS belief_redactions_subject ON belief_redactions (source_id, subject_key, field);+CREATE INDEX IF NOT EXISTS belief_redactions_field_hash ON belief_redactions (source_id, field_hash);+DO \$rls\$ BEGIN+ IF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN+ ALTER TABLE belief_redactions ENABLE ROW LEVEL SECURITY;+ END IF;+END \$rls\$;+-- END GENERATED from src/core/belief/schema.ts (BELIEF_LEDGER_SCHEMA_SQL)`;diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.tsindex 284286cf7d..762ad27cf7 100644--- a/src/core/schema-migrations/latest.generated.ts+++ b/src/core/schema-migrations/latest.generated.ts@@ -4,4 +4,4 @@// The highest schema migration version (migrate.ts LATEST_VERSION), importable without// loading the migrations themselves.-export const LATEST_SCHEMA_VERSION = 248;+export const LATEST_SCHEMA_VERSION = 249;diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex 6c14de5c01..36013d21b3 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -249,6 +249,7 @@ import { v245 } from './v245-page-search-vector-bounded-timeline.ts';import { v246 } from './v246-page-embedding-budget.ts';import { v247 } from './v247-page-extraction-state.ts';import { v248 } from './v248-segmented-page-storage.ts';+import { v249 } from './v249-belief-ledger.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -496,4 +497,5 @@ export const MIGRATIONS: Migration[] = [v246,v247,v248,+ v249,];diff --git a/src/core/schema-migrations/v249-belief-ledger.ts b/src/core/schema-migrations/v249-belief-ledger.tsnew file mode 100644index 0000000000..94aeee0d28--- /dev/null+++ b/src/core/schema-migrations/v249-belief-ledger.ts@@ -0,0 +1,19 @@+import type { Migration } from './types.ts';+import { BELIEF_LEDGER_SCHEMA_SQL, BELIEF_SOURCE_COLUMNS_SQL } from '../belief/schema.ts';++// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.+//+// Belief ledger (W1, docs/designs/BELIEF_LEDGER.md): the append-only+// `belief_events` table with its page lifetimes, commit marks, bulk retiering+// manifest and purge redaction register (src/core/belief/schema.ts, also in+// both blobs), plus the migration-only `sources.purge_epoch` counter. Additive+// and empty: nothing appends until `gbrain beliefs enable` baselines a source.+export const v249: Migration = {+ version: 249,+ name: 'belief_ledger',+ idempotent: true,+ sql: `${BELIEF_LEDGER_SCHEMA_SQL}+ ${BELIEF_SOURCE_COLUMNS_SQL}+ `,+};diff --git a/src/core/trust/proposals.ts b/src/core/trust/proposals.tsindex b559eb6bfc..87cf046308 100644--- a/src/core/trust/proposals.ts+++ b/src/core/trust/proposals.ts@@ -24,6 +24,7 @@ import type { Principal } from '../persistence/model.ts';import type { OwnerConfirmation } from './confirm.ts';import type { TrustTable } from './schema.ts';import { TRUST_PROPOSAL_ACTIONS, TRUST_PROPOSAL_STATUSES } from './schema.ts';+import { noteBelief } from '../belief/ledger.ts';export type TrustProposalAction = typeof TRUST_PROPOSAL_ACTIONS[number];export type TrustProposalStatus = typeof TRUST_PROPOSAL_STATUSES[number];@@ -107,12 +108,16 @@ export async function insertTrustProposal(tx: BrainEngine, input: NewTrustProposNULLIF(current_setting('gbrain.write_principal_kind', true), ''), NULLIF(current_setting('gbrain.write_principal_id', true), ''),NULLIF(current_setting('gbrain.write_request', true), '')::uuid)ON CONFLICT DO NOTHING RETURNING id`, params);- if (inserted) return { id: Number(inserted.id), created: true };+ if (inserted) {+ noteBelief({ kind: 'contested', table: input.target.table, rowId: input.target.id, proposalId: Number(inserted.id), guard: input.proposer });+ return { id: Number(inserted.id), created: true };+ }const [existing] = await tx.executeRaw<{ id: number }>(`SELECT id FROM trust_proposals WHERE status = 'pending' AND action = $1 AND target_table = $2 AND target_id = $3AND related_table IS NOT DISTINCT FROM $4 AND related_id IS NOT DISTINCT FROM $5 ORDER BY id LIMIT 1`,[input.action, input.target.table, input.target.id, input.related?.table ?? null, input.related?.id ?? null]);if (!existing) throw new Error('trust proposal insert conflicted but no pending row was found');+ noteBelief({ kind: 'contested', table: input.target.table, rowId: input.target.id, proposalId: Number(existing.id), guard: input.proposer });return { id: Number(existing.id), created: false };}diff --git a/src/core/write-gate-store.ts b/src/core/write-gate-store.tsindex f6b9b2ad7a..3e22bdb2cc 100644--- a/src/core/write-gate-store.ts+++ b/src/core/write-gate-store.ts@@ -13,6 +13,7 @@*/import { createHash } from 'node:crypto';import type { BrainEngine } from './engine.ts';+import { noteBelief } from './belief/ledger.ts';import {assessFactForGate, assessTakeForGate, normalizeForGate,type GateFactRow, type GateTakeRow, type WriteGateAssessment, type WriteGateConfig, type WriteGateInput, type WriteGateOrigin, type WriteGateReasonFamily,@@ -118,6 +119,8 @@ export async function recordWriteGateHold(tx: Exec, input: WriteGateHoldInput):[input.kind, input.sourceId, input.slug ?? '', holdFingerprint(input.kind, input.texts), a.detectorVersion, a.tier, a.families, reasonList(a),a.detectorError, JSON.stringify(input.payload), input.origin ? JSON.stringify(input.origin) : null, input.requestId ?? null]);const holdId = Number(rows[0]!.id);+ const fingerprint = holdFingerprint(input.kind, input.texts);+ noteBelief({ kind: 'held', holdKind: input.kind, fingerprint, holdId, slug: input.slug ?? '', tier: a.tier, valueHash: fingerprint });const receiptId = await recordWriteGateReceipt(tx, { targetTable: 'write_gate_holds', targetId: holdId, sourceId: input.sourceId, assessment: { ...a, verdict: 'quarantine' }, requestId: input.requestId });return { holdId, receiptId };}diff --git a/src/schema.sql b/src/schema.sqlindex 8fdcf388f2..10a710bebd 100644--- a/src/schema.sql+++ b/src/schema.sql@@ -3178,3 +3178,105 @@ DO $rls$ BEGINEND IF;END $rls$;-- END GENERATED from src/core/questions/schema.ts (PINNED_QUESTIONS_SCHEMA_SQL)++-- Belief ledger (W1, docs/designs/BELIEF_LEDGER.md): append-only canonical audit state.+-- BEGIN GENERATED from src/core/belief/schema.ts (BELIEF_LEDGER_SCHEMA_SQL). Edit that file, then run: bun run build:schema+CREATE TABLE IF NOT EXISTS belief_events (+ id BIGSERIAL PRIMARY KEY,+ event_key BYTEA NOT NULL UNIQUE,+ source_id TEXT NOT NULL,+ source_incarnation UUID NOT NULL,+ page_lifetime UUID,+ slug TEXT NOT NULL,+ subject_kind TEXT NOT NULL CHECK (subject_kind IN ('page','fact','take','link','link_transition','coverage')),+ subject_key TEXT NOT NULL,+ event_type TEXT NOT NULL,+ origin TEXT NOT NULL DEFAULT 'live' CHECK (origin IN ('live','unmanaged','baseline','backfill','reconcile')),+ trust_tier TEXT NOT NULL,+ writer_tier TEXT,+ tier_basis TEXT NOT NULL DEFAULT 'row' CHECK (tier_basis IN ('row','writer','unknown')),+ visibility TEXT NOT NULL,+ publication_id UUID NOT NULL,+ ord INTEGER NOT NULL,+ recorded_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),+ source_time TIMESTAMPTZ,+ valid_from TIMESTAMPTZ,+ valid_until TIMESTAMPTZ,+ value JSONB,+ value_hash TEXT,+ prior_hash TEXT,+ state_hash TEXT NOT NULL,+ cause JSONB NOT NULL,+ claim_fp TEXT,+ purged BOOLEAN NOT NULL DEFAULT false,+ redacted_fields TEXT[]+);+CREATE INDEX IF NOT EXISTS belief_events_page ON belief_events (source_id, slug, id);+CREATE INDEX IF NOT EXISTS belief_events_subject ON belief_events (source_id, subject_kind, subject_key, id);+CREATE INDEX IF NOT EXISTS belief_events_recorded ON belief_events (recorded_at);+CREATE INDEX IF NOT EXISTS belief_events_claim_fp ON belief_events (source_id, claim_fp) WHERE claim_fp IS NOT NULL;+CREATE INDEX IF NOT EXISTS belief_events_lifetime ON belief_events (page_lifetime, id) WHERE page_lifetime IS NOT NULL;+CREATE INDEX IF NOT EXISTS belief_events_publication ON belief_events (publication_id);+DO $rls$ BEGIN+ IF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN+ ALTER TABLE belief_events ENABLE ROW LEVEL SECURITY;+ END IF;+END $rls$;+CREATE TABLE IF NOT EXISTS belief_page_lifetimes (+ page_lifetime UUID PRIMARY KEY,+ source_id TEXT NOT NULL,+ source_incarnation UUID NOT NULL,+ slug TEXT NOT NULL,+ page_id INTEGER,+ started_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),+ ended_at TIMESTAMPTZ+);+CREATE UNIQUE INDEX IF NOT EXISTS belief_page_lifetimes_open ON belief_page_lifetimes (source_incarnation, slug) WHERE ended_at IS NULL;+CREATE INDEX IF NOT EXISTS belief_page_lifetimes_slug ON belief_page_lifetimes (source_id, slug);+DO $rls$ BEGIN+ IF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN+ ALTER TABLE belief_page_lifetimes ENABLE ROW LEVEL SECURITY;+ END IF;+END $rls$;+CREATE TABLE IF NOT EXISTS belief_commit_marks (+ publication_id UUID PRIMARY KEY,+ observed_at TIMESTAMPTZ NOT NULL+);+DO $rls$ BEGIN+ IF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN+ ALTER TABLE belief_commit_marks ENABLE ROW LEVEL SECURITY;+ END IF;+END $rls$;+CREATE TABLE IF NOT EXISTS belief_retier_manifest (+ summary_event BIGINT NOT NULL,+ source_id TEXT NOT NULL,+ subject_kind TEXT NOT NULL,+ subject_key TEXT NOT NULL,+ from_tier TEXT,+ to_tier TEXT NOT NULL,+ PRIMARY KEY (summary_event, subject_kind, subject_key)+);+DO $rls$ BEGIN+ IF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN+ ALTER TABLE belief_retier_manifest ENABLE ROW LEVEL SECURITY;+ END IF;+END $rls$;+CREATE TABLE IF NOT EXISTS belief_redactions (+ id BIGSERIAL PRIMARY KEY,+ source_id TEXT NOT NULL,+ subject_key TEXT NOT NULL,+ field TEXT NOT NULL,+ purge_request UUID NOT NULL,+ field_hash TEXT NOT NULL,+ released_by UUID,+ released_hash TEXT,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+);+CREATE INDEX IF NOT EXISTS belief_redactions_subject ON belief_redactions (source_id, subject_key, field);+CREATE INDEX IF NOT EXISTS belief_redactions_field_hash ON belief_redactions (source_id, field_hash);+DO $rls$ BEGIN+ IF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN+ ALTER TABLE belief_redactions ENABLE ROW LEVEL SECURITY;+ END IF;+END $rls$;+-- END GENERATED from src/core/belief/schema.ts (BELIEF_LEDGER_SCHEMA_SQL)