Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
W1 lane C: coverage reads (intervals, coverageAt, visibility), drift scan and reconcile; probes 13, 15, 16, 17, 33
garrytand1573265a2a2
diff --git a/src/core/belief/coverage-report.ts b/src/core/belief/coverage-report.tsnew file mode 100644index 0000000000..9d5201f0d5--- /dev/null+++ b/src/core/belief/coverage-report.ts@@ -0,0 +1,331 @@+/**+ * Coverage reads and repairs of the belief ledger (docs/designs/BELIEF_LEDGER.md+ * sections 5.3, 7.1 and 7.3), shared by `gbrain beliefs`, the doctor check+ * `belief_ledger_coverage` and the cycle's extract phase.+ *+ * - `coverageIntervals`: one interval per activation run of the source's+ * current incarnation, with its watermark, certified status, baseline+ * progress, restore gaps and the slugs a drift finding uncertified.+ * - `coverageAt`: whether a recorded-time read at `T` is covered, the coded+ * refusal `coverage_from` before a page's cut, `coverage_gap` inside a+ * stopped or restore gap.+ * - `beliefEventVisibility`: the section 5.3 visibility rule over commit marks.+ * - `scanBeliefDrift` / `reconcileBeliefDrift`: slugs whose current belief set+ * no longer hashes to their newest event's `state_hash`, and the `reconcile`+ * events that restate them.+ * - `orphanLifetimes`, `unmarkedPublications`: the check's integrity findings.+ */+import { randomUUID } from 'node:crypto';+import type { BrainEngine } from '../engine.ts';+import { COVERAGE_KEY, pageKey, valueHash } from './keys.ts';+import { appendBeliefEvents, markBeliefCommits, type BeliefEventDraft } from './append.ts';+import { coverageActive, currentStateHash, readLedgerSource } from './ledger.ts';+import { keyedSubjects } from './subjects.ts';+import { endLifetime, readOpenLifetimes } from './lifetimes.ts';++export type PurgeReplay = 'complete' | 'partial' | 'unavailable' | 'unverified';+export interface RestoreMark { event_id: number; at: string; archive_created_at: string | null; purge_replay: PurgeReplay | null; purge_requests: string[]; replay_argv: string[] | null }+export interface DriftMark { slug: string; event_id: number; from: string | null; to: string }+export interface CoverageInterval {+ run: string | null; incarnation: string; started_id: number; started_at: string;+ /** recorded_at of `coverage.complete`: the source's watermark; null while the baseline runs. */+ watermark: string | null;+ stopped_at: string | null;+ /** Only a managed source's completed baseline is certified; links only for journaled publications. */+ certified: boolean;+ links_certified: 'journaled_only' | false;+ baseline: { pages_done: number; pending: number | null; complete: boolean };+ restores: RestoreMark[];+ /** Slug intervals a drift finding uncertified: (from, to], permanently. */+ drift: DriftMark[];+}++interface CoverageRow { id: number; event_type: string; recorded_at: string; value: unknown; cause: unknown; incarnation: string }+const iso = (v: unknown) => new Date(v as string).toISOString();+const obj = (v: unknown): Record<string, unknown> => (typeof v === 'string' ? JSON.parse(v) : v ?? {}) as Record<string, unknown>;+const field = (row: CoverageRow, name: string) => obj(row.value)[name] ?? obj(row.cause)[name];++/** Coverage intervals of the source's current incarnation, oldest first. */+export async function coverageIntervals(engine: BrainEngine, sourceId: string): Promise<CoverageInterval[]> {+ const rows = await engine.executeRaw<CoverageRow>(`SELECT e.id, e.event_type, e.recorded_at, e.value, e.cause, e.source_incarnation::text AS incarnation+ 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`, [sourceId, COVERAGE_KEY]);+ const intervals: CoverageInterval[] = [];+ for (const row of rows) {+ const id = Number(row.id);+ const current = intervals.at(-1);+ if (row.event_type === 'coverage.started') {+ intervals.push({ run: (obj(row.cause).run as string | undefined) ?? null, incarnation: row.incarnation, started_id: id, started_at: iso(row.recorded_at),+ watermark: null, stopped_at: null, certified: false, links_certified: false, baseline: { pages_done: 0, pending: null, complete: false }, restores: [], drift: [] });+ continue;+ }+ if (!current || current.stopped_at) continue;+ if (row.event_type === 'coverage.complete') {+ current.watermark = iso(row.recorded_at);+ current.certified = obj(row.cause).certified === true;+ current.links_certified = current.certified ? 'journaled_only' : false;+ current.baseline.complete = true;+ } else if (row.event_type === 'coverage.stopped') current.stopped_at = iso(row.recorded_at);+ else if (row.event_type === 'coverage.restored') {+ const archive = field(row, 'archive_created_at');+ const requests = field(row, 'purge_requests');+ const argv = field(row, 'replay_argv');+ current.restores.push({ event_id: id, at: iso(row.recorded_at), archive_created_at: archive ? iso(archive) : null,+ purge_replay: (field(row, 'purge_replay') as PurgeReplay | undefined) ?? null, purge_requests: Array.isArray(requests) ? requests.map(String) : [],+ replay_argv: Array.isArray(argv) ? argv.map(String) : null });+ }+ }+ for (const interval of intervals) {+ const [done] = await engine.executeRaw<{ n: number }>(`SELECT count(DISTINCT slug)::int AS n FROM belief_events+ WHERE source_id = $1 AND event_type = 'baseline' AND cause->>'run' = $2`, [sourceId, interval.run ?? '']);+ interval.baseline.pages_done = Number(done?.n ?? 0);+ const drift = await engine.executeRaw<{ id: number; slug: string; recorded_at: string; from: string | null }>(`SELECT id, slug, recorded_at, cause->>'uncertified_from' AS "from"+ FROM belief_events WHERE source_id = $1 AND origin = 'reconcile' AND subject_kind = 'page' AND source_incarnation = $2::uuid AND id > $3+ AND ($4::timestamptz IS NULL OR recorded_at <= $4::timestamptz) ORDER BY id`,+ [sourceId, interval.incarnation, interval.started_id, interval.stopped_at]);+ interval.drift = drift.map(d => ({ slug: d.slug, event_id: Number(d.id), from: d.from ? iso(d.from) : null, to: iso(d.recorded_at) }));+ }+ const open = intervals.at(-1);+ if (open && !open.stopped_at && !open.baseline.complete) {+ const [pending] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n 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 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)`,+ [sourceId, open.run ?? '']);+ open.baseline.pending = Number(pending?.n ?? 0);+ }+ return intervals;+}++export type CoverageAt =+ | { ok: true; certified: boolean; uncertified_reason: 'unmanaged' | 'drift' | null; cut: string; interval: CoverageInterval }+ | { ok: false; code: 'coverage_from'; from: string | null; message: string }+ | { ok: false; code: 'coverage_gap'; reason: 'not_covered' | 'restore'; from: string | null; until: string | null; message: string };++/** The first recorded cut of `slug` in the interval: its baseline, creation snapshot or first page-less assertion. */+async function slugCut(engine: BrainEngine, sourceId: string, interval: CoverageInterval, slug: string): Promise<string | null> {+ const [row] = await engine.executeRaw<{ recorded_at: string }>(`SELECT recorded_at FROM belief_events+ WHERE source_id = $1 AND source_incarnation = $2::uuid AND slug = $3 AND id > $4+ AND (event_type = 'baseline' OR (event_type = 'page.published' AND value->>'revision_before' IS NULL)+ OR (page_lifetime IS NULL AND subject_kind = 'fact' AND event_type = 'fact.asserted'))+ ORDER BY id LIMIT 1`, [sourceId, interval.incarnation, slug, interval.started_id]);+ return row ? iso(row.recorded_at) : null;+}++/**+ * Whether a recorded-time read at `at` is answered by the ledger: for a page+ * (`slug`), from its own cut; for the source, from the watermark. Before the+ * cut: `coverage_from`. Between intervals or inside a restore gap+ * ([archive time, restore]): `coverage_gap`. A covered answer says whether it+ * is certified (managed source, no drift mark over `at`).+ */+export async function coverageAt(engine: BrainEngine, sourceId: string, at: Date | string, slug?: string): Promise<CoverageAt> {+ const t = new Date(at).getTime();+ const intervals = await coverageIntervals(engine, sourceId);+ const first = intervals[0];+ if (!first || t < Date.parse(first.started_at)) {+ return { ok: false, code: 'coverage_from', from: first?.watermark ?? first?.started_at ?? null,+ message: first ? `The belief ledger covers ${sourceId} only from ${first.watermark ?? first.started_at}.` : `The belief ledger has no coverage of ${sourceId}.` };+ }+ const interval = [...intervals].reverse().find(i => Date.parse(i.started_at) <= t);+ if (!interval || (interval.stopped_at && t >= Date.parse(interval.stopped_at))) {+ const next = intervals.find(i => Date.parse(i.started_at) > t) ?? null;+ return { ok: false, code: 'coverage_gap', reason: 'not_covered', from: interval?.stopped_at ?? null, until: next?.started_at ?? null,+ message: `The belief ledger was not recording ${sourceId} at ${new Date(t).toISOString()}.` };+ }+ const gap = interval.restores.find(r => r.archive_created_at && t > Date.parse(r.archive_created_at) && t <= Date.parse(r.at));+ if (gap) {+ return { ok: false, code: 'coverage_gap', reason: 'restore', from: gap.archive_created_at, until: gap.at,+ message: `A backup restore at ${gap.at} replaced the ledger with an archive from ${gap.archive_created_at}; what happened between them is unknown.` };+ }+ const cut = slug ? await slugCut(engine, sourceId, interval, slug) : interval.watermark;+ if (!cut || t < Date.parse(cut)) {+ return { ok: false, code: 'coverage_from', from: cut,+ message: cut ? `The belief ledger covers ${slug ?? sourceId} only from ${cut}.` : `The baseline of ${slug ?? sourceId} has not run yet.` };+ }+ const drifted = slug ? interval.drift.some(d => d.slug === slug && (d.from == null || t > Date.parse(d.from)) && t <= Date.parse(d.to)) : false;+ return { ok: true, certified: interval.certified && !drifted, uncertified_reason: !interval.certified ? 'unmanaged' : drifted ? 'drift' : null, cut, interval };+}++/**+ * Section 5.3: at `at`, an event is visible once its publication's commit mark+ * is at or before `at`, not visible when it was recorded after `at`, and+ * otherwise unproven unless a later event of the same page (higher id, same+ * page lock) was recorded at or before `at`.+ */+export async function beliefEventVisibility(engine: BrainEngine, eventId: number, at: Date | string): Promise<'visible' | 'not_visible' | 'unproven'> {+ const [row] = await engine.executeRaw<{ recorded: boolean; observed: boolean; proven: boolean }>(`SELECT e.recorded_at <= $2::timestamptz AS recorded,+ COALESCE(m.observed_at <= $2::timestamptz, false) AS observed,+ EXISTS (SELECT 1 FROM belief_events l WHERE l.source_id = e.source_id AND l.id > e.id AND l.recorded_at <= $2::timestamptz+ AND ((e.page_lifetime IS NOT NULL AND l.page_lifetime = e.page_lifetime) OR (e.page_lifetime IS NULL AND l.slug = e.slug))) AS proven+ FROM belief_events e LEFT JOIN belief_commit_marks m ON m.publication_id = e.publication_id WHERE e.id = $1`, [eventId, new Date(at).toISOString()]);+ if (!row) throw new Error(`belief event not found: ${eventId}`);+ if (row.observed) return 'visible';+ if (!row.recorded) return 'not_visible';+ return row.proven ? 'visible' : 'unproven';+}++export interface DriftFinding { slug: string; recorded_hash: string | null; current_hash: string; last_event_id: number | null }+export interface DriftScan { checked: number; candidates: number; exact: boolean; drifted: DriftFinding[] }+export const DRIFT_SAMPLE_PAGES = 200;++/**+ * Slugs whose current belief set no longer hashes to the `state_hash` of their+ * newest event (a writer changed state without appending). Candidates are the+ * source's pages, page-less fact subjects and open lifetimes, most recently+ * updated first; `deep` checks all of them, otherwise the first `limit`.+ * Runs only on a source whose baseline completed.+ */+export async function scanBeliefDrift(engine: BrainEngine, sourceId: string, opts: { deep?: boolean; limit?: number } = {}): Promise<DriftScan> {+ const source = await readLedgerSource(engine, sourceId);+ if (!source || !coverageActive(source.coverage) || source.coverage === 'coverage.started') return { checked: 0, candidates: 0, exact: true, drifted: [] };+ const candidates = await engine.executeRaw<{ slug: string }>(`SELECT slug FROM (+ SELECT p.slug, p.updated_at AS at FROM pages p WHERE p.source_id = $1+ UNION ALL SELECT f.entity_slug, max(f.created_at) FROM facts f WHERE f.source_id = $1 AND f.source_markdown_slug IS NULL AND f.entity_slug IS NOT NULL GROUP BY f.entity_slug+ UNION ALL SELECT l.slug, l.started_at FROM belief_page_lifetimes l WHERE l.source_id = $1 AND l.source_incarnation = $2::uuid AND l.ended_at IS NULL+ ) c GROUP BY slug ORDER BY max(at) DESC NULLS LAST, slug`, [sourceId, source.incarnation]);+ const limit = opts.deep ? candidates.length : Math.min(candidates.length, opts.limit ?? DRIFT_SAMPLE_PAGES);+ const drifted: DriftFinding[] = [];+ for (const { slug } of candidates.slice(0, limit)) {+ const finding = await driftOf(engine, sourceId, source.incarnation, slug);+ if (finding) drifted.push(finding);+ }+ return { checked: limit, candidates: candidates.length, exact: limit === candidates.length, drifted };+}++async function newestEvent(tx: BrainEngine, sourceId: string, incarnation: string, slug: string): Promise<{ id: number; state_hash: string; recorded_at: string } | null> {+ const [row] = await tx.executeRaw<{ id: number; state_hash: string; recorded_at: string }>(`SELECT id, state_hash, recorded_at FROM belief_events+ WHERE source_id = $1 AND source_incarnation = $2::uuid AND slug = $3 AND subject_kind <> 'coverage' ORDER BY id DESC LIMIT 1`, [sourceId, incarnation, slug]);+ return row ? { id: Number(row.id), state_hash: row.state_hash, recorded_at: iso(row.recorded_at) } : null;+}++async function driftOf(engine: BrainEngine, sourceId: string, incarnation: string, slug: string): Promise<DriftFinding | null> {+ return engine.transaction(async tx => {+ const [{ hash, state }, last] = [await currentStateHash(tx, sourceId, incarnation, slug), await newestEvent(tx, sourceId, incarnation, slug)];+ if (last?.state_hash === hash) return null;+ const open = await readOpenLifetimes(tx, [{ incarnation, slug }]);+ if (!last && !state.pages.some(p => p.slug === slug) && !state.facts.length && !open.size) return null;+ return { slug, recorded_hash: last?.state_hash ?? null, current_hash: hash, last_event_id: last?.id ?? null };+ });+}++/** The diff hash of a recorded value: a link's context is carried text, outside the hash (subjects.ts). */+function recordedVhash(r: { subject_kind: string; value: unknown; value_hash: string | null }): string | null {+ if (r.subject_kind !== 'link') return r.value_hash;+ const { context: _context, ...identity } = obj(r.value);+ return valueHash(identity);+}++const PROVEN_KINDS = /\.(asserted|revised|resolved|unresolved|adopted|transferred)$|^baseline$|^reconcile$/;++/**+ * Appends `reconcile` events (origin 'reconcile', recorded_at the append) for+ * one drifted slug, under its page key: one per key whose current value no+ * per-key event after the slug's latest snapshot proves unchanged, one with no+ * value per recorded key that is gone, and one on the page carrying the new+ * full-set state_hash and `uncertified_from` (the previous event's time). On a+ * managed source that interval stays uncertified (coverageIntervals' drift).+ * Returns the events appended (0 when the slug no longer drifts under its key).+ */+export async function reconcileSlug(engine: BrainEngine, sourceId: string, slug: string, opts: { op?: string } = {}): Promise<number> {+ 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 last = await newestEvent(tx, sourceId, source.incarnation, slug);+ if (last?.state_hash === hash) return 0;+ const page = state.pages.find(p => p.slug === slug) ?? null;+ const lifetime = page ? lifetimes.get(page.id)! : null;+ 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 && (page && !page.deleted || s.dbOnly));+ const recorded = await tx.executeRaw<{ id: number; subject_kind: string; subject_key: string; event_type: string; value: unknown; value_hash: string | null; trust_tier: string;+ visibility: string; claim_fp: string | null }>(`SELECT DISTINCT ON (subject_kind, subject_key) id, subject_kind, subject_key, event_type, value, value_hash, trust_tier, visibility, claim_fp+ FROM belief_events WHERE source_id = $1 AND source_incarnation = $2::uuid AND slug = $3 AND subject_kind NOT IN ('page','coverage')+ AND id > COALESCE((SELECT max(id) FROM belief_events s WHERE s.source_id = $1 AND s.source_incarnation = $2::uuid AND s.slug = $3 AND s.subject_kind = 'page'+ AND (s.event_type IN ('baseline','reconcile') OR (s.event_type = 'page.published' AND s.value->>'revision_before' IS NULL))), 0)+ ORDER BY subject_kind, subject_key, id DESC`, [sourceId, source.incarnation, slug]);+ const proven = new Map(recorded.filter(r => PROVEN_KINDS.test(r.event_type) && r.value_hash).map(r => [`${r.subject_kind}\u0000${r.subject_key}`, recordedVhash(r)]));+ const present = new Set(subjects.map(s => `${s.kind}\u0000${s.key}`));+ const cause = { op: opts.op ?? 'reconcile', drift: true, ...(last ? { prior_event: last.id, uncertified_from: last.recorded_at } : {}) };+ const base = { sourceId, incarnation: source.incarnation, slug, stream: slug, eventType: 'reconcile', stateHash: hash };+ const link = (kind: string) => kind === 'link' || kind === 'link_transition';+ const drafts: BeliefEventDraft[] = subjects.filter(s => proven.get(`${s.kind}\u0000${s.key}`) !== s.vhash).map(s => ({ ...base,+ lifetime: s.dbOnly && !page ? null : lifetime, subjectKind: s.kind, subjectKey: s.key, trustTier: link(s.kind) ? 'unknown' : s.tier,+ tierBasis: link(s.kind) ? 'unknown' as const : 'row' as const, visibility: s.visibility, value: s.value, claimFp: s.claimFp, validFrom: s.validFrom,+ validUntil: s.validUntil, cause: { ...cause, ...(s.rowNum != null ? { row: s.rowNum } : {}), label: s.label } }));+ for (const r of recorded) {+ if (present.has(`${r.subject_kind}\u0000${r.subject_key}`) || !PROVEN_KINDS.test(r.event_type) || !r.value_hash) continue;+ drafts.push({ ...base, lifetime, subjectKind: r.subject_kind as BeliefEventDraft['subjectKind'], subjectKey: r.subject_key, trustTier: r.trust_tier,+ tierBasis: link(r.subject_kind) ? 'unknown' : 'row', visibility: r.visibility, value: null, claimFp: r.claim_fp, cause: { ...cause, absent: true } });+ }+ if (page) {+ const bound = subjects.filter(s => !s.dbOnly);+ drafts.push({ ...base, lifetime, subjectKind: 'page', subjectKey: pageKey(lifetime!), trustTier: page.tier, visibility: page.visible ? 'world' : 'private',+ value: { revision_after: page.revision, full_set: true, 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 }, ...(page.deleted ? { deleted: true } : {}) },+ cause });+ } else {+ const open = (await readOpenLifetimes(tx, [{ incarnation: source.incarnation, slug }])).get(`${source.incarnation}\u0000${slug}`);+ if (open) {+ await endLifetime(tx, open.page_lifetime);+ drafts.push({ ...base, lifetime: open.page_lifetime, subjectKind: 'page', subjectKey: pageKey(open.page_lifetime), trustTier: 'unknown', tierBasis: 'unknown',+ visibility: 'world', value: { absent: true }, cause: { ...cause, absent: true } });+ }+ }+ return appendBeliefEvents(tx, drafts, { publicationId, origin: 'reconcile', purgesPossible: source.purgesPossible });+ });+ if (appended) await markBeliefCommits(engine, [publicationId]);+ return appended;+}++/** Reconcile every drifted slug the scan finds (deep unless a limit is given). */+export async function reconcileBeliefDrift(engine: BrainEngine, sourceId: string, opts: { limit?: number; op?: string } = {}): Promise<{ scan: DriftScan; reconciled: string[]; events: number }> {+ const scan = await scanBeliefDrift(engine, sourceId, opts.limit ? { limit: opts.limit } : { deep: true });+ const reconciled: string[] = [];+ let events = 0;+ for (const finding of scan.drifted) {+ const n = await reconcileSlug(engine, sourceId, finding.slug, { op: opts.op });+ if (n) { reconciled.push(finding.slug); events += n; }+ }+ return { scan, reconciled, events };+}++/** Open lifetimes with no page at their slug (an untracked hard delete), and events naming a lifetime that does not exist. */+export async function orphanLifetimes(engine: BrainEngine, sourceId: string, limit = 20): Promise<{ count: number; samples: Array<{ slug: string; page_lifetime: string; reason: 'no_page' | 'no_lifetime' }> }> {+ const rows = await engine.executeRaw<{ slug: string; page_lifetime: string; reason: 'no_page' | 'no_lifetime'; total: number }>(`SELECT slug, page_lifetime, reason, count(*) OVER ()::int AS total FROM (+ SELECT l.slug, l.page_lifetime::text AS page_lifetime, 'no_page' AS reason FROM belief_page_lifetimes l JOIN sources s ON s.id = l.source_id AND s.incarnation = l.source_incarnation+ WHERE l.source_id = $1 AND l.ended_at IS NULL AND NOT EXISTS (SELECT 1 FROM pages p WHERE p.source_id = l.source_id AND p.slug = l.slug)+ UNION ALL SELECT DISTINCT e.slug, e.page_lifetime::text, 'no_lifetime' FROM belief_events e+ WHERE e.source_id = $1 AND e.page_lifetime IS NOT NULL AND NOT EXISTS (SELECT 1 FROM belief_page_lifetimes l WHERE l.page_lifetime = e.page_lifetime)+ ) o ORDER BY slug LIMIT ${Math.max(1, Math.floor(limit))}`, [sourceId]);+ return { count: Number(rows[0]?.total ?? 0), samples: rows.map(r => ({ slug: r.slug, page_lifetime: r.page_lifetime, reason: r.reason })) };+}++/** Committed publications of the source with no commit mark (a crash before the post-commit mark). */+export async function unmarkedPublications(engine: BrainEngine, sourceId: string, limit = 1000): Promise<string[]> {+ const rows = await engine.executeRaw<{ publication_id: string }>(`SELECT DISTINCT e.publication_id::text AS publication_id FROM belief_events e+ WHERE e.source_id = $1 AND NOT EXISTS (SELECT 1 FROM belief_commit_marks m WHERE m.publication_id = e.publication_id)+ ORDER BY 1 LIMIT ${Math.max(1, Math.floor(limit))}`, [sourceId]);+ return rows.map(r => r.publication_id);+}++/** Writes the missing commit marks (a reader that finds a committed event with no mark writes one, section 5.3). */+export async function fillCommitMarks(engine: BrainEngine, sourceId: string): Promise<number> {+ let filled = 0;+ for (;;) {+ const ids = await unmarkedPublications(engine, sourceId);+ if (!ids.length) return filled;+ await markBeliefCommits(engine, ids);+ filled += ids.length;+ if (ids.length < 1000) return filled;+ }+}++/** Sources with any coverage event in their current incarnation. */+export async function coveredSources(engine: BrainEngine): Promise<string[]> {+ const rows = await engine.executeRaw<{ source_id: string }>(`SELECT DISTINCT e.source_id FROM belief_events e JOIN sources s ON s.id = e.source_id AND s.incarnation = e.source_incarnation+ WHERE e.subject_kind = 'coverage' ORDER BY 1`);+ return rows.map(r => r.source_id);+}diff --git a/src/core/belief/ledger.ts b/src/core/belief/ledger.tsindex c68a131c8b..c76459a099 100644--- a/src/core/belief/ledger.ts+++ b/src/core/belief/ledger.ts@@ -61,6 +61,12 @@ export function noteBelief(note: BeliefNote): void {store.getStore()?.notes.push(note);}+/** True when an enclosing batch on this async context already records these slugs (a nested writer must not append them twice). */+export function beliefBatchCovers(sourceId: string, slugs: readonly string[]): boolean {+ const outer = store.getStore();+ return !!outer && outer.opts.sourceId === sourceId && slugs.every(slug => outer.opts.slugs.includes(slug));+}+/** 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,diff --git a/test/belief-ledger-coverage.test.ts b/test/belief-ledger-coverage.test.tsnew file mode 100644index 0000000000..7a34cd950b--- /dev/null+++ b/test/belief-ledger-coverage.test.ts@@ -0,0 +1,323 @@+/**+ * Belief ledger coverage probes (docs/designs/BELIEF_LEDGER.md section 11:+ * 13, 15, 16, 17, 33) and the coverage tooling they rest on: intervals,+ * certified status, drift and reconcile, commit marks, coverageAt. Each probe+ * asserts exact event types, keys and values on PGLite and on Postgres when+ * DATABASE_URL is set, and each has a forced probe: a deliberately broken+ * emitter (or marker) that must make it fail.+ */+import { afterEach, describe, expect, test } from 'bun:test';+import { rmSync } from 'node:fs';+import { join } from 'node:path';+import { __setBeliefEmitterFaultForTests, markBeliefCommits, type BeliefEventDraft } from '../src/core/belief/append.ts';+import { currentStateHash, readLedgerSource, withBeliefBatch } from '../src/core/belief/ledger.ts';+import { deleteSourceRow } from '../src/core/source-delete.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { enableBeliefLedger, disableBeliefLedger } from '../src/core/belief/coverage.ts';+import {+ beliefEventVisibility, coverageAt, coverageIntervals, fillCommitMarks, orphanLifetimes, reconcileBeliefDrift, scanBeliefDrift, unmarkedPublications,+} from '../src/core/belief/coverage-report.ts';+import { testBackends } from './helpers/test-backends.ts';+import { beliefBrain, beliefEngineCase, beliefPage, shape, type BeliefBrain } from './helpers/belief-ledger.ts';++afterEach(() => { __setBeliefEmitterFaultForTests(null); });++const page = (o: Parameters<typeof beliefPage>[0] = {}) => beliefPage({ facts: ['Acme raised a seed round', 'Acme has ten staff'],+ takes: ['Acme will win its market', 'Acme will hire fast'], links: ['people/alice-example'], ...o });+const fault = (f: (drafts: BeliefEventDraft[]) => BeliefEventDraft[]) => __setBeliefEmitterFaultForTests(f);+/** The database clock rounded up to the next millisecond, so a JS timestamp is never below a microsecond time read before it. */+const dbNow = async (b: BeliefBrain) => new Date(new Date((await b.engine.executeRaw<{ t: string }>(`SELECT date_trunc('milliseconds', clock_timestamp()) + interval '1 millisecond' AS t`))[0]!.t).getTime()).toISOString();+const pause = () => new Promise(resolve => setTimeout(resolve, 20));++async function seeded(b: BeliefBrain) {+ await b.put('people/alice-example', beliefPage({ type: 'person', title: 'Alice Example' }));+ await b.put('companies/acme-example', page());+}++for (const engineCase of testBackends().map(beliefEngineCase)) {+ describe(`belief ledger coverage (${engineCase.name})`, () => {+ const brain = (run: (b: BeliefBrain) => Promise<void>, opts: { managed?: boolean; enable?: boolean; setup?: (b: BeliefBrain) => Promise<void> } = {}) =>+ beliefBrain(run, { managed: opts.managed ?? true, enable: opts.enable, setup: opts.setup, databaseUrl: engineCase.databaseUrl });++ test('journaled publications leave no drift; the interval is certified on a managed source', async () => {+ await brain(async b => {+ await seeded(b);+ await b.put('companies/acme-example', page({ facts: ['Acme raised a seed round', { claim: 'Acme has ten staff', confidence: '0.5' }] }));+ const scan = await scanBeliefDrift(b.engine, b.sourceId, { deep: true });+ expect(scan.drifted).toEqual([]);+ expect(scan.exact).toBe(true);+ const [interval] = await coverageIntervals(b.engine, b.sourceId);+ expect(interval).toMatchObject({ certified: true, links_certified: 'journaled_only', stopped_at: null, baseline: { complete: true }, drift: [] });+ expect(interval!.watermark).not.toBeNull();+ });+ }, 120_000);++ test('probe 15: unmanaged source, a resolution then its undo between two scans: the hash matches, the interval stays uncertified', async () => {+ const run = async (b: BeliefBrain) => {+ await seeded(b);+ expect((await scanBeliefDrift(b.engine, b.sourceId, { deep: true })).drifted).toEqual([]);+ const [interval] = await coverageIntervals(b.engine, b.sourceId);+ await pause();+ const between = await dbNow(b);+ await b.engine.executeRaw(`UPDATE takes SET resolved_at = now(), resolved_outcome = true, resolved_by = 'grader'+ WHERE claim = 'Acme will win its market' AND page_id = (SELECT id FROM pages WHERE source_id = $1 AND slug = 'companies/acme-example')`, [b.sourceId]);+ const mid = await scanBeliefDrift(b.engine, b.sourceId, { deep: true });+ expect(mid.drifted.map(d => d.slug)).toEqual(['companies/acme-example']);+ await b.engine.executeRaw(`UPDATE takes SET resolved_at = NULL, resolved_outcome = NULL, resolved_by = NULL+ WHERE claim = 'Acme will win its market' AND page_id = (SELECT id FROM pages WHERE source_id = $1 AND slug = 'companies/acme-example')`, [b.sourceId]);+ expect((await scanBeliefDrift(b.engine, b.sourceId, { deep: true })).drifted).toEqual([]);+ return { interval: interval!, at: await coverageAt(b.engine, b.sourceId, between, 'companies/acme-example') };+ };+ await brain(async b => {+ const { interval, at } = await run(b);+ expect(interval).toMatchObject({ certified: false, links_certified: false, baseline: { complete: true } });+ expect(at).toMatchObject({ ok: true, certified: false, uncertified_reason: 'unmanaged' });+ }, { managed: false });+ // Forced probe: an emitter that stamps the unmanaged activation certified is caught.+ await brain(async b => {+ const { interval, at } = await run(b);+ expect(interval.certified).toBe(true);+ expect(at).toMatchObject({ ok: true, certified: true });+ }, { managed: false, enable: false, setup: async b => {+ fault(drafts => drafts.map(d => d.eventType === 'coverage.complete' ? { ...d, cause: { ...d.cause, certified: true } } : d));+ await b.enable();+ __setBeliefEmitterFaultForTests(null);+ } });+ }, 180_000);++ test('drift on a managed source: reconcile restates the moved keys and the slug interval stays uncertified after a clean hash', async () => {+ await brain(async b => {+ await seeded(b);+ await b.put('people/bob-example', beliefPage({ type: 'person', title: 'Bob Example' }));+ const before = await b.lastId();+ const prior = (await b.events()).filter(e => e.slug === 'companies/acme-example').at(-1)!;+ await b.engine.executeRaw(`INSERT INTO links (from_page_id, to_page_id, link_type, link_source, context, origin_page_id)+ SELECT a.id, p.id, 'mentions', 'markdown', 'bypass', a.id FROM pages a, pages p+ WHERE a.source_id = $1 AND a.slug = 'companies/acme-example' AND p.source_id = $1 AND p.slug = 'people/bob-example'`, [b.sourceId]);+ const scan = await scanBeliefDrift(b.engine, b.sourceId, { deep: true });+ expect(scan.drifted.map(d => d.slug)).toEqual(['companies/acme-example']);+ expect(scan.drifted[0]!.recorded_hash).toBe(prior.state_hash);+ const fixed = await reconcileBeliefDrift(b.engine, b.sourceId);+ expect(fixed.reconciled).toEqual(['companies/acme-example']);+ const events = await b.events(before);+ const current = await b.engine.transaction(tx => currentStateHash(tx, b.sourceId, prior.source_incarnation, 'companies/acme-example'));+ // The creation snapshot proves no key, so every current key is restated, then the page carries the full set.+ expect(shape(events).sort()).toEqual(['fact:reconcile', 'fact:reconcile', 'link:reconcile', 'link:reconcile', 'page:reconcile', 'take:reconcile', 'take:reconcile']);+ expect(events.every(e => e.origin === 'reconcile' && e.state_hash === current.hash && e.cause.uncertified_from === new Date(prior.recorded_at).toISOString())).toBe(true);+ const bypass = events.find(e => e.subject_kind === 'link' && e.value!.context === 'bypass')!;+ expect(bypass).toMatchObject({ trust_tier: 'unknown', tier_basis: 'unknown', value: { context: 'bypass', link_kind: null } });+ expect(events.find(e => e.subject_kind === 'page')!.value).toMatchObject({ full_set: true, counts: { facts: 2, takes: 2, links: 2, link_transitions: 0 } });+ expect((await scanBeliefDrift(b.engine, b.sourceId, { deep: true })).drifted).toEqual([]);+ await b.engine.executeRaw(`DELETE FROM links WHERE context = 'bypass'`);+ const again = await reconcileBeliefDrift(b.engine, b.sourceId);+ const second = await b.events(events.at(-1)!.id);+ // A per-key reconcile event now proves every surviving key: only the gone link and the page are written.+ expect(again.reconciled).toEqual(['companies/acme-example']);+ expect(shape(second).sort()).toEqual(['link:reconcile', 'page:reconcile']);+ expect(second.find(e => e.subject_kind === 'link')).toMatchObject({ subject_key: bypass.subject_key, value: null, cause: { absent: true } });+ const [interval] = await coverageIntervals(b.engine, b.sourceId);+ expect(interval!.certified).toBe(true);+ expect(interval!.drift.map(d => [d.slug, d.from])).toEqual([['companies/acme-example', new Date(prior.recorded_at).toISOString()],+ ['companies/acme-example', new Date(events.at(-1)!.recorded_at).toISOString()]]);+ const inside = new Date(new Date(events[0]!.recorded_at).getTime() - 1).toISOString();+ expect(await coverageAt(b.engine, b.sourceId, inside, 'companies/acme-example')).toMatchObject({ ok: true, certified: false, uncertified_reason: 'drift' });+ expect(await coverageAt(b.engine, b.sourceId, await dbNow(b), 'companies/acme-example')).toMatchObject({ ok: true, certified: true });+ // Forced probe: an emitter that drops the page-level reconcile leaves no drift mark, so the interval would read certified.+ fault(drafts => drafts.filter(d => !(d.eventType === 'reconcile' && d.subjectKind === 'page')));+ await b.engine.executeRaw(`INSERT INTO links (from_page_id, to_page_id, link_type, link_source, context, origin_page_id)+ SELECT a.id, p.id, 'mentions', 'markdown', 'forced', a.id FROM pages a, pages p+ WHERE a.source_id = $1 AND a.slug = 'companies/acme-example' AND p.source_id = $1 AND p.slug = 'people/bob-example'`, [b.sourceId]);+ const marks = (await coverageIntervals(b.engine, b.sourceId))[0]!.drift.length;+ await reconcileBeliefDrift(b.engine, b.sourceId);+ expect((await coverageIntervals(b.engine, b.sourceId))[0]!.drift.length).toBe(marks);+ });+ }, 180_000);++ test('probe 13: a stalled publication stays unproven until its commit mark, then becomes visible; a later event of the page proves it', async () => {+ await brain(async b => {+ await seeded(b);+ const slug = 'companies/acme-example';+ const beforeTx = await dbNow(b);+ await pause();+ const mark = await b.lastId();+ await b.engine.transaction(async tx => {+ await tx.lockPageKeys([{ sourceId: b.sourceId, slug }]);+ await withBeliefBatch(tx, { sourceId: b.sourceId, slugs: [slug], op: 'probe_stall', origin: 'unmanaged' }, () =>+ tx.executeRaw(`UPDATE facts SET confidence = 0.4 WHERE source_id = $1 AND fact = 'Acme has ten staff'`, [b.sourceId]));+ await new Promise(resolve => setTimeout(resolve, 400));+ });+ const [event] = await b.events(mark);+ expect(shape([event!])).toEqual(['fact:fact.revised']);+ expect(event!.value).toMatchObject({ fact: 'Acme has ten staff', confidence: 0.4 });+ const stalled = new Date(new Date(event!.recorded_at).getTime() + 100).toISOString();+ const committed = await dbNow(b);+ expect(await unmarkedPublications(b.engine, b.sourceId)).toEqual([event!.publication_id]);+ expect(await beliefEventVisibility(b.engine, event!.id, beforeTx)).toBe('not_visible');+ expect(await beliefEventVisibility(b.engine, event!.id, stalled)).toBe('unproven');+ expect(await beliefEventVisibility(b.engine, event!.id, committed)).toBe('unproven');+ expect(await fillCommitMarks(b.engine, b.sourceId)).toBe(1);+ const marked = await dbNow(b);+ expect(await beliefEventVisibility(b.engine, event!.id, marked)).toBe('visible');+ expect(await beliefEventVisibility(b.engine, event!.id, committed)).toBe('unproven');+ await b.engine.executeRaw('DELETE FROM belief_commit_marks WHERE publication_id = $1::uuid', [event!.publication_id]);+ await b.put(slug, page({ prose: 'A later edit.' }));+ const afterLater = await dbNow(b);+ await markBeliefCommits(b.engine, [event!.publication_id]);+ expect(shape(await b.events(event!.id))).toEqual(['page:page.published', 'fact:fact.revised']);+ expect(await beliefEventVisibility(b.engine, event!.id, afterLater)).toBe('visible');+ // Forced probe: a marker that stamps the event's own recorded time (an observer's early transaction start) makes the stalled interval visible.+ await b.engine.executeRaw('DELETE FROM belief_commit_marks WHERE publication_id = $1::uuid', [event!.publication_id]);+ await b.engine.executeRaw(`INSERT INTO belief_commit_marks (publication_id, observed_at) SELECT publication_id, max(recorded_at) FROM belief_events+ WHERE publication_id = $1::uuid GROUP BY publication_id`, [event!.publication_id]);+ expect(await beliefEventVisibility(b.engine, event!.id, stalled)).toBe('visible');+ }, { managed: false });+ }, 120_000);++ test('probe 33: an observer that starts before a publication commits and marks it afterwards writes observed_at at or after recorded_at', async () => {+ await brain(async b => {+ await seeded(b);+ const mark = await b.lastId();+ const observe = async (publish: () => Promise<void>) => b.engine.transaction(async obs => {+ const [{ start }] = await obs.executeRaw<{ start: string }>('SELECT now() AS start');+ await publish();+ const other = engineCase.name === 'postgres' ? b.engine : obs;+ const [event] = await other.executeRaw<{ publication_id: string; recorded_at: string }>(`SELECT publication_id::text AS publication_id, recorded_at+ FROM belief_events WHERE source_id = $1 AND id > $2 ORDER BY id LIMIT 1`, [b.sourceId, mark]);+ await other.executeRaw('DELETE FROM belief_commit_marks WHERE publication_id = $1::uuid', [event!.publication_id]);+ await markBeliefCommits(obs, [event!.publication_id]);+ const [row] = await obs.executeRaw<{ observed_at: string }>('SELECT observed_at FROM belief_commit_marks WHERE publication_id = $1::uuid', [event!.publication_id]);+ await obs.executeRaw('DELETE FROM belief_commit_marks WHERE publication_id = $1::uuid', [event!.publication_id]);+ await obs.executeRaw(`INSERT INTO belief_commit_marks (publication_id, observed_at) SELECT publication_id, now() FROM belief_events+ WHERE publication_id = $1::uuid GROUP BY publication_id`, [event!.publication_id]);+ const [broken] = await obs.executeRaw<{ observed_at: string }>('SELECT observed_at FROM belief_commit_marks WHERE publication_id = $1::uuid', [event!.publication_id]);+ return { start: new Date(start).getTime(), recorded: new Date(event!.recorded_at).getTime(), observed: new Date(row!.observed_at).getTime(),+ broken: new Date(broken!.observed_at).getTime() };+ });+ if (engineCase.name === 'postgres') {+ const r = await observe(async () => { await b.put('companies/acme-example', page({ prose: 'Observed edit.' })); });+ expect(r.start).toBeLessThan(r.recorded);+ expect(r.observed).toBeGreaterThanOrEqual(r.recorded);+ // Forced probe: a marker using now() (the observer's start) writes a mark below the event's recorded time.+ expect(r.broken).toBeLessThan(r.recorded);+ return;+ }+ // PGLite runs one transaction at a time, so an observer cannot start before a publication commits: the publication precedes it.+ await b.put('companies/acme-example', page({ prose: 'Observed edit.' }));+ const r = await observe(async () => {});+ expect(r.start).toBeGreaterThanOrEqual(r.recorded);+ expect(r.observed).toBeGreaterThanOrEqual(r.recorded);+ expect(r.broken).toBe(r.start);+ });+ }, 120_000);++ test('probe 16: activation interrupted by a concurrent edit resumes with one consistent cut per page', async () => {+ await brain(async b => {+ await b.put('people/alice-example', beliefPage({ type: 'person', title: 'Alice Example' }));+ await b.put('companies/acme-example', page());+ await b.put('companies/beta-example', page({ title: 'Beta Example' }));+ await b.put('companies/gamma-example', page({ title: 'Gamma Example' }));+ fault(drafts => { if (drafts.some(d => d.eventType === 'baseline' && d.slug === 'companies/gamma-example')) throw new Error('interrupted'); return drafts; });+ await expect(enableBeliefLedger(b.engine, b.sourceId)).rejects.toThrow('interrupted');+ __setBeliefEmitterFaultForTests(null);+ const [running] = await coverageIntervals(b.engine, b.sourceId);+ expect(running).toMatchObject({ watermark: null, baseline: { pages_done: 2, pending: 2, complete: false } });+ expect((await scanBeliefDrift(b.engine, b.sourceId, { deep: true })).checked).toBe(0);+ const mark = await b.lastId();+ await b.put('companies/gamma-example', page({ title: 'Gamma Example', facts: ['Acme raised a seed round', 'Gamma has twelve staff'] }));+ const edited = await b.events(mark);+ expect(shape(edited).sort()).toEqual(['fact:fact.asserted', 'fact:fact.retracted', 'page:page.published']);+ const run = await enableBeliefLedger(b.engine, b.sourceId);+ expect(run).toMatchObject({ resumed: true, pages: 2, complete: true, certified: true });+ const events = await b.events();+ const baselines = events.filter(e => e.event_type === 'baseline' && e.subject_kind === 'page');+ expect(baselines.map(e => e.slug).sort()).toEqual(['companies/acme-example', 'companies/beta-example', 'companies/gamma-example', 'people/alice-example']);+ const gamma = events.filter(e => e.slug === 'companies/gamma-example');+ expect(shape(gamma)).toEqual(['page:page.published', 'fact:fact.asserted', 'fact:fact.retracted', 'page:baseline']);+ const cut = gamma.at(-1)!;+ const now = await b.engine.transaction(tx => currentStateHash(tx, b.sourceId, cut.source_incarnation, 'companies/gamma-example'));+ expect(cut.state_hash).toBe(now.hash);+ expect(cut.value).toMatchObject({ snapshot: true, counts: { facts: 2, takes: 2, links: 1 } });+ const edit = new Date(gamma[0]!.recorded_at).toISOString();+ expect(await coverageAt(b.engine, b.sourceId, edit, 'companies/gamma-example')).toMatchObject({ ok: false, code: 'coverage_from', from: new Date(cut.recorded_at).toISOString() });+ expect(await coverageAt(b.engine, b.sourceId, edit, 'companies/acme-example')).toMatchObject({ ok: true, certified: true });+ expect((await scanBeliefDrift(b.engine, b.sourceId, { deep: true })).drifted).toEqual([]);+ const [interval] = await coverageIntervals(b.engine, b.sourceId);+ expect(interval).toMatchObject({ baseline: { pages_done: 4, pending: null, complete: true }, certified: true });+ expect(interval!.watermark).toBe(new Date(events.at(-1)!.recorded_at).toISOString());+ }, { enable: false });+ // Forced probe: a resume whose emitter drops a page's baseline leaves that page with no cut.+ await brain(async b => {+ await b.put('companies/acme-example', page());+ await b.put('companies/gamma-example', page({ title: 'Gamma Example' }));+ fault(drafts => drafts.filter(d => !(d.eventType === 'baseline' && d.slug === 'companies/gamma-example')));+ await enableBeliefLedger(b.engine, b.sourceId);+ __setBeliefEmitterFaultForTests(null);+ const baselines = (await b.events()).filter(e => e.event_type === 'baseline' && e.subject_kind === 'page');+ expect(baselines.map(e => e.slug)).not.toContain('companies/gamma-example');+ expect(await coverageAt(b.engine, b.sourceId, await dbNow(b), 'companies/gamma-example')).toMatchObject({ ok: false, code: 'coverage_from', from: null });+ }, { enable: false });+ }, 180_000);++ test('probe 16: activation after large-page version pruning baselines the page per subject at its current state', async () => {+ await brain(async b => {+ const big = (n: number) => page({ prose: `Edit ${n}. ${'Long prose. '.repeat(100_000)}` });+ await b.put('people/alice-example', beliefPage({ type: 'person', title: 'Alice Example' }));+ for (let n = 0; n < 7; n++) await b.put('companies/huge-example', big(n));+ const [{ versions }] = await b.engine.executeRaw<{ versions: number }>(`SELECT count(*)::int AS versions FROM page_versions v JOIN pages p ON p.id = v.page_id+ WHERE p.source_id = $1 AND p.slug = 'companies/huge-example'`, [b.sourceId]);+ expect(Number(versions)).toBeLessThan(6);+ await enableBeliefLedger(b.engine, b.sourceId);+ const events = (await b.events()).filter(e => e.slug === 'companies/huge-example');+ expect(shape(events).sort()).toEqual(['fact:baseline', 'fact:baseline', 'link:baseline', 'page:baseline', 'take:baseline', 'take:baseline']);+ const head = events.find(e => e.subject_kind === 'page')!;+ expect(head.value).toMatchObject({ snapshot: false, counts: { facts: 2, takes: 2, links: 1 } });+ const now = await b.engine.transaction(tx => currentStateHash(tx, b.sourceId, head.source_incarnation, 'companies/huge-example'));+ expect(events.every(e => e.state_hash === now.hash && e.origin === 'baseline')).toBe(true);+ expect(events.filter(e => e.subject_kind === 'link').every(e => e.trust_tier === 'unknown' && e.tier_basis === 'unknown')).toBe(true);+ // Forced probe: an emitter that writes the large page as a text-free snapshot drops the values no retained version holds.+ await disableBeliefLedger(b.engine, b.sourceId);+ fault(drafts => drafts.filter(d => d.subjectKind === 'page' || d.eventType !== 'baseline'));+ const mark = await b.lastId();+ await enableBeliefLedger(b.engine, b.sourceId);+ expect(shape((await b.events(mark)).filter(e => e.slug === 'companies/huge-example'))).toEqual(['page:baseline']);+ }, { enable: false });+ }, 300_000);++ test('probe 17: a source removed and re-added with the same id inherits no event, interval or watermark', async () => {+ await brain(async b => {+ await seeded(b);+ const old = (await readLedgerSource(b.engine, b.sourceId))!;+ const oldEvents = await b.events();+ expect(await deleteSourceRow(b.engine, b.sourceId)).toBe(true);+ await b.engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [b.sourceId, b.root]);+ rmSync(join(b.root, 'companies'), { recursive: true, force: true });+ rmSync(join(b.root, 'people'), { recursive: true, force: true });+ await claimWorktree(b.engine, b.sourceId, b.root);+ const fresh = (await readLedgerSource(b.engine, b.sourceId))!;+ expect(fresh.incarnation).not.toBe(old.incarnation);+ expect(fresh.coverage).toBeNull();+ expect(await coverageIntervals(b.engine, b.sourceId)).toEqual([]);+ expect(await coverageAt(b.engine, b.sourceId, await dbNow(b))).toMatchObject({ ok: false, code: 'coverage_from', from: null });+ const mark = await b.lastId();+ await b.put('companies/acme-example', page());+ expect(await b.events(mark)).toEqual([]);+ await enableBeliefLedger(b.engine, b.sourceId);+ const intervals = await coverageIntervals(b.engine, b.sourceId);+ expect(intervals.map(i => [i.incarnation, i.baseline.pages_done])).toEqual([[fresh.incarnation, 1]]);+ expect(Date.parse(intervals[0]!.watermark!)).toBeGreaterThan(new Date(oldEvents.at(-1)!.recorded_at).getTime());+ const after = await b.events(mark);+ expect(after.every(e => e.source_incarnation === fresh.incarnation)).toBe(true);+ const lifetime = after.find(e => e.subject_kind === 'page')!.page_lifetime;+ expect(oldEvents.some(e => e.page_lifetime === lifetime)).toBe(false);+ expect((await b.events()).filter(e => e.source_incarnation === old.incarnation)).toEqual(oldEvents);+ // Forced probe: an emitter that stamps the old incarnation on the new source's coverage hides the new interval.+ await disableBeliefLedger(b.engine, b.sourceId);+ fault(drafts => drafts.map(d => ({ ...d, incarnation: old.incarnation })));+ await enableBeliefLedger(b.engine, b.sourceId).catch(() => null);+ __setBeliefEmitterFaultForTests(null);+ expect((await coverageIntervals(b.engine, b.sourceId)).map(i => i.incarnation)).toEqual([fresh.incarnation]);+ expect((await coverageIntervals(b.engine, b.sourceId)).at(-1)!.stopped_at).not.toBeNull();+ }, { managed: false });+ }, 120_000);+ });+}