Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Lane 2r-9 WIP: streamed drift check and restore for segmented pages over the single-string ceiling

garrytan00f357c70e93
diff --git a/src/commands/export.ts b/src/commands/export.ts
index b7d26961f0..80b5773344 100644
--- a/src/commands/export.ts
+++ b/src/commands/export.ts
@@ -11,7 +11,7 @@ import { resolveRestoreTarget, restoreFilePath } from '../core/restore-target.ts
import { ExportStage, EXPORT_SNAPSHOT_MS, EXPORT_STREAM_BYTES_PER_MS, exportPathKey, exportPayloadLimit } from '../core/export-stage.ts';
import { publishExport } from '../core/export-publish.ts';
import { nativeFileTarget } from '../core/persistence/native-file-target.ts';
-import { readExportPage, readExportWithdrawals, segmentedExportMarkdown } from '../core/export-snapshot.ts';
+import { exportBodyLedger, readExportPage, readExportWithdrawals, segmentedExportMarkdown } from '../core/export-snapshot.ts';
import { readPageBodyPolicy } from '../core/page-body/limits.ts';
import { isSegmentedPage } from '../core/page-body/page-shape.ts';
@@ -105,7 +105,7 @@ a fresh directory. See docs/storage-tiering.md#safe-export.`);
if (isSegmentedPage(page)) {
streamedBytes += Number(key.bytes);
const head = serializeMarkdown(frontmatter, '', '', meta).slice(0, -1);
- await staged.addStream(page.slug + '.md', Number(key.bytes), payloadLimit, segmentedExportMarkdown(tx, page, withdrawals, head));
+ await staged.addStream(page.slug + '.md', Number(key.bytes), payloadLimit, segmentedExportMarkdown(tx, page, exportBodyLedger(page.slug, withdrawals), head));
} else staged.add(page.slug + '.md', 'file', serializeMarkdown(frontmatter, page.compiled_truth, page.timeline, meta));
const raw = Number(key.raw_count) ? await tx.getRawData(page.slug, undefined, { sourceId: page.source_id, includeDeleted: true }) : [];
if (raw.length) {
diff --git a/src/core/export-snapshot.ts b/src/core/export-snapshot.ts
index a208b16859..309841181a 100644
--- a/src/core/export-snapshot.ts
+++ b/src/core/export-snapshot.ts
@@ -4,7 +4,7 @@ import type { PageWithdrawal } from './page-state/types.ts';
import { rowToPage } from './utils.ts';
import { EXPORT_PAYLOAD_LIMIT } from './export-stage.ts';
import { isSegmentedPage } from './page-body/page-shape.ts';
-import { openSegmentedBody, readBodyRange } from './page-body/read-range.ts';
+import { openSegmentedBody, readBodyRange, type BodyLedger } from './page-body/read-range.ts';
import { TIMELINE_SEPARATOR } from './page-window/document.ts';
import type { Page } from './types.ts';
@@ -40,6 +40,11 @@ export async function readExportPage(tx: BrainEngine, key: { id: string; source_
return { page, tags: row.export_tags as string[] };
}
+/** The ledger an export overlays one page's body with: the source's withdrawals that apply to the page. */
+export function exportBodyLedger(slug: string, withdrawals: ExportWithdrawal[]): BodyLedger {
+ return { withdrawals: applicableWithdrawals(slug, withdrawals) };
+}
+
function applicableWithdrawals(slug: string, withdrawals: ExportWithdrawal[]): PageWithdrawal[] {
return withdrawals.filter(w => w.subject === '*' || w.subject === slug)
.map(({ visibility, fact_hash, withdrawn_at, purged }) => ({ visibility, fact_hash, withdrawn_at, ...(purged ? { purged: true } : {}) }));
@@ -48,13 +53,13 @@ function applicableWithdrawals(slug: string, withdrawals: ExportWithdrawal[]): P
/**
* The Markdown file of a segmented page, piece by piece: `head` (serializeMarkdown's frontmatter and blank line), the
* truth, TIMELINE_SEPARATOR before the first timeline byte, the timeline and the final newline. Each segment is read
- * once (readBodyRange, trusted stored body) with the overlay readExportPage gives an inline page, so the bytes are
- * those serializeMarkdown gives the same page read inline. A full collection every EXPORT_COLLECT_BYTES read keeps the
+ * once (readBodyRange, trusted stored body) under `ledger` (export: `exportBodyLedger`, the overlay readExportPage gives
+ * an inline page; a restore: the page snapshot's), so the bytes are those serializeMarkdown gives the same page read inline. A full collection every EXPORT_COLLECT_BYTES read keeps the
* reads' garbage (protocol buffers, decoded texts) from piling up as in the streamed import (ingest.ts): a 127 MiB page
* peaked ~700 MiB above a 2 MiB one without it, 8-55 MiB with it.
*/
-export async function* segmentedExportMarkdown(tx: BrainEngine, page: Page, withdrawals: ExportWithdrawal[], head: string): AsyncIterable<Uint8Array | string> {
- const body = await openSegmentedBody(tx, { pageId: page.id, ledger: { withdrawals: applicableWithdrawals(page.slug, withdrawals) } });
+export async function* segmentedExportMarkdown(tx: BrainEngine, page: Pick<Page, 'id'>, ledger: BodyLedger, head: string): AsyncIterable<Uint8Array | string> {
+ const body = await openSegmentedBody(tx, { pageId: page.id, ledger });
let uncollected = 0;
const collect = (bytes: number) => {
uncollected += bytes;
diff --git a/src/core/page-body/body-digests.ts b/src/core/page-body/body-digests.ts
new file mode 100644
index 0000000000..c76e0c2a16
--- /dev/null
+++ b/src/core/page-body/body-digests.ts
@@ -0,0 +1,94 @@
+/**
+ * Wave B: the drift check of a segmented page whose body is over the
+ * single-string ceiling (page-prepare.ts `prepareFileTarget`) compares its
+ * canonical file with the stored body by digest, never holding either body as
+ * one string. The file side is the streamed importer's pass 1 (`BodyScanner`,
+ * which splits the regions exactly as parseMarkdown does) over the file's
+ * bytes, then each region's byte ranges through SHA-256; the stored side is
+ * the trusted stored body (`readBodyRange`, what readPageSnapshot gives an
+ * inline page after the withdrawal overlay), one segment at a time.
+ */
+import { createHash } from 'node:crypto';
+import type { BrainEngine } from '../engine.ts';
+import type { ParseOpts } from '../markdown.ts';
+import { BodyScanner, type BodyPiece, type BodyScan } from './body-scan.ts';
+import { openSegmentedBody, readBodyRange, type BodyLedger } from './read-range.ts';
+import { readGarbageCollector } from './segment-blocks.ts';
+import { SEGMENT_MAX_BYTES } from './limits.ts';
+import type { BodyRegion } from './types.ts';
+
+const FACTS_MARKER = Buffer.from('gbrain:facts:begin', 'utf8');
+const REGIONS: readonly BodyRegion[] = ['truth', 'timeline'];
+
+/**
+ * @internal Work a digest comparison does, for the memory-bound tests: file bytes the scan and the region hashes read
+ * (`fileBytes`), stored bytes hashed (`segmentBytes`), and the largest single piece handed to a scan or hash
+ * (`largestPiece`, at most a segment). Counts, not time.
+ */
+export const bodyDigestWork = { fileBytes: 0, segmentBytes: 0, largestPiece: 0 };
+
+/** SHA-256 (hex) of each region's UTF-8 bytes. */
+export type RegionDigests = Record<BodyRegion, string>;
+
+/** A reading of file bytes: `prefix` (inferred frontmatter, empty when none), then the bytes from `skip` on (past a BOM). */
+export interface FileReading { prefix: Uint8Array; skip: number }
+
+export type FileDigests =
+ | { kind: 'ok'; parsed: BodyScan['parsed']; digests: RegionDigests; factsFence: boolean }
+ | { kind: 'unreadable'; reason: 'invalid_utf8' | 'frontmatter_head_unbounded' };
+
+function count(piece: Uint8Array, field: 'fileBytes' | 'segmentBytes'): Uint8Array {
+ bodyDigestWork[field] += piece.length;
+ if (piece.length > bodyDigestWork.largestPiece) bodyDigestWork.largestPiece = piece.length;
+ return piece;
+}
+
+/** Bytes `[start, end)` of the virtual stream, as views (no copies). */
+function* virtualSlice(bytes: Uint8Array, reading: FileReading, start: number, end: number): Iterable<Uint8Array> {
+ const { prefix, skip } = reading;
+ if (start < prefix.length) yield prefix.subarray(start, Math.min(end, prefix.length));
+ for (let at = Math.max(start, prefix.length); at < end; at += SEGMENT_MAX_BYTES) {
+ yield bytes.subarray(skip + at - prefix.length, skip + Math.min(end, at + SEGMENT_MAX_BYTES) - prefix.length);
+ }
+}
+
+/** The scan of one reading of the file and the digest of each region; `factsFence` when a region holds a facts fence marker. */
+export function fileBodyDigests(bytes: Uint8Array, reading: FileReading, filePath: string, opts: ParseOpts): FileDigests {
+ const scanner = new BodyScanner(filePath, opts);
+ for (const piece of virtualSlice(bytes, reading, 0, reading.prefix.length + bytes.length - reading.skip)) scanner.push(count(piece, 'fileBytes'));
+ const scan = scanner.finish();
+ if (scan.kind !== 'ok') return { kind: 'unreadable', reason: scan.kind };
+ let factsFence = false;
+ const digest = (pieces: readonly BodyPiece[]) => {
+ const hash = createHash('sha256');
+ let tail = Buffer.alloc(0);
+ for (const piece of pieces) {
+ const parts = 'text' in piece ? [Buffer.from(piece.text, 'utf8')] : virtualSlice(bytes, reading, piece.start, piece.end);
+ for (const part of parts) {
+ hash.update(count(part, 'fileBytes'));
+ const view = Buffer.from(part.buffer, part.byteOffset, part.byteLength);
+ const seam = Buffer.concat([tail, view.subarray(0, FACTS_MARKER.length - 1)]);
+ if (view.includes(FACTS_MARKER) || seam.includes(FACTS_MARKER)) factsFence = true;
+ tail = Buffer.concat([tail, view.subarray(Math.max(0, view.length - FACTS_MARKER.length + 1))]).subarray(-(FACTS_MARKER.length - 1));
+ }
+ }
+ return hash.digest('hex');
+ };
+ return { kind: 'ok', parsed: scan.parsed, digests: { truth: digest(scan.truth), timeline: digest(scan.timeline) }, factsFence };
+}
+
+/** The digest of each region of a segmented page's trusted stored body under `ledger` (the snapshot's withdrawals), one segment at a time. */
+export async function storedBodyDigests(engine: BrainEngine, pageId: number, ledger: BodyLedger): Promise<RegionDigests> {
+ const body = await openSegmentedBody(engine, { pageId, ledger });
+ const collect = readGarbageCollector();
+ const digests = {} as RegionDigests;
+ for (const region of REGIONS) {
+ const hash = createHash('sha256');
+ for await (const piece of readBodyRange(engine, { pageId, space: 'stored', start: 0, end: Infinity, audience: 'trusted', region, body })) {
+ hash.update(count(piece.bytes, 'segmentBytes'));
+ collect(piece.bytes.length);
+ }
+ digests[region] = hash.digest('hex');
+ }
+ return digests;
+}
diff --git a/src/core/page-body/streamed-import.ts b/src/core/page-body/streamed-import.ts
index ed6c7e9ecc..aaebeab5fe 100644
--- a/src/core/page-body/streamed-import.ts
+++ b/src/core/page-body/streamed-import.ts
@@ -183,6 +183,14 @@ async function scanFile(file: FileHandle, bom: number, prefix: Uint8Array, size:
async function inferredPrefix(file: FileHandle, bom: number, size: number, relativePath: string): Promise<Uint8Array | null> {
const buffer = Buffer.alloc(Math.min(FRONTMATTER_HEAD_MAX_BYTES, size - bom));
await file.read(buffer, 0, buffer.length, bom);
+ return inferredHeadPrefix(buffer, relativePath);
+}
+
+/**
+ * The frontmatter inference would prepend to a file, from its head (at most FRONTMATTER_HEAD_MAX_BYTES after the BOM):
+ * empty when no rule applies, null when the head does not hold the first 20 lines inference reads (undecidable).
+ */
+export async function inferredHeadPrefix(buffer: Uint8Array, relativePath: string): Promise<Uint8Array | null> {
const raw = utf8Prefix(buffer, buffer.length);
const head = raw.slice(0, raw.lastIndexOf('\n') + 1);
if (head.split('\n').length <= 20 || !head.trim()) return null;
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index 7fa9cdf7a9..2a46187c12 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -11,7 +11,7 @@ import type { BrainEngine } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
import type { Page, PageVersion } from '../types.ts';
import { importFromContent, verifyPageReadable, type ParsedPage } from '../import-file.ts';
-import { comparableFrontmatter, frontmatterHoldMessageWithoutKeys, parseMarkdown, resolveParsedSubtype, serializePageToMarkdown, resolveSourceLocalFilePath, type ParseOpts } from '../markdown.ts';
+import { comparableFrontmatter, frontmatterHoldMessageWithoutKeys, parseMarkdown, resolveParsedSubtype, serializePageToMarkdown, resolveSourceLocalFilePath, type ParsedMarkdown, type ParseOpts } from '../markdown.ts';
import { assertLargePageReplacement } from './large-page-guard.ts';
import { applyInference } from '../frontmatter-inference.ts';
import { OperationError, opError } from '../ops/contract.ts';
@@ -45,7 +45,16 @@ import { materializedSnapshot, sealSegmentedPage } from './segmented-apply.ts';
import { pipelined } from '../page-state/transactions.ts';
import { overlayCanonicalBodies } from '../page-state/snapshot.ts';
import { segmentedRevertRefusal } from '../page-state/versions.ts';
-import { isSegmentedPage } from '../page-body/page-shape.ts';
+import { bodyUnread, isSegmentedPage, pageBodySegmentedError, withoutBody } from '../page-body/page-shape.ts';
+import { fileBodyDigests, storedBodyDigests, type FileReading, type RegionDigests } from '../page-body/body-digests.ts';
+import { ledgerApplies } from '../page-body/segment-ledger.ts';
+import { inferredHeadPrefix } from '../page-body/streamed-import.ts';
+import { FRONTMATTER_HEAD_MAX_BYTES } from '../page-body/limits.ts';
+import { occurrencesWithoutChunks } from '../page-body/ingest.ts';
+import { buildSegmentedProjection } from '../page-body/projection.ts';
+import { segmentedExportMarkdown } from '../export-snapshot.ts';
+import { loadImportSanityConfig } from '../import-screen.ts';
+import { DEFAULT_WRITE_GATE_CONFIG, writeGateApplies } from '../write-gate.ts';
import { materializeTimeline, prepareCanonicalProjections, type TimelineRowsRemoved } from './canonical-projections.ts';
import { assertTimelineNotOmitted, timelineWritePolicy } from './timeline-omission.ts';
import { preserveProtectedTakes } from './protected-takes.ts';
@@ -166,17 +175,7 @@ export async function fileMatchesSnapshot(engine: BrainEngine, slug: string, byt
const expected = digest(canonical(snapshot.page, snapshot.tags));
const matches = async (content: string, inferred: boolean) => {
const parsed = parseMarkdown(content, slug, { activePack });
- // #5521 parity for subtype (#5928): a pack rule is not part of the file's bytes, so a file
- // without an explicit `subtype:` keeps the stored subtype (or none); the import still stamps it.
- delete parsed.inferredSubtype;
- resolveParsedSubtype(parsed, snapshot.page);
- // #6429: the v0.13.1 grandfather stamped `validate: false` into the database; on an unmanaged brain that path
- // never wrote the file, so the file lacks a key the database carries. The mechanical stamp authors nothing
- // (grandfather.ts): a file without a `validate:` key keeps the stored stamp, and the next coordinated write publishes it.
- if (!Object.hasOwn(parsed.frontmatter, 'validate') && snapshot.page.frontmatter?.validate === false) parsed.frontmatter.validate = false;
- // #1035 parity (#5521): a file without an explicit `type:` keeps the stored type on import. An inferred
- // type is not one the file declared (#6605): inference only applies to a file with no frontmatter.
- const type = parsed.typeExplicit && !inferred ? parsed.type : snapshot.page.type;
+ const type = importedFileType(parsed, snapshot.page, inferred);
// Withdrawal overlays intentionally precede physical mirroring. The ledger
// is applied by the import preparation and cannot be undone by this check.
const actual = canonical({ ...parsed, type, ...await overlayCanonicalBodies(engine.executeRaw.bind(engine),
@@ -187,8 +186,50 @@ export async function fileMatchesSnapshot(engine: BrainEngine, slug: string, byt
const reading = readCanonicalAsImported(bytes, typeof sourcePath === 'string' ? sourcePath : await sourcePath());
return reading.inferred && await matches(reading.content, true);
}
+/** The type a file's parse compares with (`fileMatchesSnapshot`), after aligning the parse with what its import over `page` stores. */
+function importedFileType(parsed: ParsedMarkdown, page: Pick<Page, 'type' | 'frontmatter'>, inferred: boolean): Page['type'] {
+ // #5521 parity for subtype (#5928): a pack rule is not part of the file's bytes, so a file
+ // without an explicit `subtype:` keeps the stored subtype (or none); the import still stamps it.
+ delete parsed.inferredSubtype;
+ resolveParsedSubtype(parsed, page);
+ // #6429: the v0.13.1 grandfather stamped `validate: false` into the database; on an unmanaged brain that path
+ // never wrote the file, so the file lacks a key the database carries. The mechanical stamp authors nothing
+ // (grandfather.ts): a file without a `validate:` key keeps the stored stamp, and the next coordinated write publishes it.
+ if (!Object.hasOwn(parsed.frontmatter, 'validate') && page.frontmatter?.validate === false) parsed.frontmatter.validate = false;
+ // #1035 parity (#5521): a file without an explicit `type:` keeps the stored type on import. An inferred
+ // type is not one the file declared (#6605): inference only applies to a file with no frontmatter.
+ return parsed.typeExplicit && !inferred ? parsed.type : page.type;
+}
+/**
+ * Wave B: `fileMatchesSnapshot` for a segmented page whose body was not read back (over the single-string ceiling).
+ * The same comparison with each body region replaced by its SHA-256 on both sides: the file's regions as the streamed
+ * importer's scan splits them, the stored ones from the trusted stored body (body-digests.ts), one segment at a time.
+ * The withdrawal overlay leaves a body without a facts fence unchanged; a file whose body has one under a ledger
+ * that applies cannot be overlaid streamed, so it refuses (`page_body_segmented`) instead of reading as drift.
+ */
+async function segmentedFileMatches(engine: BrainEngine, slug: string, bytes: Buffer, snapshot: PageSnapshot,
+ sourcePath: () => Promise<string>, activePack?: ParseOpts['activePack']): Promise<boolean> {
+ const ledger = { withdrawals: snapshot.withdrawals, ...(snapshot.globalPurges ? { globalPurges: snapshot.globalPurges } : {}) };
+ let stored: RegionDigests | undefined;
+ const matches = async (reading: FileReading, inferred: boolean) => {
+ const file = fileBodyDigests(bytes, reading, slug, { activePack });
+ if (file.kind !== 'ok') return file.reason;
+ if (file.factsFence && ledgerApplies(ledger)) throw pageBodySegmentedError(snapshot.page, 'fileMatchesSnapshot (a facts fence under withdrawals)');
+ const parsed = { ...file.parsed, compiled_truth: file.digests.truth, timeline: file.digests.timeline };
+ const type = importedFileType(parsed, snapshot.page, inferred);
+ stored ??= await storedBodyDigests(engine, Number(snapshot.page.id), ledger);
+ return digest(canonical({ ...parsed, type }, parsed.tags))
+ === digest(canonical({ ...withoutBody(snapshot.page), compiled_truth: stored.truth, timeline: stored.timeline }, snapshot.tags));
+ };
+ const raw = await matches({ prefix: new Uint8Array(0), skip: 0 }, false);
+ if (raw === true) return true;
+ if (raw === 'invalid_utf8') return false;
+ const skip = bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf ? 3 : 0;
+ const prefix = await inferredHeadPrefix(bytes.subarray(skip, skip + FRONTMATTER_HEAD_MAX_BYTES), await sourcePath());
+ return !!prefix?.length && await matches({ prefix, skip }, true) === true;
+}
export async function prepareFileTarget(engine: BrainEngine, row: Pick<WriteRequest, 'source_id' | 'worktree_id' | 'slug'> & { operation?: string }, snapshot: PageSnapshot | null,
- content: string | null, hostId?: string, options: { allowMissing?: boolean; deleting?: boolean; capture?: { path: string; hash: string }; activePack?: ParseOpts['activePack']; remote?: boolean;
+ content: string | Uint8Array | null, hostId?: string, options: { allowMissing?: boolean; deleting?: boolean; capture?: { path: string; hash: string }; activePack?: ParseOpts['activePack']; remote?: boolean;
/** #6368: a tombstone purge whose file matches these sync.exclude globs (relative to the source root) owns no file. */
excludeTombstone?: { patterns: string[]; onExcluded: (path: string) => void };
/** #6517: a delete whose file another live page of the source records owns no file; the census target and claimants are reported. */
@@ -254,7 +295,9 @@ export async function prepareFileTarget(engine: BrainEngine, row: Pick<WriteRequ
// Unknown local edits require explicit import/recovery, even for force writes.
if (before && snapshot) {
const importPath = async () => scannerSourcePath(root, path, mode ?? await scannerSlugRootMode(engine, row.source_id, root));
- if (!await fileMatchesSnapshot(engine, row.slug, before.toString('utf8'), snapshot, importPath, options.activePack)) {
+ const matches = bodyUnread(snapshot.page) ? await segmentedFileMatches(engine, row.slug, before, snapshot, importPath, options.activePack)
+ : await fileMatchesSnapshot(engine, row.slug, before.toString('utf8'), snapshot, importPath, options.activePack);
+ if (!matches) {
const held = await heldFileRefusal(engine, row, root, path, 'drift', options.remote === true);
if (held) throw held;
// #6394: a page that never recorded its file reconciles against the file at its slug path only when adopted explicitly.
@@ -410,6 +453,59 @@ async function prepareDeletePageMutation(engine: BrainEngine, row: WriteRequest,
return prepared;
}
+/**
+ * Wave B: `restore_page` of a segmented page whose body was not read back (over the single-string ceiling). Soft
+ * delete only set `deleted_at` (its body, chunks, links and projections stay), so the restore clears it without
+ * re-serializing or re-importing the body: version, clear, reseal (or queue the projection when chunks are missing).
+ * The canonical file is serializePageToMarkdown's bytes streamed from the segments by export's serializer into one
+ * buffer, never one string. A step that needs the whole body refuses (`page_body_segmented`): a core page's budget
+ * render, and a write gate that applies to the restoring writer's tier.
+ */
+async function prepareUnreadRestore(engine: BrainEngine, row: WriteRequest, snapshot: PageSnapshot,
+ options: { activePack?: ParseOpts['activePack']; clock?: ClaimPhaseClock; allowMissingFile?: boolean }): Promise<PreparedMutation> {
+ const source = { sourceId: row.source_id };
+ const noop = snapshot.page.deleted_at == null;
+ const storedTier = await storedPageTier(engine, row.source_id, row.slug);
+ const trust = pageWriteTrust(row, snapshot.page.frontmatter);
+ const gateTrust = pageGateTrust(row, trust, storedTier);
+ if (!noop && gateTrust && writeGateApplies(gateTrust.tier, (await loadImportSanityConfig(engine)).writeGate ?? DEFAULT_WRITE_GATE_CONFIG)) {
+ throw pageBodySegmentedError(snapshot.page, `restore_page (the write gate scans the whole body of a ${gateTrust.tier} write)`);
+ }
+ enterClaimStep(options.clock, 'core_guard', undefined, 'db');
+ const core = noop ? null : await prepareCoreGuard(engine, { row, snapshot, incoming: snapshot.page });
+ enterClaimStep(options.clock, 'file_target', undefined, 'fs');
+ const file = await prepareFileTarget(engine, row, snapshot, await unreadPageFile(engine, snapshot), undefined,
+ { allowMissing: options.allowMissingFile, activePack: options.activePack, remote: row.authority.remote });
+ const pageId = Number(snapshot.page.id);
+ let complete = true;
+ const prepared: PreparedMutation = { observedRevision: snapshot.revision, noop, file, ...await pageDatabaseOnlyPublication(engine, row, file),
+ ...(core ? { exclusiveSources: core.exclusiveSources } : {}), ...(trust ? { trust } : {}),
+ validate: async tx => { await core?.validate(tx); },
+ apply: async tx => {
+ if (noop) return { ...pageNoopAdvisories(row), status: 'skipped', slug: row.slug, source_id: row.source_id, noop: true, chunks: 0, chunk_skip_reason: 'write_skipped' };
+ await tx.createVersion(row.slug, source);
+ await tx.restorePage(row.slug, source);
+ const lowered = storedTier ? await recordAgentPageLowering(tx, row, { tier: storedTier, revision: snapshot.revision }) : null;
+ const [page] = await tx.executeRaw<{ body_generation: number | string }>('SELECT body_generation FROM pages WHERE id=$1', [pageId]);
+ complete = !(await occurrencesWithoutChunks(tx, pageId, Number(page!.body_generation), await tx.readManifest(pageId))).length;
+ if (complete) await sealSegmentedPage(tx, pageId);
+ if (core) await core.record(tx, (await tx.readPageSnapshot(row.slug, source))?.revision ?? null);
+ return { ...pageNoopAdvisories(row), status: 'restored', slug: row.slug, source_id: row.source_id, chunks: 0, noop: false,
+ ...(complete ? {} : { projection: 'pending' }), ...await sizeStateField(tx, row.source_id, row.slug, snapshot.page),
+ ...(lowered ? { trust_lowered: lowered } : {}) };
+ },
+ afterCommit: async target => { if (!complete) await buildSegmentedProjection(target, source).catch(() => undefined); } };
+ return prepared;
+}
+/** serializePageToMarkdown's bytes for a page whose body was not read back, streamed from its segments into one buffer. */
+async function unreadPageFile(engine: BrainEngine, snapshot: PageSnapshot): Promise<Buffer> {
+ const head = serializePageToMarkdown({ ...withoutBody(snapshot.page), compiled_truth: '', timeline: '' }, snapshot.tags).slice(0, -1);
+ const ledger = { withdrawals: snapshot.withdrawals, ...(snapshot.globalPurges ? { globalPurges: snapshot.globalPurges } : {}) };
+ const parts: Uint8Array[] = [];
+ for await (const piece of segmentedExportMarkdown(engine, snapshot.page, ledger, head)) parts.push(typeof piece === 'string' ? Buffer.from(piece, 'utf8') : piece);
+ return Buffer.concat(parts);
+}
+
/**
* Providers and parsing run before the OS lock and before any publication transaction.
* `coordinated`: the caller publishes this mutation itself through the coordinator, whose
@@ -469,6 +565,7 @@ export async function preparePageMutation(unbounded: BrainEngine, row: WriteRequ
if (!snapshot) throw pageRefusal('page_not_found', 'Page not found.', row,
`Page ${row.slug} does not exist in source ${row.source_id} (it was purged or never written), so nothing was ${row.operation === 'restore_page' ? 'restored' : 'reverted'}. Check the slug and the source.`,
pageFix(row.source_id, row.slug));
+ if (row.operation === 'restore_page' && bodyUnread(snapshot.page)) return prepareUnreadRestore(engine, row, snapshot, { activePack, clock, allowMissingFile: options.allowMissingFile });
let page = snapshot.page;
let tags = snapshot.tags;
if (row.operation === 'revert_version') {