Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
W2 page-at-time: known_as_of on get_page and get_versions over ledger validity intervals; rename leaves a preimage
garrytan56b7bf48450f
diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex 72aac63a13..7da992bc7f 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -2263,6 +2263,55 @@ covers the whole retry budget each grant authorizes. A resumed run replays thegrant it already made instead of granting another cycle. A signature-mismatchedvector is never reconciled; it is re-embedded.+## Recorded-time reads++`get_page {known_as_of}` and `get_versions {known_as_of}` read a page as this+brain had recorded it at an instant, from the belief ledger+([design, section 10](../designs/BELIEF_LEDGER.md#10-what-w2s-first-slice-needs-from-w1)).+`known_as_of` is recorded time: an ISO 8601 instant with a zone. It is not+`as_of` on `get_links`, which is valid time (a date). A read answers with the+interval the instant falls in, `certified` (false with `uncertified_reason` on+an unmanaged source, a drifted interval or a truncated walk), and a `body` of+`live`, `version`, `segmented` (read it through `body_ref`) or `unavailable`+with a `body_reason` (`purged`, `expired`, `hard_deleted`, `pruned`,+`version_missing`). A body no retained version holds is disclosed, never+borrowed from the version next to it. The refusals below change nothing; run+`gbrain beliefs status --source <id> --json` to see the coverage a read is+checked against.++### Coverage from++The ledger does not cover the instant: it is before the ledger was enabled on+the source, or before the page's baseline cut. Earlier times are unknown, not+empty. `reason` is `not_recorded`, or `backfill_only` / `backfill_incomplete`+when `gbrain beliefs backfill` seeded best-effort history for the page: that+history carries source times only, so it never answers a recorded-time read.+Ask about an instant at or after the time the message names.++### Coverage gap++The ledger was not recording at the instant: coverage was stopped+(`reason: not_covered`), or a backup restore replaced the ledger with an+archive, and what happened between the archive's time and the restore is+unknown (`reason: restore`). Ask about an instant outside the gap the message+names.++### Clock mismatch++`known_as_of` got a calendar date (`reason: date_for_instant`). A date is+valid time; recorded time needs an instant. Pass a full instant such as+`2026-10-01T12:00:00Z`.++### Known as of unproven++A change to the page was recorded before the instant, but nothing proves it+had committed by then: its commit mark is later, and no later write to the+same page was recorded by the instant (section 5.3 of the design). The page at+that instant can't be stated either way, so the read refuses rather than+guess. The refusal is `retryable`: ask about an instant before the write's+recorded time, or after its commit was observed (the message names the write).+A stalled transaction stays unproven until it commits and is marked.+## Repair refusal codesEach heading below is the `docs` anchor a refusal carries.diff --git a/src/core/belief/page-at-time.ts b/src/core/belief/page-at-time.tsnew file mode 100644index 0000000000..16a966fba3--- /dev/null+++ b/src/core/belief/page-at-time.ts@@ -0,0 +1,274 @@+/**+ * Page-at-time (W2 first slice, docs/designs/BELIEF_LEDGER.md section 10):+ * what a page was, as the brain had recorded it at a recorded-time instant+ * `known_as_of`. Each version's validity interval comes from the page+ * lifetime's publication events, never from the newest `page_versions` row+ * at or before T (versions are preimages, so that picks the wrong side of an+ * edit). An event counts at T under the section 5.3 visibility rule: its+ * commit mark is at or before T, or a later event of the same lifetime was+ * recorded at or before T; recorded after T, it does not count; otherwise the+ * read refuses `known_as_of_unproven` instead of guessing. The body of+ * interval i is the preimage version written by the transition that closed+ * it (versions of one revision pair with that revision's closed intervals in+ * order), or the live page for the open head. A body no version holds any+ * more is disclosed, never borrowed from a neighbour.+ */+import type { BrainEngine } from '../engine.ts';+import { opError } from '../ops/contract.ts';+import { readFix } from '../ops/op-fix.ts';+import { privatePagesFilterFragment } from '../search/private-visibility.ts';+import { PAGE_INLINE_MAX_BYTES } from '../page-size-policy.ts';+import { coverageAt } from './coverage-report.ts';++const INSTANT = /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d{1,9})?)?(?:Z|[+-]\d{2}(?::?\d{2})?)$/i;+const DATE_ONLY = /^\d{4}-\d{2}(?:-\d{2})?$/;++/** Parses `known_as_of`: an ISO 8601 instant with a zone. A bare date is the valid-time clock (`as_of`), refused `clock_mismatch`. */+export function parseKnownAsOf(value: unknown): Date {+ const text = typeof value === 'string' ? value.trim() : '';+ if (DATE_ONLY.test(text)) {+ throw opError('clock_mismatch', `known_as_of needs an instant with a time and zone (for example 2026-10-01T12:00:00Z), not the date ${text}.`,+ 'known_as_of is recorded time: when the brain had recorded something. A calendar date is valid time, which as_of takes on get_links. Pass a full instant.',+ { reason: 'date_for_instant' });+ }+ const at = INSTANT.test(text) ? new Date(text.replace(' ', 'T')) : null;+ if (!at || Number.isNaN(at.getTime())) {+ throw opError('invalid_params', 'known_as_of must be an ISO 8601 instant with a zone, for example 2026-10-01T12:00:00Z.', 'Pass an instant such as 2026-10-01T12:00:00Z.');+ }+ return at;+}++interface PageEventRow {+ id: number; lifetime: string; slug: string; event_type: string; origin: string; visibility: string;+ recorded_at: string; observed_at: string | null; source_time: string | null; value: Record<string, unknown> | null; purged: boolean; proven: boolean;+}++export type BodyStatus = 'live' | 'version' | 'segmented' | 'unavailable';+export type BodyReason = 'purged' | 'expired' | 'hard_deleted' | 'pruned' | 'version_missing';+export interface PageInterval {+ lifetime: string;+ slug: string;+ revision: string | null;+ deleted: boolean;+ /** The transition that opened the interval: `recorded_at` bounds when it was written, `visible_at` is its commit mark. */+ event: { id: number; type: string; origin: string; recorded_at: string; visible_at: string | null; source_time: string | null; visibility: string };+ /** When the next transition known at T was recorded; null for the interval current at T. */+ until: string | null;+ body: BodyStatus;+ /** Why no body is returned. */+ body_reason?: BodyReason;+ version_id?: number;+ page?: { title: string | null; type: string | null; frontmatter: Record<string, unknown>; tags: string[]; compiled_truth: string | null; timeline: string | null; body_bytes: number | null };+}++export interface PageAtTime {+ slug: string;+ source_id: string;+ known_as_of: string;+ certified: boolean;+ uncertified_reason: string | null;+ coverage_cut: string;+ /** Intervals of the page at `slug` known at T, oldest first; the interval current at T has `until: null`. */+ intervals: PageInterval[];+ /** The interval current at T, when a page stood at the slug then. */+ current: PageInterval | null;+ /** The page row of the lifetime current at T, when it still exists. */+ page_id: number | null;+}++const GONE: Record<string, BodyReason> = { 'page.purged': 'purged', 'page.expired': 'expired' };+const SKIPPED = ['backfill', 'trust.retiered', 'trust.contested', 'trust.held', 'derived.hidden'];+const json = (v: unknown) => typeof v === 'string' ? JSON.parse(v) : v;+const iso = (v: unknown) => v == null ? null : new Date(v as string).toISOString();++/** The page events of every lifetime that ever stood at `slug` in the source's current incarnation (backfill rows excluded), each with whether a later event of its lifetime was recorded by T. */+async function readPageEvents(engine: BrainEngine, sourceId: string, slug: string, at: Date): Promise<PageEventRow[]> {+ const rows = await engine.executeRaw<PageEventRow>(`WITH inc AS (SELECT incarnation FROM sources WHERE id = $1),+ lt AS (SELECT DISTINCT e.page_lifetime FROM belief_events e, inc WHERE e.source_id = $1 AND e.source_incarnation = inc.incarnation AND e.slug = $2+ AND e.subject_kind = 'page' AND e.page_lifetime IS NOT NULL AND e.origin <> 'backfill')+ SELECT e.id, e.page_lifetime::text AS lifetime, e.slug, e.event_type, e.origin, e.visibility, e.recorded_at, m.observed_at, e.source_time, e.value, e.purged,+ EXISTS (SELECT 1 FROM belief_events l WHERE l.source_id = e.source_id AND l.page_lifetime = e.page_lifetime AND l.id > e.id AND l.origin <> 'backfill'+ AND l.recorded_at <= $3::timestamptz) AS proven+ FROM belief_events e LEFT JOIN belief_commit_marks m ON m.publication_id = e.publication_id+ WHERE e.source_id = $1 AND e.page_lifetime IN (SELECT page_lifetime FROM lt) AND e.subject_kind = 'page' AND e.origin <> 'backfill'+ AND NOT (e.event_type = ANY($4::text[]))+ ORDER BY e.id`, [sourceId, slug, at.toISOString(), SKIPPED]);+ return rows.map(r => ({ ...r, id: Number(r.id), recorded_at: iso(r.recorded_at)!, observed_at: iso(r.observed_at), source_time: iso(r.source_time),+ value: json(r.value) as PageEventRow['value'], purged: r.purged === true, proven: r.proven === true }));+}++function visibilityAt(e: PageEventRow, t: number): 'visible' | 'not_visible' | 'unproven' {+ if (e.observed_at && Date.parse(e.observed_at) <= t) return 'visible';+ if (Date.parse(e.recorded_at) > t) return 'not_visible';+ return e.proven ? 'visible' : 'unproven';+}++interface Draft { lifetime: string; slug: string; revision: string | null; deleted: boolean; gone: BodyReason | null; content: boolean; event: PageInterval['event'] }++/** Replays one lifetime's events into intervals: one per content state (a revision, or a view change at one revision), rename or removal. A purge-redacted event keeps its own interval, with no revision. */+function replay(events: PageEventRow[]): Draft[] {+ const out: Draft[] = [];+ let state: { slug: string; deleted: boolean; revision: string | null } | null = null;+ for (const e of events) {+ const v = e.value ?? {};+ const gone = GONE[e.event_type] ?? (v.hard === true ? 'hard_deleted' : null);+ const content = gone == null && (typeof v.revision_after === 'string' || e.purged);+ const next: { slug: string; deleted: boolean; revision: string | null } = { slug: e.slug, revision: content ? (v.revision_after as string | undefined) ?? null : state?.revision ?? null,+ deleted: gone != null || e.event_type === 'page.deleted' || (v.deleted === true && e.event_type !== 'page.restored') };+ if (state && !content && gone == null && next.slug === state.slug && next.deleted === state.deleted) continue;+ state = next;+ out.push({ lifetime: e.lifetime, slug: next.slug, revision: next.revision, deleted: next.deleted, gone, content,+ event: { id: e.id, type: e.event_type, origin: e.origin, recorded_at: e.recorded_at, visible_at: e.observed_at, source_time: e.source_time, visibility: e.visibility } });+ }+ return out;+}++/**+ * Reads the page at `slug` as recorded at `at`. Refuses `coverage_from`+ * before the ledger covers the time (naming the page's best-effort backfill+ * when one exists), `coverage_gap` inside a stopped interval or restore gap,+ * and `known_as_of_unproven` when a transition of the page straddles T.+ * `history` returns every interval known at T (get_versions); otherwise only+ * the one current at T.+ */+export async function readPageAtTime(engine: BrainEngine, q: { sourceId: string; slug: string; at: Date; history?: boolean; withBodies?: boolean }): Promise<PageAtTime> {+ const t = q.at.getTime();+ const [{ now }] = await engine.executeRaw<{ now: string }>('SELECT clock_timestamp() AS now');+ if (t > Date.parse(iso(now)!)) {+ throw opError('invalid_params', `known_as_of ${q.at.toISOString()} is in the future.`, 'Pass an instant at or before now; omit known_as_of for the current page.');+ }+ const events = await readPageEvents(engine, q.sourceId, q.slug, q.at);+ const pageCov = await coverageAt(engine, q.sourceId, q.at, q.slug);+ let cov = pageCov;+ if (!pageCov.ok) {+ if (pageCov.code === 'coverage_gap') throw coverageRefusal(pageCov, q);+ const sourceCov = await coverageAt(engine, q.sourceId, q.at);+ if (!sourceCov.ok) throw coverageRefusal(sourceCov, q, await backfillSummary(engine, q.sourceId, q.slug));+ const first = events.find(e => e.slug === q.slug);+ if (first?.event_type === 'baseline' && Date.parse(first.recorded_at) > t) {+ throw coverageRefusal({ ...pageCov, from: first.recorded_at }, q, await backfillSummary(engine, q.sourceId, q.slug));+ }+ cov = sourceCov;+ }+ if (!cov.ok) throw coverageRefusal(cov, q);++ const lifetimes: Array<{ lifetime: string; all: Draft[]; known: Draft[] }> = [];+ for (const lifetime of [...new Set(events.map(e => e.lifetime))]) {+ const list = events.filter(e => e.lifetime === lifetime);+ const vis = list.map(e => visibilityAt(e, t));+ const last = vis.lastIndexOf('visible');+ const straddling = list.find((_, i) => i > last && vis[i] === 'unproven');+ if (straddling) {+ throw opError('known_as_of_unproven', `A change to ${q.slug} recorded at ${straddling.recorded_at} was not yet proven committed at ${q.at.toISOString()}.`,+ `The write was in flight at that instant, so the page then cannot be stated either way. Ask about an instant before ${straddling.recorded_at}, or after the write was observed committed.`,+ { retryable: true });+ }+ lifetimes.push({ lifetime, all: replay(list), known: replay(list.slice(0, last + 1)) });+ }+ const current = lifetimes.map(l => ({ l, head: l.known[l.known.length - 1] }))+ .filter((x): x is { l: typeof x.l; head: Draft } => !!x.head && x.head.slug === q.slug && x.head.gone == null)+ .sort((a, b) => Number(a.head.deleted) - Number(b.head.deleted) || b.head.event.id - a.head.event.id)[0];+ const keep = q.history ? lifetimes.flatMap(l => l.known.filter(d => d.slug === q.slug)) : current ? [current.head] : [];+ const intervals = (await withBodies(engine, lifetimes, keep, q.withBodies !== false))+ .sort((a, b) => Date.parse(a.event.recorded_at) - Date.parse(b.event.recorded_at) || a.event.id - b.event.id);+ const head = current ? intervals.find(i => i.event.id === current.head.event.id) ?? null : null;+ const [lt] = current ? await engine.executeRaw<{ page_id: number | null }>('SELECT page_id FROM belief_page_lifetimes WHERE page_lifetime = $1::uuid', [current.l.lifetime]) : [];+ return { slug: q.slug, source_id: q.sourceId, known_as_of: q.at.toISOString(), certified: cov.certified, uncertified_reason: cov.uncertified_reason, coverage_cut: cov.cut,+ intervals, current: head, page_id: lt?.page_id == null ? null : Number(lt.page_id) };+}++/**+ * Bodies for `keep`. A content interval's body is the preimage version the next content transition wrote: the closed+ * intervals of one revision pair with that revision's versions in id order, newest with newest. The lifetime's open+ * content interval reads the live page while the page still stands at that revision.+ */+async function withBodies(engine: BrainEngine, lifetimes: Array<{ lifetime: string; all: Draft[]; known: Draft[] }>, keep: Draft[], bodies: boolean): Promise<PageInterval[]> {+ const ids = [...new Set(keep.map(d => d.lifetime))];+ if (!ids.length) return [];+ const rows = await engine.executeRaw<{ page_lifetime: string; page_id: number | null; ended_at: string | null; revision: string | null; body_storage: string | null; body_bytes: number | null }>(+ `SELECT l.page_lifetime::text AS page_lifetime, l.page_id, l.ended_at, p.knowledge_revision::text AS revision, p.body_storage,+ COALESCE(p.body_bytes, octet_length(COALESCE(p.compiled_truth, '')) + octet_length(COALESCE(p.timeline, ''))) AS body_bytes+ FROM belief_page_lifetimes l LEFT JOIN pages p ON p.id = l.page_id WHERE l.page_lifetime = ANY($1::uuid[])`, [ids]);+ const out: PageInterval[] = [];+ for (const lifetime of ids) {+ const l = lifetimes.find(x => x.lifetime === lifetime)!;+ const row = rows.find(r => r.page_lifetime === lifetime);+ const pageId = row?.page_id == null || row.revision == null ? null : Number(row.page_id);+ const content = l.all.filter(d => d.content);+ const openHead = row && row.ended_at == null && pageId != null ? content[content.length - 1] ?? null : null;+ const liveHead = openHead && openHead.revision === row!.revision ? openHead : null;+ const revisions = [...new Set(content.map(d => d.revision).filter((r): r is string => !!r))];+ const versions = pageId != null && bodies && revisions.length ? await engine.executeRaw<Record<string, unknown>>(`SELECT id, knowledge_revision::text AS revision,+ compiled_truth, timeline, title, type, frontmatter, tags, body_storage,+ COALESCE(body_bytes, octet_length(COALESCE(compiled_truth, '')) + octet_length(COALESCE(timeline, ''))) AS body_bytes+ FROM page_versions WHERE page_id = $1 AND knowledge_revision = ANY($2::uuid[]) ORDER BY id`, [pageId, revisions]) : [];+ const pairing = new Map<number, Record<string, unknown>>();+ for (const revision of revisions) {+ const closed = content.filter(d => d.revision === revision && d !== liveHead);+ const held = versions.filter(v => v.revision === revision);+ for (let i = 1; i <= Math.min(closed.length, held.length); i++) pairing.set(closed[closed.length - i]!.event.id, held[held.length - i]!);+ }+ const gone = l.all.find(d => d.gone)?.gone ?? (pageId == null ? 'hard_deleted' : null);+ const large = row?.body_storage === 'segmented' || Number(row?.body_bytes ?? 0) > PAGE_INLINE_MAX_BYTES;+ for (const d of keep.filter(x => x.lifetime === lifetime)) {+ const owner = [...content].reverse().find(c => c.event.id <= d.event.id) ?? null;+ const next: Draft | undefined = l.known[l.known.findIndex(k => k.event.id === d.event.id) + 1];+ const base: PageInterval = { lifetime, slug: d.slug, revision: d.revision, deleted: d.deleted, event: d.event, until: next ? next.event.recorded_at : null, body: 'unavailable' };+ if (d.gone) { out.push({ ...base, body_reason: d.gone }); continue; }+ if (owner && owner === liveHead) {+ if (!bodies) { out.push({ ...base, body: 'live' }); continue; }+ const page = await livePage(engine, pageId!);+ out.push({ ...base, body: page.segmented ? 'segmented' : 'live', page: page.view });+ continue;+ }+ const version = owner ? pairing.get(owner.event.id) : undefined;+ if (!bodies) { out.push({ ...base, ...(owner && revisions.length && pageId != null ? {} : { body_reason: gone ?? 'version_missing' }) }); continue; }+ if (!version) { out.push({ ...base, body_reason: gone ?? (large ? 'pruned' : 'version_missing') }); continue; }+ const segmented = version.body_storage === 'segmented';+ out.push({ ...base, body: segmented ? 'segmented' : 'version', version_id: Number(version.id), page: {+ title: (version.title as string | null) ?? null, type: (version.type as string | null) ?? null, frontmatter: (json(version.frontmatter) as Record<string, unknown>) ?? {},+ tags: (json(version.tags) as string[] | null) ?? [], compiled_truth: segmented ? null : (version.compiled_truth as string | null) ?? null,+ timeline: segmented ? null : (version.timeline as string | null) ?? null, body_bytes: version.body_bytes == null ? null : Number(version.body_bytes) } });+ }+ }+ return out;+}++async function livePage(engine: BrainEngine, pageId: number) {+ const [row] = await engine.executeRaw<Record<string, unknown>>(`SELECT p.title, p.type, p.frontmatter, p.body_storage, p.compiled_truth, p.timeline,+ COALESCE(p.body_bytes, octet_length(COALESCE(p.compiled_truth, '')) + octet_length(COALESCE(p.timeline, ''))) AS body_bytes,+ COALESCE((SELECT json_agg(t.tag ORDER BY t.tag) FROM tags t WHERE t.page_id = p.id), '[]'::json) AS tags+ FROM pages p WHERE p.id = $1`, [pageId]);+ const segmented = row!.body_storage === 'segmented';+ return { segmented, view: { title: (row!.title as string | null) ?? null, type: (row!.type as string | null) ?? null,+ frontmatter: (json(row!.frontmatter) as Record<string, unknown>) ?? {}, tags: (json(row!.tags) as string[]) ?? [],+ compiled_truth: segmented ? null : (row!.compiled_truth as string | null) ?? null, timeline: segmented ? null : (row!.timeline as string | null) ?? null,+ body_bytes: row!.body_bytes == null ? null : Number(row!.body_bytes) } };+}++/** The page's best-effort history summary (the backfill's `backfill` event), named in a `coverage_from` refusal. */+async function backfillSummary(engine: BrainEngine, sourceId: string, slug: string): Promise<{ complete: boolean; versions: number; reasons: string[] } | null> {+ const [row] = await engine.executeRaw<{ value: unknown }>(`SELECT e.value 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.slug = $2 AND e.event_type = 'backfill' ORDER BY e.id DESC LIMIT 1`, [sourceId, slug]);+ const v = row ? json(row.value) as Record<string, unknown> : null;+ return v ? { complete: v.backfill_complete === true, versions: Number(v.versions ?? 0), reasons: (v.reasons as string[] | undefined) ?? [] } : null;+}++function coverageRefusal(c: { code: 'coverage_from' | 'coverage_gap'; from: string | null; message: string; until?: string | null; reason?: string },+ q: { sourceId: string; slug: string; at: Date }, backfill?: { complete: boolean; versions: number; reasons: string[] } | null) {+ const fix = readFix('Lists the coverage intervals, watermark and restore gaps the read is checked against.', { argv: ['gbrain', 'beliefs', 'status', '--source', q.sourceId, '--json'] });+ if (c.code === 'coverage_gap') {+ return opError('coverage_gap', c.message, `Ask about an instant before ${c.from ?? 'the gap'} or after ${c.until ?? 'it'}.`, { reason: c.reason, fix });+ }+ const hint = backfill+ ? `Recorded history of ${q.slug} starts ${c.from ?? 'later'}. A best-effort history from retained versions exists (${backfill.complete ? 'complete' : `incomplete: ${backfill.reasons.join(', ') || 'unknown'}`}); it holds source times only, never recorded times, so it cannot answer known_as_of.`+ : `Recorded history starts ${c.from ?? 'once the ledger is enabled on this source'}; ask about an instant at or after it.`;+ return opError('coverage_from', c.message, hint, { reason: backfill ? (backfill.complete ? 'backfill_only' : 'backfill_incomplete') : 'not_recorded', fix });+}++/** A remote caller reads an interval only when its event was world-visible when recorded and its page is visible now; it fails closed when the page row is gone. */+export async function remoteMayRead(engine: BrainEngine, pageId: number | null, interval: PageInterval): Promise<boolean> {+ if (pageId == null || interval.event.visibility !== 'world') return false;+ const [row] = await engine.executeRaw<{ visible: boolean }>(`SELECT ${privatePagesFilterFragment('p')} AS visible FROM pages p WHERE p.id = $1 AND p.deleted_at IS NULL`, [pageId]);+ return row?.visible === true;+}diff --git a/src/core/engine-sql/pages.ts b/src/core/engine-sql/pages.tsindex 1af641ad08..b4087129a6 100644--- a/src/core/engine-sql/pages.ts+++ b/src/core/engine-sql/pages.ts@@ -31,6 +31,7 @@ import { jsonbParam, type SqlExecutor } from './executor.ts';import type { LegacyUnscopedRead, ScopedRead } from './brands.ts';import type { ScopedReadRunner } from './cjk-search.ts';import { compileRowNormalizer } from './normalize.ts';+import { createPageVersion } from '../page-state/versions.ts';import { renderFragment, sqlFragment, trustedSql } from './fragment.ts';import { quoteIdentifier, resolveWriteColumnFromConfigRows } from '../search/embedding-column.ts';@@ -987,9 +988,13 @@ export async function revertToVersion(* The rename statement plus its slug alias and bindings, run on the* transaction the engine opened (`exec` is that transaction's executor,* `tx` its engine clone). Source-qualified so a rename in source A doesn't- * sweep up same-slug rows in sources B/C/D.+ * sweep up same-slug rows in sources B/C/D. The move advances the page's+ * knowledge revision, so it first versions the page as it stood: page-at-time+ * (belief ledger W2) reads the body before the rename from that preimage.*/export async function updateSlug(exec: SqlExecutor, tx: BrainEngine, oldSlug: string, newSlug: string, sourceId: string): Promise<number> {+ const preimage = await tx.readPageSnapshot(oldSlug, { sourceId, includeDeleted: true });+ if (preimage) await createPageVersion(tx, oldSlug, sourceId, preimage);const moved = await exec.executeRaw(`UPDATE pages SET slug = $1, updated_at = now() WHERE slug = $2 AND source_id = $3 RETURNING id`,[newSlug, oldSlug, sourceId],diff --git a/src/core/error-catalogue.ts b/src/core/error-catalogue.tsindex 5dbd3a243f..0d8166cdd3 100644--- a/src/core/error-catalogue.ts+++ b/src/core/error-catalogue.ts@@ -32,6 +32,11 @@ export interface CatalogueEntry {}export const ERROR_CATALOGUE = {+ // W2 page-at-time: recorded-time reads (`known_as_of`).+ coverage_from: { code: 'coverage_from', docs: 'docs/guides/repair.md#coverage-from' },+ coverage_gap: { code: 'coverage_gap', docs: 'docs/guides/repair.md#coverage-gap' },+ clock_mismatch: { code: 'clock_mismatch', docs: 'docs/guides/repair.md#clock-mismatch' },+ known_as_of_unproven: { code: 'known_as_of_unproven', docs: 'docs/guides/repair.md#known-as-of-unproven' },legacy_jobs_active: { code: 'legacy_jobs_active', docs: 'docs/guides/repair.md#legacy-jobs-active' },// D4 / D2 notice codes (agent-output Notice through the notice ledger).grant_blocked_operations: { code: 'grant_blocked_operations', docs: 'docs/guides/repair.md#grant-blocked-operations' },diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 73358df7e9..7e9a1495b1 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -93,8 +93,10 @@ export const CODES = {bridge_ownership_conflict: { class: 'caller', summary: "The private local CLI registration is invalid." },bucket_not_found: { class: 'unavailable', summary: "The configured storage bucket does not exist." },budget_unsatisfiable: { class: 'unavailable', summary: "Reserved by MEMORY_VERBS v1; never returned." },- coverage_from: { class: 'caller', summary: "The belief ledger does not cover that time for this page or source: it starts at the page's baseline cut or the source's watermark.", why: "Recorded history exists only from a page's baseline (or creation) after the ledger was enabled; earlier times are unknown, not empty.", docs: 'docs/designs/BELIEF_LEDGER.md#71-activation-baseline-and-the-watermark', suggestion: 'Ask about a time at or after the `from` time, or run `gbrain beliefs backfill --source <id>` for best-effort history before it.' },- coverage_gap: { class: 'caller', summary: "The belief ledger was not recording at that time: coverage was stopped, or a backup restore left a gap between the archive's time and the restore.", docs: 'docs/designs/BELIEF_LEDGER.md#71-activation-baseline-and-the-watermark', suggestion: 'Ask about a time outside the gap; `gbrain beliefs status --source <id>` lists the intervals and gaps.' },+ coverage_from: { class: 'caller', summary: "The belief ledger does not cover that time for this page or source: it starts at the page's baseline cut or the source's watermark.", why: "Recorded history exists only from a page's baseline (or creation) after the ledger was enabled; earlier times are unknown, not empty. A best-effort backfill from retained versions carries source times only, so it never answers a recorded-time read.", reasons: ['not_recorded', 'backfill_only', 'backfill_incomplete'], docs: 'docs/guides/repair.md#coverage-from', suggestion: 'Ask about a time at or after the time the message names; `gbrain beliefs status --source <id>` lists the coverage intervals.' },+ coverage_gap: { class: 'caller', summary: "The belief ledger was not recording at that time: coverage was stopped, or a backup restore left a gap between the archive's time and the restore.", why: 'Nothing proves what happened to the page inside the gap, so the read refuses instead of answering from either side.', reasons: ['not_covered', 'restore'], docs: 'docs/guides/repair.md#coverage-gap', suggestion: 'Ask about a time outside the gap; `gbrain beliefs status --source <id>` lists the intervals and gaps.' },+ clock_mismatch: { class: 'caller', summary: 'A time parameter got a value on the wrong clock: `known_as_of` (recorded time) needs an instant with a zone, not a calendar date.', why: 'Recorded time (`known_as_of`) is when the brain had recorded something; valid time (`as_of`) is when a fact held in the world, as a date. A bare date is ambiguous as a recorded-time instant, so it is refused instead of guessed.', reasons: ['date_for_instant'], docs: 'docs/guides/repair.md#clock-mismatch', suggestion: 'Pass a full instant such as 2026-10-01T12:00:00Z to known_as_of, or use as_of where the tool takes a valid-time date.' },+ known_as_of_unproven: { class: 'caller', summary: 'A change to the page was recorded before the requested instant but was not yet proven committed at it, so the page at that instant cannot be stated.', why: "A write's recorded time is a lower bound on when it became visible; until its commit mark (or a later write to the same page) proves it committed by the instant, the page then may or may not have included it.", docs: 'docs/guides/repair.md#known-as-of-unproven', suggestion: 'Ask about an instant before the write was recorded, or after it was observed committed (the message names both).' },cache_quota_exceeded: { class: 'caller', summary: "Retained shared-skill revisions reached this installation's local cache quota.", docs: 'docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover' },calendar_unreadable: { class: 'caller', summary: "A Google source's configured calendar returned HTTP 403 or 404 to its account, so its sync imports no events.", why: "Without the typed result an unreadable calendar looks exactly like an empty one. The calendar sweep records it in the source's connector state (the run is not failed); `gbrain doctor` (google_calendar_readable) reads it with no network call and `gbrain google status` probes it live.", docs: 'docs/guides/google-connect.md#unreadable-calendar', suggestion: 'List the calendars the account can read with `gbrain google calendars --account <email>`, then point the source at one with `gbrain sources set-calendar <source> <calendar-id>` and run `gbrain sync --source <source>`.', fix: { argv: ['gbrain', 'google', 'calendars', '--json'], consent: [], actor: 'agent', why: 'Read-only: lists the calendar ids the connected account can read.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'google_calendar_readable', '--json'] } } },cancelled: { class: 'caller', summary: "The write was cancelled before it committed." },diff --git a/src/core/ops/admin.ts b/src/core/ops/admin.tsindex 12d14357a3..7a880c6b4f 100644--- a/src/core/ops/admin.ts+++ b/src/core/ops/admin.ts@@ -14,12 +14,14 @@ import { sanitizeRemoteBody } from '../remote-body.ts';*/import type { Operation, OperationContext } from './contract.ts';+import { opError } from './contract.ts';import { enforceClientSlugFence, sourceScopeOpts } from './context.ts';import { VERSION } from '../../version.ts';import { resolveActiveEmbeddingColumnFromEngine } from '../search/embedding-column.ts';import { memoizedHealth } from '../health-memo.ts';import { LARGE_PAGES_CAPABILITY } from './get-page-body.ts';import { isSegmentedPage, pageBodyBytes } from '../page-body/page-shape.ts';+import { getVersionsKnownAsOf, KNOWN_AS_OF_PARAM, VERSIONS_DIFF_PARAM } from './known-as-of.ts';// --- Admin ---@@ -203,6 +205,9 @@ const get_versions: Operation = {slug: { type: 'string', required: true, description: 'Slug of the page whose version history to list.' },limit: { type: 'number', description: `Return only the newest N versions (a positive integer). Default ${GET_VERSIONS_DEFAULT_LIMIT}; MCP callers are capped at ${GET_VERSIONS_REMOTE_MAX_LIMIT}.` },include_body: { type: 'boolean', description: 'true adds compiled_truth and timeline to every version. Default false (metadata only).' },+ known_as_of: { ...KNOWN_AS_OF_PARAM, description: 'Recorded time: the validity intervals this brain had recorded by this ISO 8601 instant, from the belief ledger. Not as_of, which is valid time (a date).' },+ diff: VERSIONS_DIFF_PARAM,+ source_id: { type: 'string', description: 'With known_as_of: the source.', fullSurfaceOnly: true },},handler: async (ctx, p) => {// #5234: the bound and the body projection run in SQL, after the scope and@@ -211,6 +216,8 @@ const get_versions: Operation = {// Large pages: metadata only and the newest 20 by default (100 per MCP// call); one probe row past the limit says whether older versions exist.const { limit, clampedFrom } = pagingLimit(ctx, 'get_versions', p.limit, GET_VERSIONS_DEFAULT_LIMIT, GET_VERSIONS_REMOTE_MAX_LIMIT);+ if (p.known_as_of !== undefined) return getVersionsKnownAsOf(ctx, p, limit);+ if (p.diff !== undefined || p.source_id !== undefined) throw opError('invalid_params', 'get_versions: diff and source_id need known_as_of.', 'Pass known_as_of (an ISO 8601 instant) with them, or drop them for the snapshot list.');const opts = { ...(await readPolicyOpts(ctx)), limit: limit + 1 };const page = <T>(rows: T[]): T[] => {reportVersionPage(ctx, p, { limit, clampedFrom, truncated: rows.length > limit });diff --git a/src/core/ops/known-as-of.ts b/src/core/ops/known-as-of.tsnew file mode 100644index 0000000000..bde12005f4--- /dev/null+++ b/src/core/ops/known-as-of.ts@@ -0,0 +1,105 @@+/**+ * W2 page-at-time on the op surface: `get_page {known_as_of}` and+ * `get_versions {known_as_of, diff}` (docs/designs/BELIEF_LEDGER.md section+ * 10). Recorded time, read from the belief ledger's publication events+ * (`belief/page-at-time.ts`); `as_of` elsewhere is valid time.+ */+import type { OperationContext, ParamDef } from './contract.ts';+import { opError } from './contract.ts';+import { assertExplicitSourceLive, federatedSearchScope, pageNotFoundError, parseSourceIdParam } from './context.ts';+import { inlineBodyBytes } from './get-page-body.ts';+import { pageTrustForRead } from './get-page-projection.ts';+import { parseKnownAsOf, readPageAtTime, remoteMayRead, type PageAtTime, type PageInterval } from '../belief/page-at-time.ts';+import { sanitizeRemoteBody } from '../remote-body.ts';+import { unifiedDiff } from '../skillpack/diff-text.ts';++export const KNOWN_AS_OF_PARAM: ParamDef = { type: 'string', fullSurfaceOnly: true,+ description: 'Recorded time: the page as this brain had recorded it at this ISO 8601 instant (2026-10-01T12:00:00Z), from the belief ledger. Not as_of, which is valid time (a date).' };+export const VERSIONS_DIFF_PARAM: ParamDef = { type: 'boolean', fullSurfaceOnly: true, description: 'With known_as_of: each version also carries a unified diff from the version before it.' };++/** get_page parameters that select a body window, a fuzzy match or an edit view, none of which a historical read serves. */+const GET_PAGE_UNSUPPORTED = ['fuzzy', 'include_content', 'content_only', 'include_timeline_entries', 'grammar_diagnostics', 'include_quarantined',+ 'lines', 'bytes', 'around_chunk_id', 'context_lines', 'cursor', 'max_bytes', 'view', 'outline_from'] as const;++/** The one source a recorded-time read targets: the explicit or ambient source, else the only granted source whose ledger names the slug. */+async function targetSource(ctx: OperationContext, p: Record<string, unknown>, op: string): Promise<string> {+ const sourceIdParam = parseSourceIdParam(p.source_id, op, { allowAll: true });+ const scope = federatedSearchScope(ctx, sourceIdParam);+ await assertExplicitSourceLive(ctx, sourceIdParam);+ if (scope.sourceId) return scope.sourceId;+ const rows = await ctx.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.slug = $1 AND e.subject_kind = 'page' AND ($2::text[] IS NULL OR e.source_id = ANY($2::text[])) ORDER BY e.source_id`, [p.slug, scope.sourceIds ?? null]);+ if (rows.length === 1) return rows[0]!.source_id;+ if (rows.length > 1) {+ throw opError('invalid_params', `${op}: ${String(p.slug)} has recorded history in several sources (${rows.map(r => r.source_id).join(', ')}).`, 'Pass source_id to name one.');+ }+ return scope.sourceIds?.length === 1 ? scope.sourceIds[0]! : 'default';+}++/** Readable intervals: a remote caller sees an interval only under the ledger's visibility rule and the page's current trust floor. */+async function readable(ctx: OperationContext, read: PageAtTime, intervals: PageInterval[], minTrust: unknown): Promise<PageInterval[]> {+ if (ctx.remote === false) return intervals;+ if (read.page_id == null || !(await pageTrustForRead(ctx, { id: read.page_id }, minTrust))) return [];+ const out: PageInterval[] = [];+ for (const i of intervals) if (await remoteMayRead(ctx.engine, read.page_id, i)) out.push(i);+ return out;+}++function intervalView(ctx: OperationContext, i: PageInterval, opts: { body: boolean; inlineMax: number }) {+ const meta = { slug: i.slug, revision: i.revision, deleted: i.deleted, recorded_at: i.event.recorded_at, visible_at: i.event.visible_at, until: i.until,+ source_time: i.event.source_time, event: i.event.type, event_id: i.event.id, origin: i.event.origin, body: i.body,+ ...(i.body_reason ? { body_reason: i.body_reason } : {}), ...(i.version_id != null ? { version_id: i.version_id } : {}),+ ...(i.page ? { title: i.page.title, type: i.page.type, tags: i.page.tags, frontmatter: i.page.frontmatter } : {}) };+ if (!opts.body || !i.page) return meta;+ const bytes = i.page.body_bytes ?? 0;+ if (i.body === 'segmented' || bytes > opts.inlineMax) {+ return { ...meta, body_ref: { total_bytes: bytes, ...(i.version_id != null ? { read: { tool: 'get_page', arguments: { slug: i.slug, version_id: i.version_id, body: 'window' } } } : {}) } };+ }+ const clean = (s: string | null) => s == null ? null : ctx.remote === false ? s : sanitizeRemoteBody(s, { includeWithdrawn: true, keepMaterializedMarkers: true });+ return { ...meta, compiled_truth: clean(i.page.compiled_truth), timeline: clean(i.page.timeline) };+}++function ledgerView(read: PageAtTime) {+ return { known_as_of: read.known_as_of, source_id: read.source_id, certified: read.certified, uncertified_reason: read.uncertified_reason, coverage_from: read.coverage_cut };+}++/** `get_page {known_as_of}`: the page at the slug as recorded at the instant, with the interval it was in and whether the ledger certifies it. */+export async function getPageKnownAsOf(ctx: OperationContext, p: Record<string, unknown>): Promise<Record<string, unknown>> {+ const at = parseKnownAsOf(p.known_as_of);+ const extra = GET_PAGE_UNSUPPORTED.filter(k => p[k] !== undefined && p[k] !== false);+ if (extra.length || (p.body !== undefined && p.body !== 'auto' && p.body !== 'full' && p.body !== 'none')) {+ throw opError('invalid_params', `get_page: known_as_of does not combine with ${extra.length ? extra.join(', ') : `body: ${String(p.body)}`}.`,+ 'Read the page as recorded with known_as_of alone (plus source_id, include_deleted or body: "none"), or drop known_as_of for the current page.');+ }+ const slug = String(p.slug);+ const sourceId = await targetSource(ctx, p, 'get_page');+ const read = await readPageAtTime(ctx.engine, { sourceId, slug, at });+ const current = read.current && (await readable(ctx, read, [read.current], p.min_trust))[0];+ if (!current || (current.deleted && p.include_deleted !== true)) throw pageNotFoundError(ctx, slug, { includeDeleted: p.include_deleted === true, sourceIdParam: sourceId });+ return { ...intervalView(ctx, current, { body: p.body !== 'none', inlineMax: await inlineBodyBytes(ctx) }), ...ledgerView(read) };+}++/** `get_versions {known_as_of}`: the page's validity intervals known at the instant, newest first; `diff` adds each one's change from the one before it. */+export async function getVersionsKnownAsOf(ctx: OperationContext, p: Record<string, unknown>, limit: number): Promise<Record<string, unknown>> {+ const at = parseKnownAsOf(p.known_as_of);+ const slug = String(p.slug);+ const sourceId = await targetSource(ctx, p, 'get_versions');+ const wantBody = p.include_body === true;+ const read = await readPageAtTime(ctx.engine, { sourceId, slug, at, history: true, withBodies: wantBody || p.diff === true });+ const intervals = await readable(ctx, read, read.intervals, p.min_trust);+ if (!intervals.length) throw pageNotFoundError(ctx, slug, { includeDeleted: true, sourceIdParam: sourceId });+ const inlineMax = await inlineBodyBytes(ctx);+ const views = intervals.map((i, n) => {+ const view: Record<string, unknown> = intervalView(ctx, i, { body: wantBody, inlineMax });+ if (p.diff !== true) return view;+ const prev = intervals.slice(0, n).reverse().find(x => x.lifetime === i.lifetime);+ const text = (x: PageInterval | undefined) => x?.page && x.body !== 'segmented' ? `${x.page.compiled_truth ?? ''}${x.page.timeline ? `\n${x.page.timeline}` : ''}` : null;+ const [a, b] = [prev ? text(prev) : '', text(i)];+ view.diff = a == null || b == null ? null : unifiedDiff(ctx.remote === false ? a : sanitizeRemoteBody(a), ctx.remote === false ? b : sanitizeRemoteBody(b),+ { oldPath: prev ? `${slug}@${prev.event.recorded_at}` : '/dev/null', newPath: `${slug}@${i.event.recorded_at}` });+ return view;+ });+ const newest = views.reverse();+ return { slug, ...ledgerView(read), truncated: newest.length > limit, versions: newest.slice(0, limit) };+}diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.tsindex 7e62d90c8c..3ac860fb83 100644--- a/src/core/ops/pages.ts+++ b/src/core/ops/pages.ts@@ -21,6 +21,7 @@ import { pageTrustForRead, projectFetchText, projectGetPage, readQuarantined } fimport { assertLargePageAdmission } from '../persistence/large-page-guard.ts';import { assertFullReadFits, bodyBytes, fetchWindowResult, GET_PAGE_BODY_PARAMS, inlineBodyBytes, parseBodyRequest, readPartialBody } from './get-page-body.ts';import { MIN_TRUST_PARAM } from '../eligibility/policy.ts';+import { getPageKnownAsOf, KNOWN_AS_OF_PARAM } from './known-as-of.ts';import { stampRowTrust } from '../eligibility/stamp.ts';import { isAutoLinkEnabled } from '../link-extraction.ts';import { sanitizeRemoteBody } from '../remote-body.ts';@@ -100,8 +101,10 @@ const get_page: Operation = {source_id: { type: 'string', description: "One source, or '__all__'." },include_quarantined: { type: 'boolean', description: 'Admin: quarantined body.' },min_trust: MIN_TRUST_PARAM,+ known_as_of: KNOWN_AS_OF_PARAM,},handler: async (ctx, p) => {+ if (p.known_as_of !== undefined) return getPageKnownAsOf(ctx, p);const slug = p.slug as string;const fuzzy = (p.fuzzy as boolean) || false;const includeDeleted = (p.include_deleted as boolean) === true;diff --git a/test/belief-ledger-page-at-time.test.ts b/test/belief-ledger-page-at-time.test.tsnew file mode 100644index 0000000000..69d6029386--- /dev/null+++ b/test/belief-ledger-page-at-time.test.ts@@ -0,0 +1,226 @@+/**+ * W2 page-at-time probes (docs/designs/BELIEF_LEDGER.md section 10):+ * `get_page {known_as_of}` and `get_versions {known_as_of}` read the page as+ * this brain had recorded it at an instant, from validity intervals over the+ * ledger's publication events. Each cell of section 10's table, plus the+ * coverage, clock and purge refusals, runs on PGLite and on Postgres when+ * DATABASE_URL is set, and each has a forced probe that must make it fail.+ */+import { afterEach, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { operationsByName } from '../src/core/operations.ts';+import { withBeliefBatch } from '../src/core/belief/ledger.ts';+import { fillCommitMarks } from '../src/core/belief/coverage-report.ts';+import { backfillBeliefHistory } from '../src/core/belief/backfill.ts';+import { replayPurgesInRestore } from '../src/core/belief/purge-mirror.ts';+import { renamePageOntoSlug } from '../src/commands/sync/rename-collision.ts';+import { __setBeliefEmitterFaultForTests } from '../src/core/belief/append.ts';+import { testBackends } from './helpers/test-backends.ts';+import { waitForValue } from './helpers/wait-for.ts';+import { beliefBrain, beliefEngineCase, beliefPage, type BeliefBrain } from './helpers/belief-ledger.ts';++afterEach(() => __setBeliefEmitterFaultForTests(null));++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));+const at = async (b: BeliefBrain) => { await pause(); const t = await dbNow(b); await pause(); return t; };+const iso = (v: string) => new Date(v).toISOString();+const plus = (v: string, ms: number) => new Date(Date.parse(v) + ms).toISOString();+const read = (b: BeliefBrain, params: Record<string, unknown>) => operationsByName.get_page!.handler(b.ctx, params) as Promise<Record<string, any>>;+const versions = (b: BeliefBrain, params: Record<string, unknown>) => operationsByName.get_versions!.handler(b.ctx, params) as Promise<Record<string, any>>;+const refusal = (p: Promise<unknown>) => p.then(() => null, (e: { code?: string; reason?: string; retryable?: boolean; message: string }) => e);+const draft = (prose: string) => beliefPage({ prose, facts: ['Acme sells widgets'] });+const pageEvents = async (b: BeliefBrain, slug: string) => (await b.events()).filter(e => e.subject_kind === 'page' && e.slug === slug && e.origin !== 'backfill');++for (const engineCase of testBackends().map(beliefEngineCase)) {+ describe(`belief ledger page-at-time (${engineCase.name})`, () => {+ const brain = (run: (b: BeliefBrain) => Promise<void>, opts: { managed?: boolean; enable?: boolean } = {}) =>+ beliefBrain(run, { managed: opts.managed ?? true, enable: opts.enable, databaseUrl: engineCase.databaseUrl });+ const slug = 'companies/acme-example';++ test('before, at and after creation and each of two edits: each instant reads the body of its interval, never the preimage newest at T', () => brain(async b => {+ const before = await at(b);+ await b.put(slug, draft('First draft.'));+ const t1 = await at(b);+ await b.put(slug, draft('Second draft.'));+ const t2 = await at(b);+ await b.put(slug, draft('Third draft.'));+ const t3 = await at(b);+ const [create, edit1, edit2] = await pageEvents(b, slug);+ expect([create, edit1, edit2].map(e => e!.event_type)).toEqual(['page.published', 'page.published', 'page.published']);+ expect((await refusal(read(b, { slug, known_as_of: before })))?.code).toBe('page_not_found');+ const body = async (t: string) => { const r = await read(b, { slug, known_as_of: t }); return [r.compiled_truth.trim().split('\n')[0], r.body, r.event_id]; };+ expect(await body(t1)).toEqual(['First draft.', 'version', create!.id]);+ expect(await body(t2)).toEqual(['Second draft.', 'version', edit1!.id]);+ expect(await body(t3)).toEqual(['Third draft.', 'live', edit2!.id]);+ // At the instant an edit was recorded, before its commit was observed and with no later event of the page by then, the read is unproven, not answered.+ const atEdit = await refusal(read(b, { slug, known_as_of: iso(edit1!.recorded_at) }));+ expect(atEdit).toMatchObject({ code: 'known_as_of_unproven', retryable: true });+ const t1Read = await read(b, { slug, known_as_of: t1 });+ expect(t1Read).toMatchObject({ slug, deleted: false, until: null, certified: true, uncertified_reason: null, source_id: b.sourceId, known_as_of: t1 });+ const history = await versions(b, { slug, known_as_of: t3, include_body: true, diff: true });+ expect(history.versions.map((v: any) => [v.event_id, v.body, v.until])).toEqual([[edit2!.id, 'live', null], [edit1!.id, 'version', iso(edit2!.recorded_at)], [create!.id, 'version', iso(edit1!.recorded_at)]]);+ expect(history.versions[0].diff).toContain('-Second draft.');+ expect(history.versions[0].diff).toContain('+Third draft.');+ expect(history.versions[2].diff).toContain('+First draft.');+ expect((await versions(b, { slug, known_as_of: t1 })).versions.map((v: any) => [v.event_id, v.until])).toEqual([[create!.id, null]]);+ // The design's premise: the newest preimage at or before T is the wrong side of an edit.+ const [naive] = await b.engine.executeRaw<{ compiled_truth: string }>(`SELECT v.compiled_truth FROM page_versions v JOIN pages p ON p.id = v.page_id+ WHERE p.source_id = $1 AND p.slug = $2 AND v.snapshot_at <= $3::timestamptz ORDER BY v.id DESC LIMIT 1`, [b.sourceId, slug, t2]);+ expect(naive!.compiled_truth).toContain('First draft.');+ // Forced probe: with the preimages gone, the closed intervals disclose the missing body instead of borrowing the live one.+ await b.engine.executeRaw('DELETE FROM page_versions WHERE page_id = (SELECT id FROM pages WHERE source_id = $1 AND slug = $2)', [b.sourceId, slug]);+ expect(await read(b, { slug, known_as_of: t2 })).toMatchObject({ body: 'unavailable', body_reason: 'version_missing' });+ expect((await read(b, { slug, known_as_of: t2 })).compiled_truth).toBeUndefined();+ }), 120_000);++ test('a write straddling T is unproven until its commit mark; a later event of the page proves it; a mark stamped at recorded time would answer it', () => brain(async b => {+ await b.put(slug, draft('First draft.'));+ await pause();+ await b.put(slug, draft('Second draft.'));+ const edit = (await pageEvents(b, slug)).at(-1)!;+ await b.engine.executeRaw('DELETE FROM belief_commit_marks WHERE publication_id = $1::uuid', [edit.publication_id]);+ const stalled = plus(iso(edit.recorded_at), 1);+ await pause();+ const unproven = await refusal(read(b, { slug, known_as_of: stalled }));+ expect(unproven).toMatchObject({ code: 'known_as_of_unproven', retryable: true });+ expect((await read(b, { slug, known_as_of: plus(iso(edit.recorded_at), -1) })).compiled_truth).toContain('First draft.');+ expect(await fillCommitMarks(b.engine, b.sourceId)).toBe(1);+ const marked = await at(b);+ expect((await read(b, { slug, known_as_of: marked })).compiled_truth).toContain('Second draft.');+ expect((await refusal(read(b, { slug, known_as_of: stalled })))?.code).toBe('known_as_of_unproven');+ await b.put(slug, draft('Third draft.'));+ const later = await at(b);+ await b.engine.executeRaw('DELETE FROM belief_commit_marks WHERE publication_id = $1::uuid', [edit.publication_id]);+ expect((await versions(b, { slug, known_as_of: later })).versions.map((v: any) => v.event_id)).toContain(edit.id);+ // Forced probe: a mark stamped at the event's own recorded time (an observer's early transaction start) answers the straddling instant.+ 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`, [edit.publication_id]);+ expect((await read(b, { slug, known_as_of: stalled })).compiled_truth).toContain('Second draft.');+ }), 120_000);++ test('a rolled-back write leaves no event and no interval', () => brain(async b => {+ await b.put(slug, draft('First draft.'));+ 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_rollback', origin: 'unmanaged' }, () =>+ tx.executeRaw(`UPDATE pages SET compiled_truth = 'Rolled back.', knowledge_revision = gen_random_uuid() WHERE source_id = $1 AND slug = $2`, [b.sourceId, slug]));+ throw new Error('rollback');+ }).catch(() => undefined);+ expect(await b.events(mark)).toEqual([]);+ const t = await at(b);+ expect((await read(b, { slug, known_as_of: t })).compiled_truth).toContain('First draft.');+ expect((await versions(b, { slug, known_as_of: t })).versions).toHaveLength(1);+ }), 120_000);++ test('delete then recreate: a soft delete and put restore the same lifetime; a purge and put mint a new one, and the purged lifetime keeps no body', () => brain(async b => {+ const revision = async () => (await b.engine.executeRaw<{ r: string }>('SELECT knowledge_revision::text AS r FROM pages WHERE source_id=$1 AND slug=$2', [b.sourceId, slug]))[0]!.r;+ await b.put(slug, draft('First draft.'));+ const t1 = await at(b);+ await b.op('delete_page', { slug, expected_revision: await revision() });+ const deleted = await at(b);+ await b.put(slug, draft('Back again.'));+ const t2 = await at(b);+ expect((await refusal(read(b, { slug, known_as_of: deleted })))?.code).toBe('page_not_found');+ expect(await read(b, { slug, known_as_of: deleted, include_deleted: true })).toMatchObject({ deleted: true, event: 'page.deleted', body: 'version' });+ expect((await read(b, { slug, known_as_of: deleted, include_deleted: true })).compiled_truth).toContain('First draft.');+ expect((await read(b, { slug, known_as_of: t1 })).compiled_truth).toContain('First draft.');+ expect((await read(b, { slug, known_as_of: t2 })).compiled_truth).toContain('Back again.');+ expect((await versions(b, { slug, known_as_of: t2 })).versions.map((v: any) => [v.event, v.deleted])).toEqual([['page.restored', false], ['page.deleted', true], ['page.published', false]]);+ expect(new Set((await pageEvents(b, slug)).map(e => e.page_lifetime)).size).toBe(1);+ await b.op('delete_page', { slug, purge: true, expected_revision: await revision() });+ const purged = await at(b);+ await b.put(slug, draft('Recreated.'));+ const t3 = await at(b);+ expect(new Set((await pageEvents(b, slug)).map(e => e.page_lifetime)).size).toBe(2);+ expect((await refusal(read(b, { slug, known_as_of: purged, include_deleted: true })))?.code).toBe('page_not_found');+ expect((await read(b, { slug, known_as_of: t3 })).compiled_truth).toContain('Recreated.');+ const history = await versions(b, { slug, known_as_of: t3, include_body: true });+ expect(history.versions.map((v: any) => [v.event, v.body, v.body_reason ?? null])).toEqual([['page.published', 'live', null], ['page.purged', 'unavailable', 'purged'],+ ['page.restored', 'unavailable', 'purged'], ['page.deleted', 'unavailable', 'purged'], ['page.published', 'unavailable', 'purged']]);+ expect(JSON.stringify(history)).not.toContain('First draft.');+ expect(JSON.stringify(history)).not.toContain('Back again.');+ }), 120_000);++ test('create, forget, materialize, edit: the pre-forget body, the withdrawn view and the materialized body each answer their own instant', () => brain(async b => {+ await b.put(slug, beliefPage({ prose: 'Profile.', facts: ['Acme raised a seed round', 'Acme has ten staff'] }));+ const created = await at(b);+ const [fact] = await b.engine.executeRaw<{ id: number }>(`SELECT id FROM facts WHERE source_id = $1 AND fact = 'Acme has ten staff' AND expired_at IS NULL`, [b.sourceId]);+ const mark = await b.lastId();+ await operationsByName.forget!.handler(b.ctx, { id: String(fact!.id), request_id: randomUUID() });+ const materialized = await waitForValue(async () => (await b.events(mark)).find(e => e.cause.op === 'withdrawal_materialize'), { timeoutMs: 30_000, label: 'withdrawal materialization' });+ const afterMaterialize = await at(b);+ await b.put(slug, beliefPage({ prose: 'Profile, edited.', facts: ['Acme raised a seed round'] }));+ const edited = await at(b);+ const forget = (await b.events(mark)).find(e => e.cause.op === 'forget' && e.subject_kind === 'page')!;+ expect((await read(b, { slug, known_as_of: created })).compiled_truth).toContain('Acme has ten staff');+ const history = await versions(b, { slug, known_as_of: edited, include_body: true });+ expect(history.versions.map((v: any) => [v.event, v.body])).toEqual([['page.published', 'live'], ['page.view_changed', 'version'], ['page.view_changed', 'version'], ['page.published', 'version']]);+ expect(history.versions.map((v: any) => v.event_id).slice(1, 3)).toEqual([materialized!.id, forget.id]);+ expect(history.versions[3].compiled_truth).toContain('Acme has ten staff');+ expect((await read(b, { slug, known_as_of: afterMaterialize })).event_id).toBe(materialized!.id);+ expect((await read(b, { slug, known_as_of: edited })).compiled_truth).toContain('Profile, edited.');+ }), 180_000);++ test('rename: before the rename the old slug answers and the new one does not; after it, the reverse; one lifetime', () => brain(async b => {+ await b.put('notes/old-example', beliefPage({ type: 'note', title: 'Old', prose: 'Before the move.' }));+ const before = await at(b);+ await renamePageOntoSlug(b.engine, { sourceId: b.sourceId, oldSlug: 'notes/old-example', newSlug: 'notes/new-example', to: 'notes/new-example.md' });+ await fillCommitMarks(b.engine, b.sourceId);+ const after = await at(b);+ expect(await read(b, { slug: 'notes/old-example', known_as_of: before })).toMatchObject({ body: 'version', slug: 'notes/old-example' });+ expect((await read(b, { slug: 'notes/old-example', known_as_of: before })).compiled_truth).toContain('Before the move.');+ expect((await refusal(read(b, { slug: 'notes/new-example', known_as_of: before })))?.code).toBe('page_not_found');+ expect((await read(b, { slug: 'notes/new-example', known_as_of: after })).compiled_truth).toContain('Before the move.');+ expect((await refusal(read(b, { slug: 'notes/old-example', known_as_of: after })))?.code).toBe('page_not_found');+ const lifetimes = new Set((await b.events()).filter(e => e.subject_kind === 'page').map(e => e.page_lifetime));+ expect(lifetimes.size).toBe(1);+ // Forced probe: without the rename's preimage (the move advances the revision), the body before the rename is disclosed missing, not borrowed from the live page.+ await b.engine.executeRaw('DELETE FROM page_versions WHERE page_id = (SELECT id FROM pages WHERE source_id = $1 AND slug = $2)', [b.sourceId, 'notes/new-example']);+ expect(await read(b, { slug: 'notes/old-example', known_as_of: before })).toMatchObject({ body: 'unavailable', body_reason: 'version_missing' });+ }, { managed: false }), 120_000);++ test('refusals: coverage_from before enable (with and without a backfill), coverage_gap inside a restore gap, clock_mismatch for a date, a future instant', () => brain(async b => {+ await b.put(slug, draft('First draft.'));+ const unrecorded = await at(b);+ await b.enable();+ await b.put(slug, draft('Second draft.'));+ const covered = await at(b);+ const from = await refusal(read(b, { slug, known_as_of: unrecorded }));+ expect(from).toMatchObject({ code: 'coverage_from', reason: 'not_recorded' });+ await backfillBeliefHistory(b.engine, b.sourceId, { slugs: [slug] });+ expect(await refusal(read(b, { slug, known_as_of: unrecorded }))).toMatchObject({ code: 'coverage_from' });+ expect(['backfill_only', 'backfill_incomplete']).toContain(String((await refusal(read(b, { slug, known_as_of: unrecorded })))!.reason));+ expect((await read(b, { slug, known_as_of: covered })).compiled_truth).toContain('Second draft.');+ expect(await refusal(read(b, { slug, known_as_of: covered.slice(0, 10) }))).toMatchObject({ code: 'clock_mismatch', reason: 'date_for_instant' });+ expect((await refusal(read(b, { slug, known_as_of: 'yesterday' })))?.code).toBe('invalid_params');+ expect((await refusal(read(b, { slug, known_as_of: plus(covered, 86_400_000) })))?.code).toBe('invalid_params');+ const archivedAt = await at(b);+ const inGap = await at(b);+ await b.engine.transaction(tx => replayPurgesInRestore(tx, { lines: [], archivedAt, restoreId: randomUUID() }));+ await fillCommitMarks(b.engine, b.sourceId);+ expect(await refusal(read(b, { slug, known_as_of: inGap }))).toMatchObject({ code: 'coverage_gap', reason: 'restore' });+ expect((await read(b, { slug, known_as_of: await at(b) })).compiled_truth).toContain('Second draft.');+ }, { enable: false }), 120_000);++ test('an unmanaged source answers with a disclosure, never as certified fact', () => brain(async b => {+ await b.put(slug, draft('First draft.'));+ expect(await read(b, { slug, known_as_of: await at(b) })).toMatchObject({ certified: false, uncertified_reason: 'unmanaged' });+ }, { managed: false }), 120_000);++ test('a purged page discloses every body as purged, never a neighbouring version', () => brain(async b => {+ await b.put(slug, draft('First draft.'));+ await pause();+ await b.put(slug, draft('Second draft.'));+ const t = await at(b);+ const revision = (await b.engine.executeRaw<{ r: string }>('SELECT knowledge_revision::text AS r FROM pages WHERE source_id=$1 AND slug=$2', [b.sourceId, slug]))[0]!.r;+ await b.op('delete_page', { slug, purge: true, expected_revision: revision });+ const history = await versions(b, { slug, known_as_of: await at(b), include_body: true });+ expect(history.versions.map((v: any) => [v.event, v.body, v.body_reason, v.compiled_truth])).toEqual([+ ['page.purged', 'unavailable', 'purged', undefined], ['page.published', 'unavailable', 'purged', undefined], ['page.published', 'unavailable', 'purged', undefined]]);+ expect(await read(b, { slug, known_as_of: t })).toMatchObject({ event: 'page.published', deleted: false, body: 'unavailable', body_reason: 'purged' });+ expect((await read(b, { slug, known_as_of: t })).compiled_truth).toBeUndefined();+ }), 120_000);+ });+}