Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
W2: enforce the preimage invariant (test-only batch check, doctor scan); purge_fact versions before its rewrite; remote known_as_of refuses page_not_found for unseen pages (N6 Postgres-HTTP oracle); RLS and gauge goldens
garrytan4978e00c5df2
diff --git a/docs/architecture/key-files/belief-ledger.md b/docs/architecture/key-files/belief-ledger.mdindex 658143099a..8ff570a2c3 100644--- a/docs/architecture/key-files/belief-ledger.md+++ b/docs/architecture/key-files/belief-ledger.md@@ -16,6 +16,7 @@ Design: [BELIEF_LEDGER.md](../../designs/BELIEF_LEDGER.md). Operator surface: `g- `src/core/belief/backfill.ts` — `backfillBeliefHistory`: marked history from `page_versions` only (git is not read), origin `backfill`, historical time in `source_time`, recorded_at the run time; a purge during the run retries (`belief_stale_preparation`), and the summary event says whether pruned versions left it incomplete. A version whose own frontmatter is private (or a pinned question) publishes private events; a carrying field a purge registered from a retained version (`registerVersionCarriers`) is appended as the marker.- `src/core/belief/history.ts` — the one history reader (`readBeliefHistory`); remote callers see only events that were world-visible when recorded on a page visible now, failing closed.- `src/core/belief/page-at-time.ts` — W2 page-at-time (BELIEF_LEDGER.md section 10): `readPageAtTime` replays a slug's page events of every lifetime into validity intervals under the section 5.3 visibility rule (a straddling write refuses `known_as_of_unproven`), refuses `coverage_from` / `coverage_gap` from `coverageAt`, and pairs each closed interval with the preimage version the next transition wrote (by revision, in order); the open head reads the live page. A body no version holds is disclosed (`body_reason`), never borrowed. Purge-redacted events carry no revision, so a purged lifetime splits only on slug and deleted state. `remoteMayRead` applies history.ts's remote rule per interval.+- `src/core/belief/preimages.ts` — the preimage invariant (BELIEF_LEDGER.md section 14 item 8): a revision-moving publication leaves a version of its `revision_before`. `missingPreimages` is the in-batch check `finalizeBeliefEvents` runs under `NODE_ENV=test` (off with `GBRAIN_BELIEF_PREIMAGE_CHECK=0`); `preimageGaps` is doctor's production scan (large and segmented pages exempt).- `src/core/ops/known-as-of.ts` — the op surface: `get_page {known_as_of}` and `get_versions {known_as_of, diff, source_id}` (full surface only). One target source (explicit, ambient, or the only granted source whose ledger names the slug); remote callers get only readable intervals of a page visible now at their trust floor, with sanitized bodies. `parseKnownAsOf` refuses a bare date `clock_mismatch`.- `src/core/engine-sql/pages.ts` `updateSlug` — versions the page before the move (the move advances the revision), so page-at-time has the body from before a rename.- `src/commands/beliefs.ts` — `gbrain beliefs enable|disable|status|reconcile|backfill` (local only; `--json`); an unknown source is `invalid_params`.diff --git a/docs/designs/BELIEF_LEDGER.md b/docs/designs/BELIEF_LEDGER.mdindex 9996f22ac2..8a18b16a83 100644--- a/docs/designs/BELIEF_LEDGER.md+++ b/docs/designs/BELIEF_LEDGER.md@@ -1560,3 +1560,32 @@ Garry accepted those answers. Questions 5, 6, 7 and 8 are decided.only on marks and recorded times, so the cell deletes and re-adds a mark(and stamps one at `recorded_at` as its forced probe) rather than holdinga transaction past ceiling plus grace; W1's probe 13 holds a real one.+8. **The preimage invariant, enforced.** Every publication that moves a+ page's knowledge revision leaves a `page_versions` row of the revision it+ started from (`revision_before`), written in the same transaction before+ the write that advances it. Revisions a transaction only passes through+ (a rename then an edit in one publication) are never a ledger state, since+ events record only the publication's start and end, so they need no+ version. Large and segmented pages are exempt, because their versions are+ pruned on their own policy and page-at-time discloses those bodies as+ `pruned`. Enforcement has two parts:+ - **In tests**, `finalizeBeliefEvents` checks every stream whose+ revision moved and fails the transaction when no version of+ `revision_before` exists (`preimages.ts`, `missingPreimages`), so a+ writer that breaks the rule fails its own tests. It runs only under+ `NODE_ENV=test` (`GBRAIN_BELIEF_PREIMAGE_CHECK=0` turns it off for a+ probe that breaks the rule on purpose): in production it would add one+ indexed lookup per revision-moving publication to the write path the+ W1 overhead work is cutting.+ - **In production**, doctor `belief_ledger_coverage` lists page events+ from `live` or `unmanaged` publications whose `revision_before` no+ version of the live page holds (`preimageGaps`: last 30 days, complete+ under `--tier deep`) and warns, naming the slugs and events. The body+ is not recoverable; the finding names the writer to fix.++ Turning the check on found a second writer that broke the rule:+ `purge_fact` rewrote each affected page body (dropping the purged fence+ row) with no version. It now versions each page before the rewrite, and+ its version redaction pass then redacts that version like every other+ one, so the interval before a purge reads the body as it stood, minus the+ purged claim.diff --git a/src/commands/doctor/checks/belief-ledger.ts b/src/commands/doctor/checks/belief-ledger.tsindex 243addc783..0c8b31af5d 100644--- a/src/commands/doctor/checks/belief-ledger.ts+++ b/src/commands/doctor/checks/belief-ledger.ts@@ -4,8 +4,10 @@* and baseline progress; drift (slugs whose current belief set no longer* hashes to their newest event's state_hash), sampled by default and complete* under `--tier deep`; orphan lifetimes; committed publications with no commit- * mark; and a restore whose purge replay was unavailable, partial or- * unverified.+ * mark; a restore whose purge replay was unavailable, partial or+ * unverified; and page transitions that left no version of the revision they+ * moved off (the preimage invariant, section 14 item 8; last 30 days unless+ * `--tier deep`).** `--fix` appends `reconcile` events for the drifted slugs (a managed source's* slug interval stays uncertified) and fills the missing commit marks, then@@ -19,6 +21,7 @@ import { connectedEngine, doctorSourceIds, type DoctorContext, type DoctorEntryimport {DRIFT_SAMPLE_PAGES, coverageIntervals, coveredSources, fillCommitMarks, orphanLifetimes, reconcileBeliefDrift, scanBeliefDrift, unmarkedPublications,} from '../../../core/belief/coverage-report.ts';+import { preimageGaps } from '../../../core/belief/preimages.ts';const DOCS = 'docs/designs/BELIEF_LEDGER.md#73-the-doctor-coverage-check';const UNSAFE_REPLAY = new Set(['unavailable', 'partial', 'unverified']);@@ -50,7 +53,8 @@ async function runBeliefLedger(ctx: DoctorContext): Promise<Check[]> {perSource.push({ source_id: sourceId, recording: !open.stopped_at, certified: open.certified, watermark: open.watermark, baseline: open.baseline,intervals: intervals.length, drift: { checked: drift.checked, candidates: drift.candidates, exact: drift.exact, slugs: drift.drifted.slice(0, 10).map(d => d.slug), count: drift.drifted.length },drift_marks: open.drift.length, orphans: await orphanLifetimes(engine, sourceId, 5, { deep }), unmarked: (await unmarkedPublications(engine, sourceId, 1000, { deep })).length,- restores: open.restores.filter(r => r.purge_replay && UNSAFE_REPLAY.has(r.purge_replay)) });+ restores: open.restores.filter(r => r.purge_replay && UNSAFE_REPLAY.has(r.purge_replay)),+ preimage_gaps: (await preimageGaps(engine, sourceId, { deep, limit: 10 })).map(g => ({ slug: g.slug, event_id: g.event_id, event_type: g.event_type, revision: g.revision })) });}const details = { sources: perSource, deep, docs: DOCS };const restore = perSource.find(s => s.restores.length);@@ -77,6 +81,16 @@ async function runBeliefLedger(ctx: DoctorContext): Promise<Check[]> {'Appends reconcile events (origin reconcile, honest recorded time) for the drifted slugs and fills missing commit marks; it changes no belief.', 'belief_ledger_coverage', { docs: DOCS }) });return checks;}+ const gapped = perSource.filter(s => s.preimage_gaps.length);+ if (gapped.length) {+ checks.push({ name: 'belief_ledger_coverage', status: 'warn', details,+ message: gapped.map(s => `${s.source_id}: ${s.preimage_gaps.length}${s.preimage_gaps.length === 10 ? '+' : ''} page transition(s) left no version of the revision they moved off`+ + ` (e.g. ${s.preimage_gaps.slice(0, 3).map(g => `${g.slug} at event ${g.event_id}`).join(', ')})`).join('; ')+ + '. A writer advanced a page\'s revision without versioning the page first, so page-at-time (known_as_of) discloses those bodies as version_missing; the body is not recoverable.',+ fix: agentFix(['gbrain', 'doctor', '--only', 'belief_ledger_coverage', '--tier', 'deep', '--json'],+ 'Read-only: lists every such transition (slug, event id, revision) without the recency window, to report the writer.', 'belief_ledger_coverage', { docs: DOCS }) });+ return checks;+ }const pending = perSource.find(s => s.recording && !s.baseline.complete);if (pending) {checks.push({ name: 'belief_ledger_coverage', status: 'warn', details,diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 1c7e85b1aa..b9e416ed3b 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -721,6 +721,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.266.0', text: 'A sync queued behind a recovery that only the user can resolve now stops after one governor tick with `drain_stalled`, `cause: head_blocked`, instead of waiting out the 5-minute no-progress window. Two recoveries count: a fact-withdrawal mirror whose page file was edited while the mirror was publishing (`blocked_by=effect_recovery(unexpected_file_bytes …)`; the fix asks the user to put the file back to a version gbrain recorded, then rerun the sync), and a page write whose file was edited while it was publishing (`blocked_by=request_recovery(unexpected_file_bytes …)`, whether it blocks the queued head or is the head; the fix runs the `gbrain repair stuck-recovery` preview, or the user undoes the edit). Both name the file, and `gbrain sources writer status` shows the same advice. A recovery that can still finish (its file back on a recorded version) keeps the wait. Known gap: a recovery stuck on `unexpected_staging_bytes` still waits out the window.' },// W2 belief ledger page-at-time. `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.{ since: '0.60.266.0', text: 'A page rename (a sync that sees a file move, a frontmatter slug repair, a held-file or import move) now saves the page as it stood before the move as a version, as an edit does, so `get_versions` and `gbrain history` list one more snapshot per rename. The move advances the page\'s revision, and until now no version held the body from before it.' },+ { since: '0.60.266.0', text: '`purge_fact` now saves each page it rewrites as a version before dropping the purged fence row, and its version redaction then removes the claim from that version as from every other, so `get_versions` and `gbrain history` list one more snapshot per page a fact purge rewrites. The snapshot holds the page as it stood before the purge, without the purged claim.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/belief/ledger.ts b/src/core/belief/ledger.tsindex 28585bd0f5..1f7987fb40 100644--- a/src/core/belief/ledger.ts+++ b/src/core/belief/ledger.ts@@ -21,6 +21,7 @@ import { readBeliefState, readFactsById, type RawPage, type RawState } from './simport { keyedSubjects, keyFact, pageNeeds, type KeyContext, type Subject } from './subjects.ts';import { endLifetime, mintLifetime, readOpenLifetimes, renameLifetime, resolveLifetimes } from './lifetimes.ts';import { appendBeliefEvents, redactionReleasedDraft, type BeliefEventDraft, type BeliefOrigin, type RedactionRelease } from './append.ts';+import { missingPreimages, preimageInvariantEnforced } from './preimages.ts';export type BeliefNote =| { kind: 'contested'; table: string; rowId: number; proposalId: number; guard: string }@@ -434,6 +435,14 @@ export async function finalizeBeliefEvents(tx: BrainEngine, batch: Batch): PromisubjectKind: s.kind as BeliefEventDraft['subjectKind'], subjectKey: s.key, trustTier: s.tier, visibility: s.visibility, stateHash: streamHash(s.stream) }, note.releases, batch.publicationId));}}+ if (preimageInvariantEnforced()) {+ const needs = streams.flatMap(s => s.pre && s.post && s.pre.id === s.post.id && s.pre.revision !== s.post.revision && !s.pre.large && !s.post.large+ ? [{ pageId: s.post.id, slug: s.pre.slug, revision: s.pre.revision }] : []);+ const missing = await missingPreimages(tx, needs);+ if (missing.length) {+ throw new Error(`belief preimage invariant: ${missing.map(m => `${m.slug} moved off revision ${m.revision} with no page_versions row for it`).join('; ')} (op ${opts.op}; BELIEF_LEDGER.md section 14 item 8)`);+ }+ }return appendBeliefEvents(tx, drafts, { publicationId: batch.publicationId, origin: opts.origin ?? (batch.managed ? 'live' : 'unmanaged'),writerTier, remote: opts.remote, ownerEdit: opts.ownerEdit, purgesPossible: batch.purgesPossible || batch.notes.some(n => n.kind === 'purged') });}diff --git a/src/core/belief/preimages.ts b/src/core/belief/preimages.tsnew file mode 100644index 0000000000..dc3d18a4c8--- /dev/null+++ b/src/core/belief/preimages.ts@@ -0,0 +1,49 @@+/**+ * The preimage invariant page-at-time rests on (docs/designs/BELIEF_LEDGER.md+ * section 14, item 8): every publication that moves a page's knowledge revision+ * leaves a `page_versions` row holding the revision it started from+ * (`revision_before`), written in the same transaction. Revisions a+ * transaction only passes through are never a ledger state, so they need none.+ * A large or segmented page is exempt: its versions are pruned on their own+ * policy, and page-at-time discloses those bodies as pruned.+ */+import type { BrainEngine } from '../engine.ts';+import { PAGE_INLINE_MAX_BYTES } from '../page-size-policy.ts';++export interface PreimageNeed { pageId: number; slug: string; revision: string }++/** The needs with no version of their starting revision on their page. */+export async function missingPreimages(engine: Pick<BrainEngine, 'executeRaw'>, needs: readonly PreimageNeed[]): Promise<PreimageNeed[]> {+ if (!needs.length) return [];+ const rows = await engine.executeRaw<{ i: number }>(`SELECT n.i FROM unnest($1::bigint[], $2::uuid[]) WITH ORDINALITY AS n(page_id, revision, i)+ WHERE NOT EXISTS (SELECT 1 FROM page_versions v WHERE v.page_id = n.page_id AND v.knowledge_revision = n.revision)`,+ [needs.map(n => n.pageId), needs.map(n => n.revision)]);+ return rows.map(r => needs[Number(r.i) - 1]!);+}++/** Test runs enforce the invariant inside every belief batch; `GBRAIN_BELIEF_PREIMAGE_CHECK=0` turns it off for a probe that breaks it on purpose. */+export const preimageInvariantEnforced = (): boolean => process.env.NODE_ENV === 'test' && process.env.GBRAIN_BELIEF_PREIMAGE_CHECK !== '0';++export interface PreimageGap { event_id: number; slug: string; event_type: string; revision: string; recorded_at: string }++/**+ * Doctor's scan: page events whose `revision_before` no version of the live page holds, on a page whose+ * versions are never pruned. Bounded to the last `windowDays` unless `deep`.+ */+export async function preimageGaps(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, opts: { limit?: number; deep?: boolean; windowDays?: number } = {}): Promise<PreimageGap[]> {+ const rows = await engine.executeRaw<PreimageGap>(`SELECT e.id AS event_id, e.slug, e.event_type, e.value->>'revision_before' AS revision, e.recorded_at+ FROM belief_events e+ JOIN sources s ON s.id = e.source_id AND s.incarnation = e.source_incarnation+ JOIN belief_page_lifetimes l ON l.page_lifetime = e.page_lifetime+ JOIN pages p ON p.id = l.page_id AND p.source_id = e.source_id+ WHERE e.source_id = $1 AND e.subject_kind = 'page' AND NOT e.purged AND e.origin IN ('live', 'unmanaged')+ AND ($2::boolean OR e.recorded_at > now() - make_interval(days => $3::int))+ AND e.value->>'revision_before' IS NOT NULL AND e.value->>'revision_before' IS DISTINCT FROM e.value->>'revision_after'+ AND p.body_storage IS DISTINCT FROM 'segmented'+ AND COALESCE(p.body_bytes, octet_length(COALESCE(p.compiled_truth, '')) + octet_length(COALESCE(p.timeline, ''))) <= $4+ AND NOT EXISTS (SELECT 1 FROM page_versions v WHERE v.page_id = p.id AND (v.body_storage = 'segmented'+ OR COALESCE(v.body_bytes, octet_length(COALESCE(v.compiled_truth, '')) + octet_length(COALESCE(v.timeline, ''))) > $4))+ AND NOT EXISTS (SELECT 1 FROM page_versions v WHERE v.page_id = p.id AND v.knowledge_revision = (e.value->>'revision_before')::uuid)+ ORDER BY e.id DESC LIMIT ${Math.max(1, Math.floor(opts.limit ?? 100))}`, [sourceId, opts.deep === true, opts.windowDays ?? 30, PAGE_INLINE_MAX_BYTES]);+ return rows.map(r => ({ ...r, event_id: Number(r.event_id), recorded_at: new Date(r.recorded_at).toISOString() }));+}diff --git a/src/core/facts/purge.ts b/src/core/facts/purge.tsindex 059aa7d372..12762e33e0 100644--- a/src/core/facts/purge.ts+++ b/src/core/facts/purge.ts@@ -47,6 +47,7 @@ import { carriesClaimSql, claimNeedles, purgeCompletion, verifyFactPurge, type Pimport { noteBelief, withBeliefBatch } from '../belief/ledger.ts';import { markBeliefCommits } from '../belief/append.ts';import { appendPurgeCommitted, appendPurgeIntent } from '../belief/purge-mirror.ts';+import { createPageVersion } from '../page-state/versions.ts';import { appendDerivedHidden, bumpPurgeEpoch, derivedBeliefTargets, derivedStreamSlugs, redactCarryingFields, redactPurgedKeys, registerLiveCarriers, registerVersionCarriers, sourceHasBeliefEvents,type LedgerPurgeReport } from '../belief/purge.ts';@@ -173,7 +174,10 @@ async function assertNoPendingPublication(tx: BrainEngine, sourceId: string, pagwhy: 'Shows the source\'s pending and recovering writes, read-only.' } });}-/** Drop purged rows from each affected page's stored body; returns the slugs rewritten. */+/**+ * Drop purged rows from each affected page's stored body; returns the slugs rewritten. Each page is versioned first+ * (the rewrite advances its revision), and `redactPageVersions` then redacts that version like every other one.+ */export async function rewritePageBodies(tx: BrainEngine, sourceId: string, pages: PurgePlan['pages']): Promise<string[]> {if (!pages.length) return [];const rows = await tx.executeRaw<Record<string, unknown>>(`SELECT p.*,COALESCE((SELECT jsonb_agg(t.tag ORDER BY t.tag) FROM tags t WHERE t.page_id=p.id),'[]'::jsonb) AS purge_tags@@ -185,6 +189,8 @@ export async function rewritePageBodies(tx: BrainEngine, sourceId: string, pagesconst compiled = await dropPurgedFenceRows(tx, sourceId, page.compiled_truth, page.slug);const timeline = await dropPurgedFenceRows(tx, sourceId, page.timeline ?? '', page.slug);if (compiled === page.compiled_truth && timeline === (page.timeline ?? '')) continue;+ const preimage = await tx.readPageSnapshot(page.slug, { sourceId, includeDeleted: true });+ if (preimage) await createPageVersion(tx, page.slug, sourceId, preimage);const hash = contentHash({ ...page, compiled_truth: compiled, timeline, tags: row.purge_tags as string[] });// #5575 ENG-1: dropping a fence row is a gbrain-managed fence edit, not authorship: the page keeps its tier and origin.await withPageTierKept(tx, { sourceId, slug: page.slug }, () => tx.executeRaw(`UPDATE pages SET compiled_truth=$3,timeline=$4,content_hash=$5,updated_at=now(),text_projection_revision=NULL,embedding_signature=NULLdiff --git a/src/core/ops/known-as-of.ts b/src/core/ops/known-as-of.tsindex bde12005f4..9bea00610b 100644--- a/src/core/ops/known-as-of.ts+++ b/src/core/ops/known-as-of.ts@@ -11,6 +11,7 @@ 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 { privatePagesFilterFragment } from '../search/private-visibility.ts';import { unifiedDiff } from '../skillpack/diff-text.ts';export const KNOWN_AS_OF_PARAM: ParamDef = { type: 'string', fullSurfaceOnly: true,@@ -21,20 +22,43 @@ export const VERSIONS_DIFF_PARAM: ParamDef = { type: 'boolean', fullSurfaceOnly: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. */+/**+ * The one source a recorded-time read targets: the explicit or ambient source, else the only granted source whose+ * ledger names the slug. A remote caller's search counts only world-visible events of a page it can see now, and+ * finding none across several sources is `page_not_found`, so which source is picked never reveals a private page.+ */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 visible = ctx.remote === false ? '' : `AND e.visibility = 'world' AND EXISTS (SELECT 1 FROM pages p WHERE p.source_id = e.source_id AND p.slug = e.slug+ AND p.deleted_at IS NULL AND ${privatePagesFilterFragment('p')})`;const rows = await ctx.engine.executeRaw<{ source_id: string }>(`SELECT DISTINCT e.source_id FROM belief_events eJOIN 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]);+ WHERE e.slug = $1 AND e.subject_kind = 'page' AND ($2::text[] IS NULL OR e.source_id = ANY($2::text[])) ${visible} 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';+ if (scope.sourceIds?.length === 1) return scope.sourceIds[0]!;+ if (ctx.remote !== false) throw pageNotFoundError(ctx, String(p.slug), { includeDeleted: p.include_deleted === true });+ return 'default';+}++const PAGE_REFUSALS = new Set(['coverage_from', 'coverage_gap', 'known_as_of_unproven']);++/** Reads the page as recorded; a remote caller that cannot see the page now gets `page_not_found` instead of a coverage or proof refusal about it. */+async function readAsCaller(ctx: OperationContext, q: Parameters<typeof readPageAtTime>[1], includeDeleted: boolean): Promise<PageAtTime> {+ try {+ return await readPageAtTime(ctx.engine, q);+ } catch (error) {+ if (ctx.remote === false || !PAGE_REFUSALS.has(String((error as { code?: unknown }).code))) throw error;+ const [row] = await ctx.engine.executeRaw<{ visible: boolean }>(`SELECT ${privatePagesFilterFragment('p')} AS visible FROM pages p+ WHERE p.source_id = $1 AND p.slug = $2 AND p.deleted_at IS NULL`, [q.sourceId, q.slug]);+ if (row?.visible === true) throw error;+ throw pageNotFoundError(ctx, q.slug, { includeDeleted, sourceIdParam: q.sourceId });+ }}/** Readable intervals: a remote caller sees an interval only under the ledger's visibility rule and the page's current trust floor. */@@ -74,7 +98,7 @@ export async function getPageKnownAsOf(ctx: OperationContext, p: Record<string,}const slug = String(p.slug);const sourceId = await targetSource(ctx, p, 'get_page');- const read = await readPageAtTime(ctx.engine, { sourceId, slug, at });+ const read = await readAsCaller(ctx, { sourceId, slug, at }, p.include_deleted === true);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) };@@ -86,7 +110,7 @@ export async function getVersionsKnownAsOf(ctx: OperationContext, p: Record<striconst 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 read = await readAsCaller(ctx, { sourceId, slug, at, history: true, withBodies: wantBody || p.diff === true }, 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);diff --git a/test/belief-ledger-identity.test.ts b/test/belief-ledger-identity.test.tsindex 385327dfd1..c2a06190bf 100644--- a/test/belief-ledger-identity.test.ts+++ b/test/belief-ledger-identity.test.ts@@ -271,6 +271,7 @@ for (const engineCase of testBackends().map(beliefEngineCase)) {const events = await since(b, () => maintenanceTransaction(b.engine, async tx => {await tx.lockPageKeys(['notes/a-example', 'notes/b-example'].map(slug => ({ sourceId: b.sourceId, slug })));await withBeliefBatch(tx, { sourceId: b.sourceId, slugs: ['notes/a-example', 'notes/b-example'], op: 'review_probe' }, async () => {+ for (const slug of ['notes/a-example', 'notes/b-example']) await tx.createVersion(slug, { sourceId: b.sourceId, preimage: (await tx.readPageSnapshot(slug, { sourceId: b.sourceId }))! });await tx.executeRaw('UPDATE pages SET slug=$1 WHERE source_id=$2 AND slug=$3', ['notes/swap-example', b.sourceId, 'notes/a-example']);await tx.executeRaw('UPDATE pages SET slug=$1 WHERE source_id=$2 AND slug=$3', ['notes/a-example', b.sourceId, 'notes/b-example']);await tx.executeRaw('UPDATE pages SET slug=$1 WHERE source_id=$2 AND slug=$3', ['notes/b-example', b.sourceId, 'notes/swap-example']);diff --git a/test/belief-ledger-page-at-time.test.ts b/test/belief-ledger-page-at-time.test.tsindex 54e222cce1..4d52add74b 100644--- a/test/belief-ledger-page-at-time.test.ts+++ b/test/belief-ledger-page-at-time.test.ts@@ -16,6 +16,12 @@ 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 { withEnv } from './helpers/with-env.ts';+import { enableBeliefLedger } from '../src/core/belief/coverage.ts';+import { preimageGaps } from '../src/core/belief/preimages.ts';+import { beliefLedgerEntry } from '../src/commands/doctor/checks/belief-ledger.ts';+import type { DoctorContext } from '../src/commands/doctor/context.ts';+import type { Check } from '../src/commands/doctor.ts';import { waitForValue } from './helpers/wait-for.ts';import { beliefBrain, beliefEngineCase, beliefPage, type BeliefBrain } from './helpers/belief-ledger.ts';@@ -30,6 +36,7 @@ const read = (b: BeliefBrain, params: Record<string, unknown>) => operationsByNaconst 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 doctor = async (b: BeliefBrain): Promise<Check> => (await beliefLedgerEntry.run({ engine: b.engine, tier: 'standard', doFix: false, dryRun: false, orphanRatioSourceId: b.sourceId } as DoctorContext) as Check[])[0]!;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)) {@@ -293,5 +300,53 @@ for (const engineCase of testBackends().map(beliefEngineCase)) {await b.engine.executeRaw(`UPDATE belief_events SET visibility = 'world' WHERE source_id = $1 AND slug = 'companies/opening-example'`, [b.sourceId]);expect(JSON.stringify(await rversions({ slug: 'companies/opening-example', known_as_of: t2, include_body: true }))).toContain('Private at first.');}), 120_000);++ test('remote callers over several sources: a private page and a never-written slug refuse the same way (no existence oracle through source choice or coverage)', () => brain(async b => {+ const other = `${b.sourceId}-two`;+ await b.engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1)', [other]);+ await enableBeliefLedger(b.engine, other);+ await b.put('companies/hidden-example', beliefPage({ prose: 'Hidden plans.', frontmatter: { visibility: 'private' } }));+ await b.put('companies/shown-example', draft('Shown profile.'));+ const t = await at(b);+ const remote = { ...b.ctx, remote: true, transport: 'http', takesHoldersAllowList: ['world'], sourceId: b.sourceId,+ auth: { token: '', clientId: 'probe', scopes: ['read'], sourceId: b.sourceId, allowedSources: [b.sourceId, other] } } as unknown as typeof b.ctx;+ const outcome = (op: string, slug: string) => operationsByName[op]!.handler(remote, { slug, known_as_of: t, ...(op === 'get_versions' ? { include_body: true, diff: true } : {}) })+ .then(r => ({ ok: true, body: JSON.stringify(r) }), (e: { code?: string; message: string }) => ({ ok: false, code: e.code, message: e.message.replace(slug, '<slug>') }));+ for (const op of ['get_page', 'get_versions']) {+ const hidden = await outcome(op, 'companies/hidden-example');+ expect(hidden).toEqual(await outcome(op, 'companies/never-written-example'));+ expect(hidden).toMatchObject({ ok: false, code: 'page_not_found' });+ expect(await outcome(op, 'companies/shown-example')).toMatchObject({ ok: true });+ }+ }, { managed: false }), 120_000);++ test('the preimage invariant: a publication that moves a page off a revision with no version of it is refused in tests and reported by doctor', () => brain(async b => {+ await b.put('notes/move-example', beliefPage({ type: 'note', title: 'Move', prose: 'Before the move.' }));+ const rawRename = (from: string, to: string) => b.engine.transaction(async tx => {+ await tx.lockPageKeys([from, to].map(s => ({ sourceId: b.sourceId, slug: s })));+ await withBeliefBatch(tx, { sourceId: b.sourceId, slugs: [from, to], op: 'probe_rename' }, () =>+ tx.executeRaw('UPDATE pages SET slug = $1 WHERE source_id = $2 AND slug = $3', [to, b.sourceId, from]));+ });+ const before = await b.lastId();+ // Forced probe: a rename that skips its preimage is refused in the batch, and nothing commits.+ const refused = await rawRename('notes/move-example', 'notes/moved-example').then(() => null, (e: Error) => e.message);+ expect(refused).toContain('belief preimage invariant: notes/move-example moved off revision');+ expect(await b.lastId()).toBe(before);+ expect((await b.engine.executeRaw('SELECT 1 FROM pages WHERE source_id = $1 AND slug = $2', [b.sourceId, 'notes/move-example'])).length).toBe(1);+ // The production rename versions first and passes.+ await renamePageOntoSlug(b.engine, { sourceId: b.sourceId, oldSlug: 'notes/move-example', newSlug: 'notes/moved-example', to: 'notes/moved-example.md' });+ expect(await preimageGaps(b.engine, b.sourceId)).toEqual([]);+ expect((await doctor(b)).status).toBe('ok');+ // With the test-only check off, the same skipped preimage commits, and doctor names it.+ await withEnv({ GBRAIN_BELIEF_PREIMAGE_CHECK: '0' }, () => rawRename('notes/moved-example', 'notes/moved-again-example'));+ await fillCommitMarks(b.engine, b.sourceId);+ const moved = (await b.events(before)).filter(e => e.subject_kind === 'page' && e.slug === 'notes/moved-again-example' && e.value?.revision_before).at(-1)!;+ const gaps = await preimageGaps(b.engine, b.sourceId);+ expect(gaps.map(g => [g.slug, g.event_id, g.revision])).toEqual([['notes/moved-again-example', moved.id, String(moved.value!.revision_before)]]);+ const check = await doctor(b);+ expect(check.status).toBe('warn');+ expect(check.message).toContain(`${b.sourceId}: 1 page transition(s) left no version of the revision they moved off (e.g. notes/moved-again-example at event ${moved.id})`);+ expect(await read(b, { slug: 'notes/moved-example', known_as_of: await at(b) }).catch(() => null)).toBeNull();+ }, { managed: false }), 120_000);});}diff --git a/test/fixtures/goldens/postgres-engine-gauge/acquires-by-case.json b/test/fixtures/goldens/postgres-engine-gauge/acquires-by-case.jsonindex a4b422541b..11d7f2f7e7 100644--- a/test/fixtures/goldens/postgres-engine-gauge/acquires-by-case.json+++ b/test/fixtures/goldens/postgres-engine-gauge/acquires-by-case.json@@ -393,11 +393,11 @@"traversePathsDetailed#out+sourceId+linkType": {},"updatePageContextualRetrievalState#default": {},"updateSlug#moved": {- "raw": 10,+ "raw": 11,"tx": 1},"updateSlug#noop": {- "raw": 1,+ "raw": 2,"tx": 1},"updateSourceConfig#default": {},diff --git a/test/fixtures/goldens/rls-scope-inventory.json b/test/fixtures/goldens/rls-scope-inventory.jsonindex 546fcc9dee..7df312f894 100644--- a/test/fixtures/goldens/rls-scope-inventory.json+++ b/test/fixtures/goldens/rls-scope-inventory.json@@ -3390,23 +3390,28 @@"tx>sp"],"flagOffOpensTransaction": true,- "flagOn": "unscoped",+ "flagOn": "scoped","flagOnLanes": ["tx","tx>sp"],- "flagOnScopes": []+ "flagOnScopes": [+ "src-a"+ ]},"updateSlug#noop": {"flagOffLanes": ["tx"],"flagOffOpensTransaction": true,- "flagOn": "unscoped",+ "flagOn": "scoped","flagOnLanes": [- "tx"+ "tx",+ "tx>sp"],- "flagOnScopes": []+ "flagOnScopes": [+ "default"+ ]},"updateSourceConfig#default": {"flagOffLanes": [diff --git a/test/postgres-rls-scope-inventory.test.ts b/test/postgres-rls-scope-inventory.test.tsindex 557b815609..46be9cd70c 100644--- a/test/postgres-rls-scope-inventory.test.ts+++ b/test/postgres-rls-scope-inventory.test.ts@@ -148,6 +148,7 @@ async function observe(cases: SqlCase[]): Promise<Record<string, RuntimeObservatconst SCOPED_THROUGH_NON_THIS_CALLEE: Record<string, string> = {putPage: 'expectedRevision variant calls tx.readPageSnapshot on the transaction clone',createVersion: 'page-state/versions.ts createPageVersion calls tx.readPageSnapshot',+ updateSlug: 'engine-sql/pages.ts updateSlug versions the page first through tx.readPageSnapshot (belief ledger W2 rename preimage)',replaceDerivedLinks: 'derived-links.ts replaceDerivedLinks reads the origin via readPageSnapshot',replaceDerivedLinksBatch: 'derived-links.ts replaceDerivedLinksBatch reads the origins via tx.readPageSnapshotsBatch',};