Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Lane D: lossless delete/restore of file-backed pages over 24 MiB; prior file staged by path and digest
garrytan1d807570540f
diff --git a/docs/architecture/key-files/core-services-2-continued.md b/docs/architecture/key-files/core-services-2-continued.mdindex f27ff64954..57a27219f8 100644--- a/docs/architecture/key-files/core-services-2-continued.md+++ b/docs/architecture/key-files/core-services-2-continued.md@@ -21,6 +21,7 @@ The page-state concurrency foundation under `src/core/page-state/` and the share- `src/core/page-body/read-range.ts` + `segment-projection.ts` + `segment-ledger.ts` — Wave B PR 2 (spec 7.1, 7.3): the segment reader. `openSegmentedBody` reads a page's live manifest rows and its withdrawal ledger (`readBodyLedger`); `readBodyRange(engine, { pageId, space, start, end, audience, region?, body? })` streams pieces one segment text at a time, never the whole body. Remote reads and every projected-space read serve the read projection: `projectSegment` projects whole segments from their stored protected regions (takes, truncated tail and markers out, keys as the projection token, facts regions rendered world-only and credential-projected), after the withdrawal overlay (`overlaySegmentText`; a fence split by a forced cut is omitted for reads and refuses a trusted read) and the fence overlay (held and purged rows out, rows below the page tier in the low-tier block after the truth). A transform or stale metadata recomputes the regions from the segment's entry state; with none usable the read refuses `page_projection_stale`, never raw text. Trusted stored-space reads give the overlaid stored stream. `projectedLayout` (cached on the handle), `projectedUnits` (rows and fixed text in projected order, for `page-window/segmented.ts`), `projectedTotals`, `projectedLineStart` and `projectedOutline` (outline from stored metadata, no segment text) locate projected bytes; the concatenation equals `projectPageText` of the joined body byte for byte except where a facts fence is longer than a segment (shows less). The chunker (`segment-chunks.ts`) chunks the same projection, so sealed segmented pages carry `MARKDOWN_CHUNKER_VERSION`; `sealSegmentedPage` indexes the overlaid, sanitized timeline lead. Pinned by `test/large-pages/projection-parity.test.ts`, `remote-window-privacy.test.ts` and `sealed-segmented-search.test.ts` (fixture `test/helpers/segmented-privacy-fixture.ts`).- `src/core/page-body/segment-rewrite.ts` — fence rewrites of a segmented body without holding it as one string (forget strikes, purge drops). Only stored `facts`/`takes` protected regions are decoded and passed, in body order with their region, to a `FenceTransform` (a region crossing forced cuts is joined with its neighbours, refused above `PAGE_MAX_BYTES`). `rewriteLiveSegmentedFences` re-stages the live body through `prepareSegmentedBody` from the segment stream with the changed units replaced and flips it in the caller's transaction (trust tier and soft delete kept; null when nothing changed); `rewriteSegmentedGeneration` rebuilds one retained generation under its own number and updates its versions' hash and size; `rewrittenContentHash` streams the hash of a rewritten generation; `segmentedBodyContains` searches a body segment by segment with the previous segment's tail carried over. Tests: `test/large-pages/purge-segments.test.ts`, `forget-scope.test.ts`, `page-purge-segments.test.ts`.- `src/core/page-body/segment-blocks.ts` + `segment-links.ts` + `segment-takes.ts` — Wave B PR 2 (spec 8, full-pass mode): the derived passes over a segmented body, O(page) work and O(segment) memory, not yet incremental. `bodyBlocks(engine, page, { regions?, separator?, want? })` yields the trusted, withdrawal-overlaid joined body one block at a time (a segment, or a run joined across forced cuts, refused above `BLOCK_MAX_BYTES` with `page_body_segmented`; `want` skips a run unread), so each block starts where the parsers start fresh; `truthLead` reads a bounded lead; `readGarbageCollector` forces a collection every 4 MiB read; `detachedValue` copies a result kept past its block so it pins no segment text; `segmentedPassWork` counts the passes' work for the linearity test. `extractSegmentedPageLinks` runs `extractBodyLinks` over each block in a window (`bodyWindows`: the whole blocks before it, 4096 chars after, the headings still open), with the role phrases a first pass found (`segmentedRoleText`), and merges candidates in `extractPageLinks` order, plus the temporal inputs (`TemporalBody`). `parseTakesFenceBlocks` gives `parseTakesFence` of the joined body. Consumers: link preparation and the links effect, stale-links maintenance, source reconciliation, the sweep, `extract links|timeline|takes --source db`, the mention pass (`pageMentions`), the canonical prior view (`segmentedPriorView`), `segmentedTimelineText`, the chronicle judge and the facts planner (`planSegmentedExtraction`). Tests: `test/large-pages/segmented-derived-parity.test.ts`, `segmented-derived-passes.test.ts`, `segmented-derived-linear.test.ts`, `segmented-derived-memory.slow.test.ts`, `segmented-derived-work.test.ts`. `segment-lines.ts` serves the line-local maintenance scans: `bodyLines` yields the joined text's complete lines a block at a time (a line cut by a block boundary is carried, counted in `segmentedPassWork.carry`), consumed by `gbrain integrity` and `reconcile-links`; `segmentedRegionContains` searches one region for literal markers across block boundaries (repair `connector-fences`). Test: `test/large-pages/segmented-maintenance-commands.test.ts`.+- `src/core/persistence/large-file.ts` — Wave B PR 2 fix lane D: canonical files over 24 MiB (`LARGE_FILE_MIN_BYTES`) on the publication path, never one string or Buffer. `hashFile`/`hashDescriptor` (the persistence file hash, read in one-segment pieces), `FileBytes` (a file read on demand through one descriptor, the `ByteSource` the drift check's `fileBodyDigests` takes; `close` refuses `source_changed` when the file changed while read), `StreamedFileContent` (restore_page's file: export's serializer over the segments, measured once in preparation, produced again by `stageStreamedContent` into the reserved publication stage after the recovery record is durable and before the publication transaction; a mismatch removes the stage and refuses `revision_conflict`), and `stageBeforeCopy` (the prior file copied by the kernel into its `before` stage, hashed and fsynced; the recovery record names it by path and SHA-256 instead of embedding base64, and reserves the file once). `largeFileWork` (@internal) counts bytes read, written and copied and the largest piece. Coordinator: `pageRecoveryRecord` → `largeRecoveryRecord`, `stageLargeFiles`, `publishStagedContent`; a group publication never takes such a member (`groupable`). Tests: `test/large-pages/segmented-delete-restore-file.slow.test.ts` (27 and 90 MiB round trips byte for byte, both engines), `test/large-pages/segmented-delete-crash.serial.test.ts` (SIGKILL between file removal and commit, and after the restoration rename).- `src/core/page-body/body-digests.ts` — Wave B PR 2: the digests the drift check of a segmented page over the single-string ceiling compares (`page-prepare.ts` `segmentedFileMatches`). `fileBodyDigests(bytes, reading, filePath, opts)` runs the streamed importer's pass 1 (`BodyScanner`) over one reading of the file's bytes (an inferred-frontmatter prefix, then the bytes past a BOM), then SHA-256 over each region's byte ranges, and reports a facts fence marker; `storedBodyDigests(engine, pageId, ledger)` hashes each region of the trusted stored body (`readBodyRange`, one segment per read, `readGarbageCollector`). `bodyDigestWork` counts file and stored bytes and the largest piece handed to a scan or hash (at most a segment). In `page-prepare.ts`, `prepareFileTarget` compares a page whose body was not read back through `segmentedFileMatches` (the raw reading, then the inferred one from `streamed-import.ts` `inferredHeadPrefix`; the same normalizations as `fileMatchesSnapshot` via `importedFileType`); a file body with a facts fence under a withdrawal ledger that applies refuses `page_body_segmented` instead of reading as drift. `restore_page` of such a page (`prepareUnreadRestore`) versions it, clears `deleted_at` and reseals (or leaves the projection queued when chunks are missing) without re-importing, and publishes `serializePageToMarkdown`'s bytes streamed from the segments by `segmentedExportMarkdown` into one buffer (under the 25 MiB pre-push scan cap); a core page and an external_untrusted writer refuse `page_body_segmented`, and an agent-tier writer's advisory write-gate scan is not re-run over the unchanged body. Tests: `test/large-pages/segmented-file-drift.test.ts`.- `src/core/page-body/segment-facts.ts` + `segment-conversation.ts` — Wave B PR 2 lane 2e2 (spec 8, full-pass mode): the facts fence reconcile and conversation facts over a segmented body. `segmentedFactsFenceView` is `factsFenceView` (facts-fence.ts: each section's parsed fence, which sections hold one, and the #3625 timeline marker) read from the segments: one SQL query selects the live manifest rows that carry facts slots, a forced cut, or a begin/end marker (bytea `position`, nothing transferred), and `bodyBlocks`' `want` option reads only the runs holding them; the segmenter never cuts inside a fence, so a fence lies in one block (a longer one is a forced run, refused above `BLOCK_MAX_BYTES` with `page_body_segmented`), and joining one across blocks is a bounded fallback. `segmentedBodyMatchesFile` is `canonicalCacheState`'s stale-cache check for a segmented page: the canonical file streamed through `BodyScanner` against the stored regions, by length and SHA-256. `readSegmentedConversationInput` gives `readConversationInput` (conversation-parser/body.ts) the summary body through ranged reads: whole within `CONVERSATION_WINDOW_BYTES` (`PAGE_MAX_BYTES`), else the newest whole segments that fit (never starting inside a forced run) with the window's `fallbackDate` from its first segment's entry state; extract-conversation-facts parses that window, passes the date to the parse and the extractor, and writes a `tail_window` receipt (`window_rule: no_prior_facts`), but only on a page with no conversation facts: one that has any keeps them and is skipped (`skipped_too_large`, `window_rule: prior_facts_kept`), since the run clears every prior fact. Each loop counts its reads in `segmentedPassWork`. Consumers: `runExtractFacts` (`planFenceReconcile`, the stale-cache guard, the managed fence-facts request), the sweep's fence candidates (segmented pages with facts slots), `extract-conversation-facts`. Tests: `test/large-pages/segmented-facts-reconcile.test.ts`, `segmented-conversation-facts.test.ts`, `segmented-derived-linear.test.ts`.- `src/core/page-window/bounded-lead.ts` — leads, snippets and synopses read a bounded prefix, never the whole body: fan-out SQL selects `boundedBodyPrefixSql(alias)` (`left(coalesce(alias.compiled_truth, alias.truth_lead), 65536)`: a segmented page's NULL body falls back to its stored lead; the one COALESCE of body and lead the page body reader ratchet allows by name), `boundedRawPrefix` cuts a body at 64 KiB on a code point, and `overlaidBoundedRows` / `overlaidBoundedPrefix` replace a prefix holding a `gbrain:facts:begin` marker with the prefix of the withdrawal-overlaid body (one batched `readPageSnapshotsBatch` read; a page it no longer returns, or a failed read, gets an empty lead). A segmented page's row carries its stored `truth_lead`; when that lead holds a facts fence it is overlaid alone with the withdrawal ledger the snapshot read returns (`overlayCanonicalBodies`, then the same 64 KiB cut), never by reading segments. `pageLeadSource` gives getPage callers (exact-slug and alias snippets) a page's compiled truth, or a segmented page's `truth_lead` without touching its throwing body getters. `projectedLead` is that prefix through `boundedProjectedPrefix` (`document.ts`). Consumers: the exact-slug tier (`exact-lookup.ts`) and alias injection (`alias-hop.ts`) snippets, relational hydrate, the reflex pointer synopsis (`retrieval-reflex.ts` `safeSynopsis`: world-only reads take the projected prefix, the trusted entity-card widening the raw prefix through its own fence strip), the entity card's hit row and `entity names` leads, and think's anchor and window-floor rows (`think/gather.ts`: the raw overlaid prefix for the trusted local CLI, the projected prefix otherwise). Small pages render as before. Pinned by `test/bounded-lead.test.ts` and `test/large-pages/segmented-leads.test.ts`.diff --git a/docs/architecture/key-files/schema-mutation.md b/docs/architecture/key-files/schema-mutation.mdindex c9bdc68a62..07bc17c902 100644--- a/docs/architecture/key-files/schema-mutation.md+++ b/docs/architecture/key-files/schema-mutation.md@@ -6,7 +6,7 @@ The schema-pack mutation surface: six foundation modules + a mutate skeleton +stats/sync data plane + CLI verbs + MCP ops + a first-class agent skill.Key files:-- `src/core/persistence/staging.ts` — journaled same-directory staging descriptors reserve names, expected sizes and full hashes before any sink. Owner-locked recovery removes only known complete regular files; partial/unexpected bytes keep the root and recovery quota blocked, including committed receipt cleanup. Legacy records acquire durable staging descriptors before any new restoration. Final accounting requires verified absence and parent-directory durability. A regular-file ancestor proves an uncreated staging leaf is absent; recovery flushes the containing directory and settles the storage failure without deleting that ancestor or retaining a false recovery fence. Tests: `atomic-write.test.ts`, `atomic-long-staging.test.ts`, `persistence-staging.test.ts`, and eight-boundary process-crash harness.+- `src/core/persistence/staging.ts` — journaled same-directory staging descriptors reserve names, expected sizes and full hashes before any sink. Owner-locked recovery removes only known complete regular files; partial/unexpected bytes keep the root and recovery quota blocked, including committed receipt cleanup. Legacy records acquire durable staging descriptors before any new restoration. Final accounting requires verified absence and parent-directory durability. Stage digests are read in pieces (`large-file.ts` `hashDescriptor`). Wave B: a `before` stage (`.<sha256>.tmp.before-<uuid>`, a name older binaries refuse) holds the copy of a prior canonical file over 24 MiB; a live request's recovery keeps it (`cleanupRecoveryStaging(record, { keepBefore })`) until `restoreBeforeStage` renames it back over the file with its recorded mode or it is removed because the file already holds the prior bytes. A regular-file ancestor proves an uncreated staging leaf is absent; recovery flushes the containing directory and settles the storage failure without deleting that ancestor or retaining a false recovery fence. Tests: `atomic-write.test.ts`, `atomic-long-staging.test.ts`, `persistence-staging.test.ts`, and eight-boundary process-crash harness.- `src/core/fs-durable.ts` — the shared durable-flush leaf (imports only `node:fs`). `flushFile(path)` fsyncs a file nobody holds open through `'r+'` on win32 (Windows `FlushFileBuffers` needs write access) and `'r'` elsewhere (a 0444 file stays flushable); a read-only file on win32 cannot be opened writable and is left to the OS. `flushDirectory(path, { bestEffort })` is strict by default: every error propagates except the win32 no-directory-flush codes (`EISDIR`/`EPERM`/`EINVAL`/`ENOTSUP`), a non-directory path fails `ENOTDIR`, and `bestEffort` swallows everything. `sameFileMode(actual, expected)` compares every permission bit on POSIX and only the owner write bit on win32, whose stat reports 0444/0666. A writer that still holds its descriptor sets the mode with `fchmodSync(fd)` and fsyncs that descriptor instead (atomic-write, skill-bundle staging). Callers: atomic-write, the persistence coordinator, identity, root registry, physical-root records, reconcile backups, recovery staging, topology checkouts (`flushTopologyDirectory` re-export, `flushTopologyTree`), skill bundles, agent-install state (`syncDirectory` re-export), `sources reconcile` previews and attendance-repair checkpoints. `scripts/check-durable-flush.ts` keeps new read-handle flushes out of `src/` (docs/TESTING.md#durable-flush-guard). Tests: `test/fs-durable.test.ts`, `test/persistence-windows-flush-5595.test.ts`, `test/bundle-files-windows-5475.test.ts`, `test/init-packaged-skills-native.test.ts`, run natively on windows-latest in the test.yml security-regressions job.- `src/core/atomic-write.ts` — the shared atomic file writer for brain-repo markdown writers: unique short hidden tmp sibling from `atomicStagingPath` (`.<sha256(full target path)>.tmp.<uuid>`, so a valid basename near NAME_MAX still stages, #5861; `validateAtomicStagingPath` also accepts the historical `<target>.tmp.<uuid>` journal form, and recovery (`persistence/staging.ts` `upgradeRecoveryStaging`) durably swaps in a short stage only for a recorded historical leaf that returns ENAMETOOLONG; `timeline-write-through.ts` reuses the same allocator) → write loop until every byte lands (writeSync may legally short-write under disk pressure; a silent short write could atomically install truncated content) → fsync → close → synchronous staging boundary → optional `verify(onDiskBytes)` callback (throw = abort, tmp removed, target untouched) → atomic rename → parent-directory fsync through `fs-durable.ts` `flushDirectory` (rename durability; strict under `durable`, the journaled-publication flag, best-effort otherwise). The stage is opened with its final mode and `fchmod`-ed on the descriptor past the umask before any byte is written: `AtomicWriteOpts.mode` sets exact bits and reasserts them over an existing target's mode (a legacy 0644 file tightens on its next write); omitted, the target's existing mode is preserved, else 0644 & ~umask. `mkdirPrivate(dir, root = dir)` creates gbrain-private directories: a missing `root` gets default-permission ancestors and is itself made exactly 0700, each missing directory between `root` and `dir` is created 0700 (`O_NOFOLLOW` fchmod), and a directory that already exists, possibly one the user chose, is never chmod-ed; `dir` outside `root` throws. Consumers of the private modes: the Google connector (`google-source.ts`, `sources-ops.ts` Google add) and the persistence coordinator's Google publication. Consumed by `src/commands/backlinks.ts` (which verifies with `parseMarkdown({validate:true})` before the rename). Rename prevents torn writes, NOT lost updates — read-modify-write callers pair it with `withPageLock` (backlinks does). Unifying the per-module copies (skillopt/apply-edits, write-through, lint) is a filed TODO.- `src/core/schema-pack/unify-types-handler.ts` + `src/core/onboard/checks.ts` (`checkPackUpgradeAvailable`) — pack-upgrade retype (`runUnifyTypes`, the `unify-types` job). #6196: on a managed brain apply runs the dry run first (`applyOnManagedBrain`): with nothing to retype, link or alias it only switches the active pack (`flipActivePack`, DB + file plane); otherwise it refuses `writer_coordinator_required` with the counts and a read-only `gbrain onboard --check --explain` fix before any lock or write, and the dry run warns that apply waits for coordinated retype. `pack_upgrade_available` on a managed brain is an info row (`readiness_state: degraded`) with that preview as its fix and no `unify-types` apply remediation it could not run. Coordinated retype (D2) is deferred.diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex 415c79c933..939134c397 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -2257,6 +2257,19 @@ put those bytes in place by hand, and let the resident writer finish therecovery. Pass `--request-id` to resolve the page recoveries on the samesource.+### Recovery large file unsupported++`recovery_large_file_unsupported`: `gbrain repair stuck-recovery` found a page+recovery whose prior file is over the 24 MiB single-string ceiling. Its prior+bytes are kept as a staged copy beside the file (named in the record, with its+SHA-256) instead of inside the record, and the preview's diff would read both+files whole, so nothing was changed. Inspect the request read-only with+`gbrain sources writer status --source <id> --json`, ask the user which version+to keep, put those bytes at the canonical path by hand (the staged copy holds+the prior bytes; never delete it), and let the resident writer finish the+recovery: it renames the copy back when the file holds the published bytes, and+removes it when the file holds the prior ones.+### Recovery choice refused`recovery_choice_refused`: `gbrain repair stuck-recovery` will not apply thatdiff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex af6c9e3b93..70d950fec5 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -660,6 +660,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: 'TBD', text: '`delete_page` (soft and `purge: true`), `restore_page`, `gbrain delete` and `gbrain restore` now work on a page over 24 MiB on a source backed by files: the file is compared with the page by digest, streamed, and a file edited on disk still refuses as before. Restoring such a page clears its deletion without re-importing it and writes its file back from the database; the 25 MiB pre-push scan cap on written files still applies, and a core page or an external_untrusted writer still refuses.' },{ since: 'TBD', text: 'A write that stores a page in segments says in its receipt whether search sees it: `searchable: true` when it commits (every new page up to 4 MiB and every rewrite), or `searchable: "pending"` for a larger new page while its chunks are built after commit, with `searchable_retry_after_ms` and a `searchable_fix` that reads the receipt again (`get_write_request`) until it says `searchable: true`. A new page up to 4 MiB was previously searchable only once a post-commit build finished.' },{ since: 'TBD', text: '`gbrain projections drain` now builds pages stored in segments whose post-commit build never ran or died, skipping one another process is still building (claim renewed within 60 s), so a brain with no resident writer can make a large new page searchable. A pending receipt\'s `searchable_fix` names it as the fallback after the re-read wait, and doctor `text_projection_readiness` counts such pages (`segmented_pending`) and points to it.' },+ { since: 'TBD', text: 'Deleting and restoring a page over 24 MiB on a source backed by files is now lossless up to the page ceiling (`pages.max_bytes`). `restore_page` and `gbrain restore` write the file back byte for byte by streaming it from the stored segments into its staging file, including a file over the 25 MiB pre-push scan cap (the restore used to refuse with `request_too_large`, so the file a soft delete had removed could not be put back on disk). A delete or restore that replaces or removes a file over 24 MiB keeps the prior file as a staged copy beside it (a hidden `.<sha256>.tmp.before-<uuid>` file) until the write commits, named in its recovery record by path and SHA-256 instead of embedded in it: the record stays a few hundred bytes, the recovery reservation counts the file once (a 90 MiB delete used to need 283 MB against the 256 MiB `persistence.limits.worktree_recovery_bytes` budget and was refused), and a crash between removing the file and committing renames the copy back. A page whose file plus its staging does not fit that budget (a Postgres page near the 256 MiB ceiling) is still refused with `request_too_large` before anything is touched. `gbrain repair stuck-recovery` refuses such a recovery with `recovery_large_file_unsupported` (resolve it by hand; the resident writer finishes it).' },{ since: 'TBD', text: 'Chunks of a page stored in segments keep a Markdown heading with the text after it, so a section appended after a full last chunk re-embeds only its own chunk (was two). Inline pages chunk as before.' },];diff --git a/src/core/error-catalogue.ts b/src/core/error-catalogue.tsindex 3e6bf51c9a..e35eb3b4bf 100644--- a/src/core/error-catalogue.ts+++ b/src/core/error-catalogue.ts@@ -47,6 +47,8 @@ export const ERROR_CATALOGUE = {repair_kind_unavailable: { code: 'unavailable', docs: 'docs/guides/repair.md#explicit-only-repair-kinds' },// #6650: gbrain repair stuck-recovery resolves page recovery records only; a shared-skill bundle record is refused.recovery_bundle_unsupported: { code: 'recovery_bundle_unsupported', docs: 'docs/guides/repair.md#recovery-bundle-unsupported' },+ // Wave B: a page recovery whose prior file is over the single-string ceiling (staged as a copy) is refused: its preview diff would read both files whole.+ recovery_large_file_unsupported: { code: 'recovery_large_file_unsupported', docs: 'docs/guides/repair.md#recovery-large-file-unsupported' },// #6650: a (request state, --keep) pair stuck-recovery cannot make safe: a terminal request, or a choice the record cannot support.recovery_choice_refused: { code: 'recovery_choice_refused', docs: 'docs/guides/repair.md#recovery-choice-refused' },// #6650: a withdrawal-mirror effect recovery only finishes forward, so stuck-recovery lists it as refused.diff --git a/src/core/page-body/body-digests.ts b/src/core/page-body/body-digests.tsindex c76e0c2a16..fa5c30a941 100644--- a/src/core/page-body/body-digests.ts+++ b/src/core/page-body/body-digests.ts@@ -30,6 +30,9 @@ 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>;+/** File bytes a digest reads views of: a Buffer, or a file read on demand (persistence/large-file.ts `FileBytes`). */+export type ByteSource = Pick<Uint8Array, 'length' | 'subarray'>;+/** 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 }@@ -44,7 +47,7 @@ function count(piece: Uint8Array, field: 'fileBytes' | 'segmentBytes'): Uint8Arr}/** Bytes `[start, end)` of the virtual stream, as views (no copies). */-function* virtualSlice(bytes: Uint8Array, reading: FileReading, start: number, end: number): Iterable<Uint8Array> {+function* virtualSlice(bytes: ByteSource, 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) {@@ -53,7 +56,7 @@ function* virtualSlice(bytes: Uint8Array, reading: FileReading, start: number, e}/** 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 {+export function fileBodyDigests(bytes: ByteSource, 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();diff --git a/src/core/persistence/bundle-files.ts b/src/core/persistence/bundle-files.tsindex 81166c4795..cfc226dc07 100644--- a/src/core/persistence/bundle-files.ts+++ b/src/core/persistence/bundle-files.ts@@ -8,11 +8,13 @@ import { sha256 } from './digest.ts';import type { BundleRecoveryRecord, FileRecoveryRecord, WriteRequest } from './model.ts';import type { WorktreeBinding } from './ownership.ts';import { recoveryStagingFile } from './staging.ts';+import { isStreamedContent, type StreamedFileContent } from './large-file.ts';export interface MutationFile {path: string;root: string;- content: string | Uint8Array | null;+ /** A `StreamedFileContent` (large-file.ts) is produced into its staging file, never held whole; page files only. */+ content: string | Uint8Array | StreamedFileContent | null;expectedBeforeHash?: string | null;}export const BUNDLE_FILE_LIMITS = Object.freeze({ files: 128, fileBytes: 1024 * 1024, totalBytes: 8 * 1024 * 1024, depth: 16 });@@ -83,7 +85,7 @@ export function prepareBundleRecovery(files: MutationFile[], binding: WorktreeBilet afterBytes = 0;const records: FileRecoveryRecord[] = [];for (const file of files) {- if (file.root !== root || file.expectedBeforeHash === undefined) throw unsafe();+ if (file.root !== root || file.expectedBeforeHash === undefined || isStreamedContent(file.content)) throw unsafe();const normalized = file.path.normalize('NFC').toLowerCase();if (seen.has(normalized)) throw unsafe();for (const path of seen) if (path.startsWith(`${normalized}${sep}`) || normalized.startsWith(`${path}${sep}`)) throw unsafe();@@ -163,7 +165,7 @@ export function stageBundleFile(file: MutationFile, record: FileRecoveryRecord):parent = next;}const stage = record.staging?.publication;- if (!stage) throw unsafe();+ if (!stage || isStreamedContent(file.content)) throw unsafe();const content = typeof file.content === 'string' ? Buffer.from(file.content) : file.content;if (content.byteLength !== stage.bytes || sha256(content) !== stage.hash) throw unsafe();const fd = openSync(stage.path, 'wx', record.mode ?? 0o644);diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.tsindex 82763bc51b..87fddbd4f6 100644--- a/src/core/persistence/coordinator.ts+++ b/src/core/persistence/coordinator.ts@@ -1,4 +1,4 @@-import { existsSync, mkdirSync, readFileSync, statSync, unlinkSync } from 'node:fs';+import { closeSync, existsSync, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, statSync, unlinkSync } from 'node:fs';import { dirname } from 'node:path';import type { BrainEngine } from '../engine.ts';import type { PageSnapshot } from '../page-state/types.ts';@@ -6,7 +6,7 @@ import { OperationError, opError } from '../ops/contract.ts';import { readFix } from '../ops/op-fix.ts';import type { Action } from '../agent-output.ts';import { pageIdentityError } from './page-identity.ts';-import { atomicWriteFileSync, mkdirPrivate } from '../atomic-write.ts';+import { atomicStagingPath, atomicWriteFileSync, mkdirPrivate, validateAtomicStagingPath } from '../atomic-write.ts';import { flushDirectory } from '../fs-durable.ts';import { isWriteTargetContained } from '../path-confine.ts';import { sha256 } from './digest.ts';@@ -30,7 +30,9 @@ import type { GitCommitNote } from './effect-model.ts';import { authorizePageVisibility } from './page-visibility.ts';import { withNoRepoWriteThroughWarning } from '../write-through.ts';import { assertUnboundPublication, classifyUnboundPage, unboundWriteWarning } from './unbound-source.ts';-import { assertRecoveryStagingAbsent, cleanupRecoveryStaging, recoveryStagingFile, upgradeRecoveryStaging } from './staging.ts';+import { assertRecoveryStagingAbsent, cleanupRecoveryStaging, recoveryStagingFile, restoreBeforeStage, upgradeRecoveryStaging, type RecoveryStagingFile } from './staging.ts';+import { assertManagedFilesystemWrite } from './filesystem-guard.ts';+import { beforeStagePath, contentBytes, contentHash, hashDescriptor, hashFile, isStreamedContent, LARGE_FILE_MIN_BYTES, stageBeforeCopy, stageStreamedContent, type StreamedFileContent } from './large-file.ts';import { bindPublicationTimeouts, publicationTransaction } from './publication-deadline.ts';import { assertMutationProtocol, assertSharedSkillPersistence, declareDurablePersistence, PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';import { assertBundleRecoveryBinding, bundleFileHash, prepareBundleRecovery, publishStagedBundleFile, stageBundleFile, type MutationFile } from './bundle-files.ts';@@ -96,7 +98,8 @@ export interface PublicationHooks {fileBoundary?(name: 'before_file' | 'staging_flushed' | 'file_replaced' | 'directory_flushed' | 'after_file'| 'before_restore' | 'restoration_staging_flushed' | 'restoration_file_replaced' | 'restoration_directory_flushed' | 'after_restore', request: WriteRequest, index: number): void;}-function fileHash(path: string): string | null { return existsSync(path) ? sha256(readFileSync(path)) : null; }+/** SHA-256 of the file at `path` read in pieces (large-file.ts), null when absent. */+const fileHash = hashFile;const ownerStatusFix = (sourceId?: string): Action => readFix(sourceId? `Shows source ${sourceId}'s canonical owner with its pending, failed and recovering write requests, read-only.`: 'Shows every source\'s canonical owner with its pending, failed and recovering write requests, read-only.',@@ -116,7 +119,8 @@ function unexpectedRecoveryBytes(message: string, row: WriteRequest, when: strin`A canonical file of request ${row.request_id} in source ${row.source_id} ${when} matches neither its prior nor its published bytes, so recovery left it untouched and the worktree stays blocked. Inspect the owner and ask the user which version to keep; do not delete the file to unblock it.`,{ fix: ownerStatusFix(row.source_id) });}-function publishFile(file: PageMutationFile, stagingPath?: string, afterStagingFlush?: () => void, mode?: number | null): void {+/** Creates the file's parent directories, confined to its source root. */+function prepareParent(file: Pick<PageMutationFile, 'path' | 'root' | 'publishMode'>): void {if (!isWriteTargetContained(file.path, file.root)) throw opError('storage_error', 'Canonical file target escapes its source root.',`The file path resolves outside its source's canonical root (a symlinked directory or a moved checkout), so the file was not written. ${confinementCheck}`,{ fix: ownerStatusFix() });@@ -125,12 +129,47 @@ function publishFile(file: PageMutationFile, stagingPath?: string, afterStagingFif (!isWriteTargetContained(file.path, file.root)) throw opError('storage_error', 'Canonical parent path changed during publication.',`A directory on the file's path was replaced (for example by a symlink) while gbrain created it, so the file was not written. ${confinementCheck}`,{ fix: ownerStatusFix() });+}+function publishFile(file: PageMutationFile, stagingPath?: string, afterStagingFlush?: () => void, mode?: number | null): void {+ prepareParent(file);const openMode = mode ?? file.publishMode;if (file.content === null) {try { unlinkSync(file.path); } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }- } else atomicWriteFileSync(file.path, file.content, { durable: true, stagingPath, ...(openMode === undefined ? {} : { mode: openMode }), afterStagingFlush });+ } else if (isStreamedContent(file.content)) publishStagedContent(file.path, file.content, stagingPath, afterStagingFlush);+ else atomicWriteFileSync(file.path, file.content, { durable: true, stagingPath, ...(openMode === undefined ? {} : { mode: openMode }), afterStagingFlush });flushDirectory(dirname(file.path));}+/**+ * The rename half of a streamed content's publication: `stageLargeFiles` wrote and verified its staging file before+ * the publication transaction; here it must still be that regular file of the measured length.+ */+function publishStagedContent(path: string, content: StreamedFileContent, stagingPath: string | undefined, afterStagingFlush?: () => void): void {+ assertManagedFilesystemWrite(path);+ if (!stagingPath) throw opError('storage_error', 'A streamed canonical file has no reserved staging file.',+ 'The publication recorded no staging file for its streamed content, so nothing was written. Inspect the owner and report it to the user; do not resubmit it unchanged.', { fix: ownerStatusFix() });+ validateAtomicStagingPath(path, stagingPath);+ const staged = lstatSync(stagingPath);+ if (!staged.isFile() || staged.nlink !== 1 || staged.size !== content.bytes) throw opError('unexpected_staging_bytes', 'The staged canonical file changed before publication.',+ 'A recovery staging file changed outside gbrain. Inspect the pending recovery in writer status and tell the user; never delete or edit staging files by hand.', { fix: ownerStatusFix() });+ afterStagingFlush?.();+ renameSync(stagingPath, path);+}+/**+ * A before stage and streamed content (large-file.ts): once the recovery record naming the stages is durable and+ * before the publication transaction, the prior file is copied to its before stage and a streamed content is written+ * into its publication stage. A prior file that changed since its digest was recorded refuses as a local edit.+ */+async function stageLargeFiles(engine: BrainEngine, row: WriteRequest, file: PageMutationFile, record: FileRecoveryRecord): Promise<void> {+ const before = record.staging?.before, publication = record.staging?.publication;+ if (!before && !isStreamedContent(file.content)) return;+ await withFilesystemPublication([file.root], async () => {+ if (before && !stageBeforeCopy(file.path, before, record.mode)) throw localEditRefusal('The canonical file changed after preparation.', row, false, 'while its prior bytes were being staged');+ if (isStreamedContent(file.content)) {+ prepareParent(file);+ await stageStreamedContent(engine, file.path, file.content, publication!, record.mode);+ }+ });+}// Effect recovery uses the same confined durable publication primitive, under// its own recovery record and native root capability.export { fileHash as persistenceFileHash, publishFile as publishPersistenceFile };@@ -252,23 +291,51 @@ export function decoratePublicationOutcome(row: WriteRequest, prepared: Prepared* while holding the worktree's native lock, before any file is touched.*/export function pageRecoveryRecord(row: WriteRequest, file: PageMutationFile, binding: WorktreeBinding): { record: FileRecoveryRecord; bytes: number } {+ const large = largeRecoveryRecord(row, file, binding);+ if (large) return large;const before = existsSync(file.path) ? readFileSync(file.path) : null;const record: FileRecoveryRecord = {version: 1, path: file.path, root: file.root,before: before?.toString('base64') ?? null, beforeHash: before ? sha256(before) : null,- afterHash: file.content === null ? null : sha256(file.content),+ afterHash: file.content === null ? null : contentHash(file.content),mode: before ? statSync(file.path).mode & 0o7777 : null,ownerEpoch: String(binding.owner_epoch), attempt: row.execution_token!,staging: {- ...(file.content === null ? {} : { publication: recoveryStagingFile(file.path, file.content) }),+ ...(file.content === null ? {} : { publication: publicationStage(file.path, file.content) }),...(before === null ? {} : { restoration: recoveryStagingFile(file.path, before) }),},};- const nextBytes = file.content === null ? 0 : typeof file.content === 'string' ? Buffer.byteLength(file.content) : file.content.byteLength;+ const nextBytes = file.content === null ? 0 : contentBytes(file.content);const beforeBytes = before?.byteLength ?? 0;return { record, bytes: Math.max(beforeBytes * 3 + nextBytes * 2, Buffer.byteLength(JSON.stringify(record)) + beforeBytes + nextBytes) + 4096 };}+function publicationStage(path: string, content: string | Uint8Array | StreamedFileContent): RecoveryStagingFile {+ return isStreamedContent(content) ? { path: atomicStagingPath(path), hash: content.hash, bytes: content.bytes } : recoveryStagingFile(path, content);+}+/**+ * A prior file over the single-string ceiling is hashed in pieces and named as the before stage (path, SHA-256,+ * length) its copy is written to, never embedded (model.ts). The reservation counts the copy and the publication stage+ * on disk plus the record. Null for a smaller or absent prior file (its bytes are embedded).+ */+function largeRecoveryRecord(row: WriteRequest, file: PageMutationFile, binding: WorktreeBinding): { record: FileRecoveryRecord; bytes: number } | null {+ if (!existsSync(file.path) || statSync(file.path).size <= LARGE_FILE_MIN_BYTES) return null;+ const fd = openSync(file.path, 'r');+ let prior: { hash: string; bytes: number; mode: number };+ try { prior = { ...hashDescriptor(fd), mode: fstatSync(fd).mode & 0o7777 }; } finally { closeSync(fd); }+ const record: FileRecoveryRecord = {+ version: 1, path: file.path, root: file.root, before: null, beforeHash: prior.hash,+ afterHash: file.content === null ? null : contentHash(file.content), mode: prior.mode,+ ownerEpoch: String(binding.owner_epoch), attempt: row.execution_token!,+ staging: {+ ...(file.content === null ? {} : { publication: publicationStage(file.path, file.content) }),+ before: { path: beforeStagePath(file.path), hash: prior.hash, bytes: prior.bytes },+ },+ };+ const nextBytes = file.content === null ? 0 : contentBytes(file.content);+ return { record, bytes: Buffer.byteLength(JSON.stringify(record)) + prior.bytes + nextBytes + 4096 };+}+export async function publishMutation(engine: BrainEngine, row: WriteRequest, prepared: PreparedMutation,hostId = localHostId(), callerHooks: PublicationHooks = {}): Promise<WriteRequest> {const hooks = withFaultPoints(callerHooks);@@ -358,6 +425,7 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, pr}await prepareRecovery(engine, row, record, bytes);recovery = record;+ await stageLargeFiles(engine, row, prepared.file, record);await hooks.boundary?.('prepared', row);}const done = await publicationTransaction(engine, async tx => {@@ -434,7 +502,12 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, prreturn committed;});await hooks.boundary?.('after_commit', done);- if (recovery) await clearResolvedRecovery(engine, row.id, done);+ if (recovery) {+ // A version 3 record's prior-file copy is removed once the outcome is durable, before its record is cleared.+ const staged = recovery;+ if (staged.version === 1 && staged.staging?.before) await withFilesystemPublication([staged.root], async () => cleanupRecoveryStaging(staged));+ await clearResolvedRecovery(engine, row.id, done);+ }afterCommitDue = done.state === 'committed';return done;} catch (error) {@@ -510,7 +583,7 @@ export async function recoverPublication(engine: BrainEngine, id: string, hostIdif (actual !== record.beforeHash && actual !== record.afterHash) throw unexpectedRecoveryBytes('Canonical recovery bytes changed outside publication.', current, 'was edited outside gbrain and');}await withFilesystemPublication([...new Set(records.map(record => record.root))], async () => {- for (const record of records) cleanupRecoveryStaging(record);+ for (const record of records) cleanupRecoveryStaging(record, { keepBefore: !isTerminal(current) });});}catch (error) {@@ -529,7 +602,12 @@ export async function recoverPublication(engine: BrainEngine, id: string, hostIdhooks.fileBoundary?.('before_restore', current, index);const actual = current.recovery.version === 2 ? bundleFileHash(record) : fileHash(record.path);if (actual !== record.beforeHash && actual !== record.afterHash) throw unexpectedRecoveryBytes('Canonical recovery bytes changed during restoration.', current, 'changed while recovery was restoring it and');- if (actual === record.afterHash && actual !== record.beforeHash) {+ if (record.staging?.before) {+ await withFilesystemPublication([record.root], async () => {+ if (actual === record.afterHash && actual !== record.beforeHash) restoreBeforeStage(record, phase => hooks.fileBoundary?.(`restoration_${phase}`, current, index));+ else cleanupRecoveryStaging(record);+ });+ } else if (actual === record.afterHash && actual !== record.beforeHash) {await withFilesystemPublication([record.root], async () => {const file = { path: record.path, root: record.root, content: record.before === null ? null : Buffer.from(record.before, 'base64') };if (current.recovery!.version === 2) {diff --git a/src/core/persistence/effect-journal.ts b/src/core/persistence/effect-journal.tsindex a89c6c0c5d..a5f2fbe1ec 100644--- a/src/core/persistence/effect-journal.ts+++ b/src/core/persistence/effect-journal.ts@@ -5,7 +5,7 @@ import type { PageSnapshot } from '../page-state/types.ts';import { opError } from '../ops/contract.ts';import { readFix } from '../ops/op-fix.ts';import type { PreparedMutation } from './coordinator.ts';-import { sha256 } from './digest.ts';+import { contentHash } from './large-file.ts';import { PARK_AFTER_FAILURES, REMOTE_AUTO_LINKS_KEY, REMOTE_MENTION_OPERATIONS, type EffectKind, type PersistenceEffect, type EffectRequest } from './effect-model.ts';import type { SqlEngine, WriteRequest } from './model.ts';import { recordChronicleDecision } from '../chronicle/ledger.ts';@@ -42,7 +42,7 @@ export async function queuePublicationEffects(tx: BrainEngine, row: EffectRequesrow.principal_kind === 'local_cli' ? { fix: readFix(`Reads request ${row.id}'s durable receipt, read-only.`, { argv: ['gbrain', 'write-request', '--', row.id] }) } : {});const commit = prepared.file.commit;queue('git', { relative_path: relative(binding.local_path, prepared.file.path).split(sep).join('/'),- expected_hash: prepared.file.content === null ? null : sha256(prepared.file.content),+ expected_hash: prepared.file.content === null ? null : contentHash(prepared.file.content),...(commit ? { commit_subject: commit.subject, commit_line: commit.line, ...(commit.trailer ? { commit_trailer: commit.trailer } : {}) } : {}) });if (outcome.persistence && typeof outcome.persistence === 'object') Object.assign(outcome.persistence, { git_state: 'queued' });}diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.tsindex de5a9a902f..92ab54dca2 100644--- a/src/core/persistence/group-publish.ts+++ b/src/core/persistence/group-publish.ts@@ -58,6 +58,7 @@ import { authorizePageVisibility } from './page-visibility.ts';import { withFilesystemPublication } from './filesystem-guard.ts';import { isWriteTargetContained } from '../path-confine.ts';import { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-guard.ts';+import { isStreamedContent } from './large-file.ts';import { decoratePublicationOutcome, finishPreparationStalled, finishUnpublishedFailure, pageRecoveryRecord, persistenceFileHash, preparationAbortReason, publicationPostimage, publishMutation,publishPersistenceFile, recoverPublication, type PreparedMutation } from './coordinator.ts';import { pipelined } from '../page-state/transactions.ts';@@ -90,6 +91,8 @@ export function singleWrite(row: Pick<WriteRequest, 'operation' | 'intent'>): boexport function groupable(row: WriteRequest, prepared: PreparedMutation): boolean {if ((row.target_kind ?? 'page') !== 'page' || prepared.target === 'skill_bundle' || prepared.sourceExclusive || prepared.exclusiveSources?.length) return false;if (syncMember(row)) return !prepared.file && typeof prepared.validate === 'function';+ // A streamed file (large-file.ts) is staged before its publication transaction, which only publishMutation does.+ if (isStreamedContent(prepared.file?.content)) return false;return independentGroup(publicationGroupKey(row)) || singleWrite(row);}@@ -255,6 +258,8 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], prif (!file || prepared[i]!.noop) continue;if (!isWriteTargetContained(file.path, file.root)) return none;const member = { row: rows[i]!, ...pageRecoveryRecord(rows[i]!, file, binding) };+ // A large prior file is copied to its before stage ahead of the transaction: the single path does that.+ if (member.record.staging?.before) return none;// A file that moved since preparation takes the single path, which decides between reprepare and refusal.if (file.expectedBeforeHash !== undefined && member.record.beforeHash !== file.expectedBeforeHash) return none;files.set(i, member);diff --git a/src/core/persistence/large-file.ts b/src/core/persistence/large-file.tsnew file mode 100644index 0000000000..8ec8777662--- /dev/null+++ b/src/core/persistence/large-file.ts@@ -0,0 +1,197 @@+/**+ * Wave B: canonical files over the single-string ceiling on the publication path (page-prepare.ts,+ * coordinator.ts, staging.ts). A file over `LARGE_FILE_MIN_BYTES` is never held as one string or Buffer: its+ * digest and the drift check read it in pieces of at most one segment, restore_page streams its new bytes from the+ * page's segments straight into the reserved staging file (`StreamedFileContent`), and a publication that replaces+ * or removes one keeps the prior file as a staged copy referenced by path and SHA-256 in its recovery record+ * (`stageBeforeCopy`, model.ts) instead of embedding its bytes.+ */+import { createHash } from 'node:crypto';+import { closeSync, constants, copyFileSync, existsSync, fchmodSync, fstatSync, fsyncSync, openSync, readSync, unlinkSync, writeSync } from 'node:fs';+import { dirname } from 'node:path';+import type { BrainEngine } from '../engine.ts';+import { PAGE_MAX_BYTES } from '../page-size-policy.ts';+import { SEGMENT_MAX_BYTES } from '../page-body/limits.ts';+import { atomicStagingPath, validateAtomicStagingPath } from '../atomic-write.ts';+import { flushDirectory } from '../fs-durable.ts';+import { OperationError, opError } from '../ops/contract.ts';+import { assertManagedFilesystemWrite } from './filesystem-guard.ts';+import { sha256 } from './digest.ts';+import type { RecoveryStagingFile } from './staging.ts';++/** A canonical file of more bytes than this is read, hashed, copied and written in pieces. */+export const LARGE_FILE_MIN_BYTES = PAGE_MAX_BYTES;+const PIECE_BYTES = SEGMENT_MAX_BYTES;++/**+ * @internal Work the large-file path does, for the memory-bound tests: bytes read from canonical or staged files+ * (`bytesRead`), streamed into a staging file (`bytesWritten`) or copied by the kernel into a before stage+ * (`bytesCopied`), and the largest single piece held (`largestPiece`, at most a segment). Counts, not time.+ */+export const largeFileWork = { bytesRead: 0, bytesWritten: 0, bytesCopied: 0, largestPiece: 0 };++function counted(bytes: number, field: 'bytesRead' | 'bytesWritten'): void {+ largeFileWork[field] += bytes;+ if (bytes > largeFileWork.largestPiece) largeFileWork.largestPiece = bytes;+}++/** SHA-256 (hex) and length of an open file's bytes, read in pieces from offset 0. */+export function hashDescriptor(fd: number): { hash: string; bytes: number } {+ const hash = createHash('sha256');+ const buffer = Buffer.allocUnsafe(PIECE_BYTES);+ let bytes = 0;+ for (let n: number; (n = readSync(fd, buffer, 0, PIECE_BYTES, bytes)) > 0; bytes += n) {+ counted(n, 'bytesRead');+ hash.update(buffer.subarray(0, n));+ }+ return { hash: hash.digest('hex'), bytes };+}++/** The persistence file hash: SHA-256 of the file's bytes read in pieces, null when no file exists there. */+export function hashFile(path: string): string | null {+ if (!existsSync(path)) return null;+ const fd = openSync(path, 'r');+ try { return hashDescriptor(fd).hash; } finally { closeSync(fd); }+}++/**+ * A canonical file's bytes read on demand through one descriptor: `subarray` reads that range (callers ask at most+ * a segment or the frontmatter head), so it stands in for the Buffer a streamed comparison takes views of+ * (body-digests.ts). `close` refuses (`source_changed`) when the file changed while it was read, so a comparison+ * never judges a torn reading.+ */+export class FileBytes {+ private hashed: string | null = null;+ private constructor(private readonly fd: number, readonly length: number, private readonly stamp: string) {}+ static open(path: string): FileBytes {+ const fd = openSync(path, 'r');+ const stat = fstatSync(fd);+ return new FileBytes(fd, stat.size, `${stat.ino}:${stat.size}:${stat.mtimeMs}`);+ }+ subarray(start = 0, end = this.length): Uint8Array {+ const from = Math.max(0, Math.min(start, this.length)), to = Math.max(from, Math.min(end, this.length));+ const buffer = Buffer.allocUnsafe(to - from);+ for (let at = 0, n: number; at < buffer.length; at += n) {+ n = readSync(this.fd, buffer, at, buffer.length - at, from + at);+ if (n <= 0) throw changedWhileRead();+ }+ counted(buffer.length, 'bytesRead');+ return buffer;+ }+ hash(): string { return this.hashed ??= hashDescriptor(this.fd).hash; }+ close(): void {+ try {+ const stat = fstatSync(this.fd);+ if (`${stat.ino}:${stat.size}:${stat.mtimeMs}` !== this.stamp) throw changedWhileRead();+ } finally { closeSync(this.fd); }+ }+}+function changedWhileRead(): OperationError {+ return new OperationError('source_changed', 'The canonical file changed while it was being read.', 'Retry the write with a new request_id; it reads the file again.');+}++/**+ * Bytes of a canonical file produced in pieces (restore_page of a page over the single-string ceiling: export's+ * serializer over the segments), measured once in preparation (length and SHA-256) and produced again into the+ * publication's staging file. Never concatenated.+ */+export class StreamedFileContent {+ private constructor(readonly bytes: number, readonly hash: string, private readonly produce: (engine: BrainEngine) => AsyncIterable<string | Uint8Array>) {}+ static async measure(engine: BrainEngine, produce: (engine: BrainEngine) => AsyncIterable<string | Uint8Array>): Promise<StreamedFileContent> {+ const hash = createHash('sha256');+ let bytes = 0;+ for await (const piece of pieces(produce(engine))) { counted(piece.length, 'bytesRead'); hash.update(piece); bytes += piece.length; }+ return new StreamedFileContent(bytes, hash.digest('hex'), produce);+ }+ pieces(engine: BrainEngine): AsyncIterable<Uint8Array> { return pieces(this.produce(engine)); }+}+async function* pieces(source: AsyncIterable<string | Uint8Array>): AsyncIterable<Uint8Array> {+ for await (const piece of source) yield typeof piece === 'string' ? Buffer.from(piece, 'utf8') : piece;+}+export function isStreamedContent(content: unknown): content is StreamedFileContent { return content instanceof StreamedFileContent; }+/** UTF-8 byte length of a file target's content. */+export function contentBytes(content: string | Uint8Array | StreamedFileContent): number {+ return isStreamedContent(content) ? content.bytes : typeof content === 'string' ? Buffer.byteLength(content) : content.byteLength;+}+export function contentHash(content: string | Uint8Array | StreamedFileContent): string {+ return isStreamedContent(content) ? content.hash : sha256(content);+}++const BEFORE_STAGE = '.tmp.before-';+/**+ * The before stage's name: an atomic staging sibling (`.<sha256(target)>.tmp.`) whose UUID is prefixed `before-`.+ * Older binaries accept only `.tmp.<uuid>` stage names, so a record naming one blocks them instead of being misread.+ */+export function beforeStagePath(path: string): string { return atomicStagingPath(path).replace(/\.tmp\.(?=[0-9a-f-]{36}$)/, BEFORE_STAGE); }+export function validateBeforeStagePath(path: string, stagePath: string): void {+ const at = stagePath.lastIndexOf(BEFORE_STAGE);+ if (at < 0) throw new Error('atomic-write: invalid journaled staging path');+ validateAtomicStagingPath(path, `${stagePath.slice(0, at)}.tmp.${stagePath.slice(at + BEFORE_STAGE.length)}`);+}++function writeAll(fd: number, bytes: Uint8Array): void {+ for (let at = 0, n: number; at < bytes.length; at += n) {+ n = writeSync(fd, bytes, at, bytes.length - at);+ if (n <= 0) throw opError('storage_error', 'The staging file stopped writing before it was complete.',+ 'Check free space on the volume holding the source checkout, then inspect the request\'s receipt before submitting the write again.');+ }+}+function removeOwnStage(path: string): void {+ try { unlinkSync(path); } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }+}++/**+ * Writes `content` into its reserved staging file (created exclusively with `mode`, else 0644 under the umask), one+ * piece at a time, fsynced. Bytes that are not the measured ones (the page changed since preparation) remove the+ * stage and refuse as `revision_conflict`, so the request is prepared again.+ */+export async function stageStreamedContent(engine: BrainEngine, path: string, content: StreamedFileContent, stage: RecoveryStagingFile, mode: number | null): Promise<void> {+ assertManagedFilesystemWrite(path);+ validateAtomicStagingPath(path, stage.path);+ const fd = openSync(stage.path, 'wx', mode ?? 0o644);+ let staged = false;+ try {+ if (mode !== null) fchmodSync(fd, mode);+ const hash = createHash('sha256');+ let bytes = 0;+ for await (const piece of content.pieces(engine)) {+ writeAll(fd, piece);+ counted(piece.length, 'bytesWritten');+ hash.update(piece);+ bytes += piece.length;+ }+ if (bytes !== stage.bytes || hash.digest('hex') !== stage.hash) throw new OperationError('revision_conflict', 'The page changed during preparation.', 'Read its current revision and submit the updated intent with a new request_id.');+ fsyncSync(fd);+ staged = true;+ } finally {+ closeSync(fd);+ if (!staged) removeOwnStage(stage.path);+ }+ flushDirectory(dirname(stage.path));+}++/**+ * Copies the canonical file at `path` to its reserved before stage (exclusive; the kernel copies, no user-space+ * buffer), sets its recorded mode, fsyncs it and checks it holds the recorded bytes. False (the copy removed) when+ * the file changed since its digest was recorded.+ */+export function stageBeforeCopy(path: string, stage: RecoveryStagingFile, mode: number | null): boolean {+ assertManagedFilesystemWrite(path);+ validateBeforeStagePath(path, stage.path);+ copyFileSync(path, stage.path, constants.COPYFILE_EXCL | constants.COPYFILE_FICLONE);+ let staged = false;+ const fd = openSync(stage.path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));+ try {+ if (mode !== null) fchmodSync(fd, mode);+ const copy = hashDescriptor(fd);+ largeFileWork.bytesCopied += copy.bytes;+ if (copy.bytes !== stage.bytes || copy.hash !== stage.hash) return false;+ fsyncSync(fd);+ staged = true;+ } finally {+ closeSync(fd);+ if (!staged) removeOwnStage(stage.path);+ }+ flushDirectory(dirname(stage.path));+ return true;+}diff --git a/src/core/persistence/model.ts b/src/core/persistence/model.tsindex cc229fa2fa..405fdfc00b 100644--- a/src/core/persistence/model.ts+++ b/src/core/persistence/model.ts@@ -24,6 +24,13 @@ export interface WriteAuthority {/** Actual holders touched by a published take mutation; retained after intent compaction. */takeHoldersUsed?: string[];}+/**+ * One file's publication recovery. The prior bytes are embedded (`before`, base64), except for a prior file over the+ * single-string ceiling (large-file.ts): `before` is null and the bytes are the staged copy `staging.before` (path,+ * SHA-256 = `beforeHash`, length), which recovery renames back. Its `.tmp.before-<uuid>` name is not a stage name+ * binaries that predate it accept, so they block on it (`unexpected_staging_bytes`) instead of reading `before: null`+ * as an absent file.+ */export interface FileRecoveryRecord {version: 1;path: string;diff --git a/src/core/persistence/noop-kernel.ts b/src/core/persistence/noop-kernel.tsindex a23019ab9f..8cb6f00bf9 100644--- a/src/core/persistence/noop-kernel.ts+++ b/src/core/persistence/noop-kernel.ts@@ -33,7 +33,7 @@ import { persistenceFileHash } from './coordinator.ts';import type { WriteRequest } from './model.ts';import type { PageSnapshot } from '../page-state/types.ts';import { belowSafeChunkFence, chunkGenerationFilter } from '../search/safe-chunks.ts';-import { sha256 } from './digest.ts';+import { contentHash } from './large-file.ts';export interface NoopKernelResult {contentUnchanged: boolean;@@ -91,7 +91,7 @@ export async function inspectUnchanged(engine: Pick<BrainEngine, 'executeRaw'>,if (!input.databaseOnly) {const file = prepared.file;const onDisk = file && file.content !== null ? persistenceFileHash(file.path) : null;- if (!file || file.content === null || onDisk !== sha256(file.content)) {+ if (!file || file.content === null || onDisk !== contentHash(file.content)) {if (onDisk === null || !input.waive?.includes('canonical_file_differs')) return result('canonical_file_differs');waived.push('canonical_file_differs');}diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.tsindex 405cc6b471..cf8dabb8f0 100644--- a/src/core/persistence/page-prepare.ts+++ b/src/core/persistence/page-prepare.ts@@ -3,7 +3,7 @@ import { sizeStateField } from '../page-embedding-budget.ts';import { enterClaimStep, type ClaimPhaseClock } from './claim-phase.ts';import { boundedReads } from './bounded-reads.ts';import { isQuarantined, quarantineOutcome } from '../quarantine.ts';-import { existsSync, readFileSync, realpathSync } from 'node:fs';+import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs';import { join, relative, sep } from 'node:path';import { matchesAnyGlob } from '../sync.ts';import { syncExcludePatterns } from './sync-discovery.ts';@@ -46,7 +46,7 @@ import { pipelined } from '../page-state/transactions.ts';import { overlayCanonicalBodies } from '../page-state/snapshot.ts';import { segmentedRevertRefusal } from '../page-state/versions.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 { fileBodyDigests, storedBodyDigests, type ByteSource, type FileReading, type RegionDigests } from '../page-body/body-digests.ts';import { ledgerApplies, type BodyLedger } from '../page-body/segment-ledger.ts';import { inferredHeadPrefix } from '../page-body/streamed-import.ts';import { FRONTMATTER_HEAD_MAX_BYTES } from '../page-body/limits.ts';@@ -81,6 +81,7 @@ import { isFenceEditWrite, pageGateTrust, pageWriteTrust, recordAgentPageLowerinimport { suppliedTrustMarkerView } from '../trust/channel.ts';import { gateField, gateInput } from '../trust/gate-outcomes.ts';import { PUSH_SCAN_MAX_FILE_BYTES } from '../page-size-policy.ts';+import { contentHash, FileBytes, isStreamedContent, LARGE_FILE_MIN_BYTES, StreamedFileContent } from './large-file.ts';const ownerStatusFix = (sourceId: string): Action => readFix(`Shows source ${sourceId}'s canonical owner with its pending, failed and recovering requests, read-only.`,@@ -211,7 +212,7 @@ function snapshotLedger(snapshot: PageSnapshot): BodyLedger {* 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,+async function segmentedFileMatches(engine: BrainEngine, slug: string, bytes: ByteSource, snapshot: PageSnapshot,sourcePath: () => Promise<string>, activePack?: ParseOpts['activePack']): Promise<boolean> {const ledger = snapshotLedger(snapshot);let stored: RegionDigests | undefined;@@ -228,19 +229,22 @@ async function segmentedFileMatches(engine: BrainEngine, slug: string, bytes: Buconst 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 bom = bytes.subarray(0, 3);+ const skip = bom[0] === 0xef && bom[1] === 0xbb && bom[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 | Uint8Array | null, hostId?: string, options: { allowMissing?: boolean; deleting?: boolean; capture?: { path: string; hash: string }; activePack?: ParseOpts['activePack']; remote?: boolean;+ content: string | Uint8Array | StreamedFileContent | 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. */sharedOrigin?: { onShared: (shared: SharedOrigin) => void } } = {}): Promise<PreparedMutation['file']> {if (!row.worktree_id) return undefined;- // A canonical file over the pre-push secret-scan cap would block every later push of the brain repo.- if (content !== null && Buffer.byteLength(content, 'utf-8') > PUSH_SCAN_MAX_FILE_BYTES) throw opError('request_too_large', 'The canonical file would exceed the pre-push secret-scan cap.',+ // A canonical file over the pre-push secret-scan cap would block every later push of the brain repo. A streamed file+ // (restore_page of a page over the single-string ceiling: the file a delete removed) is exempt: the push gate scans a+ // staged file over that cap in bounded windows (workspace-push.ts), and the database copy is the system of record.+ if (content !== null && !isStreamedContent(content) && Buffer.byteLength(content, 'utf-8') > PUSH_SCAN_MAX_FILE_BYTES) throw opError('request_too_large', 'The canonical file would exceed the pre-push secret-scan cap.',`Nothing was written. The rendered file of ${row.slug} is over ${PUSH_SCAN_MAX_FILE_BYTES} bytes, which the pre-push secret scan cannot scan, so it would block every push of source ${row.source_id}. Keep the page under the 24 MiB page ceiling (docs/guides/memory-boundaries.md#large-pages).`);// #6212: a legacy slug (admitted only to delete or restore its existing row) never owns a file: its recorded// source_uri or source_path may name the file of another page, such as the one sync now slugs it to.@@ -274,7 +278,19 @@ export async function prepareFileTarget(engine: BrainEngine, row: Pick<WriteRequconst rel = relative(root, path).split(sep).join('/');if (matchesAnyGlob(rel, options.excludeTombstone.patterns)) { options.excludeTombstone.onExcluded(rel); return undefined; }}- const before = existsSync(path) ? readFileSync(path) : null;+ // A prior file over the single-string ceiling is read on demand in pieces (large-file.ts), never whole.+ const before: Buffer | FileBytes | null = !existsSync(path) ? null : statSync(path).size > LARGE_FILE_MIN_BYTES ? FileBytes.open(path) : readFileSync(path);+ try {+ return await compareFileTarget(engine, row, snapshot, content, options, { root, path, mode, capturedPath, before });+ } finally { if (before instanceof FileBytes) before.close(); }+}++/** prepareFileTarget's comparison of the file at `path` (`before`, its bytes or a piecewise reading) with the snapshot. */+async function compareFileTarget(engine: BrainEngine, row: Pick<WriteRequest, 'source_id' | 'worktree_id' | 'slug'>, snapshot: PageSnapshot | null,+ content: string | Uint8Array | StreamedFileContent | null, options: Parameters<typeof prepareFileTarget>[5] & object,+ target: { root: string; path: string; mode: Awaited<ReturnType<typeof scannerSlugRootMode>> | undefined; capturedPath: string | null | undefined; before: Buffer | FileBytes | null }): Promise<PreparedMutation['file']> {+ const { root, path, mode, capturedPath, before } = target;+ const beforeHash = () => before instanceof FileBytes ? before.hash() : sha256(before!);if (options.deleting === true && options.sharedOrigin && snapshot && before) {const target: FileClaimTarget = { sourceId: row.source_id, slug: row.slug, pageId: snapshot.page.id, root, path, canonicalPath: realpathSync(path),mode: mode ?? await scannerSlugRootMode(engine, row.source_id, root), recordedUri: capturedPath ? snapshot.page.source_uri ?? null : null };@@ -299,8 +315,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));+ // An inline page's file over the push-scan cap cannot hold its body (at most 24 MiB): drift, never read whole.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);+ : before.length <= PUSH_SCAN_MAX_FILE_BYTES && await fileMatchesSnapshot(engine, row.slug, (before instanceof FileBytes ? Buffer.from(before.subarray()) : 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;@@ -313,12 +330,12 @@ export async function prepareFileTarget(engine: BrainEngine, row: Pick<WriteRequ{ detail: 'file_database_drift', fix: readFix(`Previews how page ${row.slug}'s canonical file and database copy reconcile; a preview never changes canonical content.`,{ argv: ['gbrain', 'sources', 'reconcile', row.source_id, row.slug, '--brain', 'host', '--preview', ...adopt] }) });}- } else if (before && !snapshot && content !== null && sha256(before) !== sha256(content)- && !(options.capture && sha256(before) === options.capture.hash)) {+ } else if (before && !snapshot && content !== null && beforeHash() !== contentHash(content)+ && !(options.capture && beforeHash() === options.capture.hash)) {throw await heldFileRefusal(engine, row, root, path, 'occupied', options.remote === true)?? new OperationError('source_changed', 'An unindexed file already occupies the canonical page path.', 'Import the file before replacing it.');}- return { path, root, content, expectedBeforeHash: before ? sha256(before) : null };+ return { path, root, content, expectedBeforeHash: before ? beforeHash() : null };}/**@@ -502,12 +519,14 @@ async function prepareUnreadRestore(engine: BrainEngine, row: WriteRequest, snapafterCommit: async target => { if (!complete) await buildSegmentedProjection(target, { sourceId: row.source_id, slug: row.slug }).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> {+/**+ * serializePageToMarkdown's bytes for a page whose body was not read back, streamed from its segments by export's+ * serializer: measured here, produced again into the publication's staging file (large-file.ts), never concatenated.+ */+async function unreadPageFile(engine: BrainEngine, snapshot: PageSnapshot): Promise<StreamedFileContent> {const head = serializePageToMarkdown({ ...withoutBody(snapshot.page), compiled_truth: '', timeline: '' }, snapshot.tags).slice(0, -1);- const parts: Uint8Array[] = [];- for await (const piece of segmentedExportMarkdown(engine, snapshot.page, snapshotLedger(snapshot), head)) parts.push(typeof piece === 'string' ? Buffer.from(piece, 'utf8') : piece);- return Buffer.concat(parts);+ const ledger = snapshotLedger(snapshot);+ return StreamedFileContent.measure(engine, exec => segmentedExportMarkdown(exec, snapshot.page, ledger, head));}/**diff --git a/src/core/persistence/recovery-resolve.ts b/src/core/persistence/recovery-resolve.tsindex 1e28feb2c0..48104921ec 100644--- a/src/core/persistence/recovery-resolve.ts+++ b/src/core/persistence/recovery-resolve.ts@@ -173,6 +173,8 @@ function writeArtifacts(dir: string, item: { files: RecoveryFileView[] }, recordasync function readItem(engine: BrainEngine, row: WriteRequest, binding: WorktreeBinding): Promise<{ item: StuckRecovery; records: FileRecoveryRecord[]; disks: Array<Buffer | null> }> {if (row.recovery?.version === 2) throw catalogueError('recovery_bundle_unsupported', `Request ${row.request_id} in source ${row.source_id} is a shared-skill bundle recovery, which gbrain repair stuck-recovery does not resolve.`,`Nothing was changed. Inspect it read-only with gbrain sources writer status --source ${row.source_id} --json and ask the user which version of each skill file to keep; resolve the bundle by hand, then let the resident writer finish its recovery.`);+ if (row.recovery?.version === 1 && row.recovery.staging?.before) throw catalogueError('recovery_large_file_unsupported', `Request ${row.request_id} in source ${row.source_id} holds a page recovery whose prior file is over the single-string ceiling, which gbrain repair stuck-recovery does not resolve.`,+ `Nothing was changed. Inspect it read-only with gbrain sources writer status --source ${row.source_id} --json and ask the user which version of the file to keep; its prior bytes are the staged copy the record names. Put the chosen bytes in place by hand, then let the resident writer finish its recovery.`);const records = recoveryFiles(row.recovery!);const [page] = await engine.executeRaw<{ revision: string | null }>('SELECT knowledge_revision::text AS revision FROM pages WHERE source_id=$1 AND slug=$2', [row.source_id, row.slug]);const disks: Array<Buffer | null> = [];diff --git a/src/core/persistence/staging.ts b/src/core/persistence/staging.tsindex 78f8fc3e67..f0b25387a0 100644--- a/src/core/persistence/staging.ts+++ b/src/core/persistence/staging.ts@@ -1,4 +1,4 @@-import { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync, unlinkSync } from 'node:fs';+import { closeSync, constants, fchmodSync, fstatSync, lstatSync, openSync, renameSync, unlinkSync } from 'node:fs';import { dirname } from 'node:path';import { atomicStagingPath, validateAtomicStagingPath } from '../atomic-write.ts';import { flushDirectory } from '../fs-durable.ts';@@ -7,10 +7,15 @@ import { opError, OperationError } from '../ops/contract.ts';import { sha256 } from './digest.ts';import type { BrainEngine } from '../engine.ts';import { readJournalLimits } from './limits.ts';+import { hashDescriptor, validateBeforeStagePath } from './large-file.ts';import { declarePersistenceProtocol } from './protocol.ts';export interface RecoveryStagingFile { path: string; hash: string; bytes: number }-export interface RecoveryStaging { publication?: RecoveryStagingFile; restoration?: RecoveryStagingFile }+/**+ * `before` (model.ts): the staged copy of a prior canonical file over the single-string ceiling,+ * which recovery renames back instead of decoding an embedded before-image; kept until recovery decides.+ */+export interface RecoveryStaging { publication?: RecoveryStagingFile; restoration?: RecoveryStagingFile; before?: RecoveryStagingFile }interface StagedRecovery { path: string; root: string; staging?: RecoveryStaging }interface StoredFileRecovery extends StagedRecovery { before?: string | null; after?: string | null }type StoredRecovery = StoredFileRecovery | { files: StoredFileRecovery[] };@@ -28,7 +33,7 @@ function stages(record: StagedRecovery): RecoveryStagingFile[] {const result = Object.values(record.staging ?? {}).filter((stage): stage is RecoveryStagingFile => !!stage);if (new Set(result.map(stage => stage.path)).size !== result.length) throw blocked();for (const stage of result) {- try { validateAtomicStagingPath(record.path, stage.path); } catch { throw blocked(); }+ try { if (stage === record.staging?.before) validateBeforeStagePath(record.path, stage.path); else validateAtomicStagingPath(record.path, stage.path); } catch { throw blocked(); }if (!isWriteTargetContained(stage.path, record.root) || !Number.isSafeInteger(stage.bytes) || stage.bytes < 0|| !/^[a-f0-9]{64}$/.test(stage.hash)) throw blocked();}@@ -53,26 +58,56 @@ function flushParent(path: string): void {}}-/** Called under the owner lock. Partial/unknown stages are preserved, never guessed. */-export function cleanupRecoveryStaging(record: StagedRecovery): void {+/**+ * Runs `settle` on a present stage leaf once it is proven the reserved file: a regular file with one link, its+ * recorded size and digest (read in pieces), unchanged while it was read. False when the leaf is absent.+ */+function withVerifiedStage(stage: RecoveryStagingFile, settle: (fd: number) => void): boolean {+ const leaf = statIfPresent(stage.path);+ if (!leaf) return false;+ if (!leaf.isFile() || leaf.nlink !== 1 || leaf.size !== stage.bytes) throw blocked();+ const fd = openSync(stage.path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));+ try {+ const opened = fstatSync(fd);+ if (opened.dev !== leaf.dev || opened.ino !== leaf.ino || opened.birthtimeMs !== leaf.birthtimeMs+ || opened.size !== stage.bytes || hashDescriptor(fd).hash !== stage.hash) throw blocked();+ const current = statIfPresent(stage.path);+ if (!current?.isFile() || current.dev !== opened.dev || current.ino !== opened.ino+ || current.birthtimeMs !== opened.birthtimeMs || current.size !== opened.size || current.mtimeMs !== opened.mtimeMs) throw blocked();+ settle(fd);+ } finally { closeSync(fd); }+ return true;+}++/**+ * Called under the owner lock. Partial/unknown stages are preserved, never guessed. `keepBefore`: a live request's+ * recovery keeps the prior file's copy until it has decided whether to rename it back (`restoreBeforeStage`).+ */+export function cleanupRecoveryStaging(record: StagedRecovery, opts: { keepBefore?: boolean } = {}): void {for (const stage of stages(record)) {- const leaf = statIfPresent(stage.path);- if (!leaf) { flushParent(stage.path); continue; }- if (!leaf.isFile() || leaf.nlink !== 1 || leaf.size !== stage.bytes) throw blocked();- const fd = openSync(stage.path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));- try {- const opened = fstatSync(fd);- if (opened.dev !== leaf.dev || opened.ino !== leaf.ino || opened.birthtimeMs !== leaf.birthtimeMs- || opened.size !== stage.bytes || sha256(readFileSync(fd)) !== stage.hash) throw blocked();- const current = statIfPresent(stage.path);- if (!current?.isFile() || current.dev !== opened.dev || current.ino !== opened.ino- || current.birthtimeMs !== opened.birthtimeMs || current.size !== opened.size || current.mtimeMs !== opened.mtimeMs) throw blocked();- unlinkSync(stage.path);- } finally { closeSync(fd); }+ if (opts.keepBefore && stage === record.staging?.before) continue;+ withVerifiedStage(stage, () => unlinkSync(stage.path));flushParent(stage.path);}}+/**+ * Recovery's restoration of a version 3 record: the verified copy of the prior file is renamed over the canonical+ * path with its recorded mode. A missing copy refuses (`unexpected_staging_bytes`): the bytes cannot be guessed.+ */+export function restoreBeforeStage(record: StagedRecovery & { mode: number | null }, boundary?: (phase: 'file_replaced' | 'directory_flushed') => void): void {+ const stage = record.staging?.before;+ if (!stage || !stages(record).includes(stage)) throw blocked();+ const restored = withVerifiedStage(stage, fd => {+ if (record.mode !== null) fchmodSync(fd, record.mode);+ renameSync(stage.path, record.path);+ });+ if (!restored) throw blocked();+ boundary?.('file_replaced');+ flushDirectory(dirname(record.path));+ boundary?.('directory_flushed');+}+/** The final accounting fence also protects direct terminal-cleanup callers. */export function assertRecoveryStagingAbsent(record: StagedRecovery): void {for (const stage of stages(record)) {diff --git a/test/fixtures/large-delete-crash-worker.ts b/test/fixtures/large-delete-crash-worker.tsnew file mode 100644index 0000000000..3850bb11a4--- /dev/null+++ b/test/fixtures/large-delete-crash-worker.ts@@ -0,0 +1,89 @@+/**+ * Child process for test/large-pages/segmented-delete-crash.serial.test.ts: one managed source whose page over the+ * single-string ceiling has a canonical file, a soft delete stopped (for SIGKILL) at a publication seam, and the+ * owner's recovery pass, stopped at a restoration seam or run to the end. Prints one JSON line per step.+ */+import { randomUUID } from 'node:crypto';+import { execFileSync } from 'node:child_process';+import { existsSync, mkdirSync, readFileSync, readdirSync, writeSync } from 'node:fs';+import { dirname, join } from 'node:path';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { PostgresEngine } from '../../src/core/postgres-engine.ts';+import type { OperationContext } from '../../src/core/operations.ts';+import { installFaultHook } from '../../src/core/persistence/fault-points.ts';+import { recoverPublication } from '../../src/core/persistence/coordinator.ts';+import { localHostId, registerLocalWriter } from '../../src/core/persistence/identity.ts';+import { importManagedFile } from '../../src/core/persistence/import-mutations.ts';+import { claimWorktree } from '../../src/core/persistence/ownership.ts';+import { submitPageMutation } from '../../src/core/persistence/page-mutations.ts';+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';+import { fileSha, writeCanonicalPage } from '../helpers/large-page-file.ts';++const [mode, configPath, boundary = ''] = process.argv.slice(2);+const config: { engine: 'pglite' | 'postgres'; database_path?: string; database_url?: string; root: string; sourceId: string; slug: string; bytes: number } = JSON.parse(readFileSync(configPath!, 'utf8'));+if (config.engine === 'postgres') assertSafeE2eDatabaseUrl(config.database_url!);+const engine = config.engine === 'postgres' ? new PostgresEngine() : new PGLiteEngine();+await engine.connect(config as never);+const emit = (value: Record<string, unknown>) => writeSync(1, JSON.stringify(value) + '\n');+const hang = (): never => { const wait = new Int32Array(new SharedArrayBuffer(4)); for (;;) Atomics.wait(wait, 0, 0); };+const file = join(config.root, `${config.slug}.md`);+const ctx = { engine, sourceId: config.sourceId, remote: false, config: { engine: engine.kind, embedding_disabled: true } as never, dryRun: false,+ logger: { info() {}, warn() {}, error() {} } } as OperationContext;+const stages = () => existsSync(dirname(file)) ? readdirSync(dirname(file)).filter(name => name.includes('.tmp.')).map(name => join(dirname(file), name)) : [];+async function settled<T>(call: () => Promise<T>): Promise<T> {+ for (;;) {+ try { return await call(); }+ catch (error) { if ((error as { code?: string }).code !== 'write_pending') throw error; await Bun.sleep(1000); }+ }+}+async function deleteRequest() {+ const [row] = await engine.executeRaw<{ id: string; state: string; recovery: Record<string, any> | null; recovery_text: string | null; recovery_bytes: string }>(+ `SELECT id, state, recovery, recovery::text AS recovery_text, recovery_bytes::text AS recovery_bytes FROM persistence_requests+ WHERE source_id=$1 AND operation='delete_page' ORDER BY sequence DESC LIMIT 1`, [config.sourceId]);+ return row!;+}++try {+ if (mode === 'initialize') {+ await engine.initSchema();+ await engine.setConfig('pages.segmented_storage', 'on');+ mkdirSync(dirname(file), { recursive: true });+ execFileSync('git', ['init', '-q'], { cwd: config.root });+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [config.sourceId, config.root]);+ await registerLocalWriter(engine, 'cli');+ await claimWorktree(engine, config.sourceId, config.root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const written = writeCanonicalPage(file, config.bytes, 7);+ const imported = await settled(() => importManagedFile(engine, file, `${config.slug}.md`, { sourceId: config.sourceId, noEmbed: true }));+ const [page] = await engine.executeRaw<{ body_storage: string }>('SELECT body_storage FROM pages WHERE source_id=$1 AND slug=$2', [config.sourceId, config.slug]);+ emit({ initialized: imported.status, body_storage: page?.body_storage, ...written });+ } else if (mode === 'delete') {+ installFaultHook(async (point, detail) => {+ if (point !== boundary || detail.operation !== 'delete_page') return;+ emit({ boundary: point });+ hang();+ });+ const snapshot = await engine.readPageSnapshot(config.slug, { sourceId: config.sourceId, includeDeleted: true });+ await settled(() => submitPageMutation(ctx, { operation: 'delete_page', params: { slug: config.slug, expected_revision: snapshot!.revision, request_id: randomUUID() } }));+ emit({ error: 'the delete committed without reaching the crash seam' });+ } else if (mode === 'inspect') {+ const row = await deleteRequest();+ const [page] = await engine.executeRaw<{ deleted: boolean }>('SELECT deleted_at IS NOT NULL AS deleted FROM pages WHERE source_id=$1 AND slug=$2', [config.sourceId, config.slug]);+ const counters = await engine.executeRaw<{ bytes: string }>('SELECT recovery_bytes::text AS bytes FROM persistence_counters');+ emit({ state: row.state, recovery_chars: row.recovery_text?.length ?? 0, recovery_bytes: Number(row.recovery_bytes),+ before: row.recovery?.before ?? null, before_hash: row.recovery?.beforeHash ?? null, before_stage: row.recovery?.staging?.before ?? null,+ file_sha: existsSync(file) ? fileSha(file) : null, stages: stages().map(path => ({ path, sha: fileSha(path) })),+ page_deleted: page?.deleted ?? null, counters_zero: counters.every(counter => Number(counter.bytes) === 0) });+ } else if (mode === 'recover') {+ const row = await deleteRequest();+ const recovered = await recoverPublication(engine, row.id, localHostId(), false, undefined, false, {+ fileBoundary: point => { if (point === boundary) { emit({ boundary: point }); hang(); } },+ });+ emit({ recovered: recovered.state, recovery: recovered.recovery === null ? null : 'set', blocked_reason: recovered.blocked_reason ?? null });+ }+} finally {+ await disposePersistenceConsumer(engine).catch(() => undefined);+ await engine.disconnect();+}diff --git a/test/helpers/large-page-file.ts b/test/helpers/large-page-file.tsnew file mode 100644index 0000000000..0ba0497d81--- /dev/null+++ b/test/helpers/large-page-file.ts@@ -0,0 +1,33 @@+/**+ * Large page files for the Wave B delete/restore tests: a file of about `bytes` body bytes in gbrain's+ * serialization (`type` before `title`, as serializePageToMarkdown writes them), so a restore writes it back+ * byte for byte, written in 8 MiB pieces so a test never holds it whole; and a streamed SHA-256 of a file.+ */+import { createHash } from 'node:crypto';+import { appendFileSync, closeSync, mkdirSync, openSync, readSync, statSync, writeFileSync } from 'node:fs';+import { dirname } from 'node:path';+import { conversationBody } from './conversation-page.ts';++const MiB = 1024 * 1024;++export function writeCanonicalPage(path: string, bytes: number, seed: number): { sha: string; size: number } {+ mkdirSync(dirname(path), { recursive: true });+ writeFileSync(path, '---\ntype: note\ntitle: Large conversation\n---\n\n');+ for (let written = 0, part = 0; written < bytes; part++) {+ const piece = `${part ? '\n\n' : ''}${conversationBody(Math.min(8 * MiB, bytes - written), { seed: seed + part })}`;+ appendFileSync(path, piece);+ written += Buffer.byteLength(piece);+ }+ appendFileSync(path, '\n');+ return { sha: fileSha(path), size: statSync(path).size };+}++export function fileSha(path: string): string {+ const hash = createHash('sha256');+ const fd = openSync(path, 'r');+ try {+ const buffer = Buffer.alloc(4 * MiB);+ for (let n; (n = readSync(fd, buffer, 0, buffer.length, null)) > 0;) hash.update(buffer.subarray(0, n));+ } finally { closeSync(fd); }+ return hash.digest('hex');+}diff --git a/test/large-pages/segmented-delete-crash.serial.test.ts b/test/large-pages/segmented-delete-crash.serial.test.tsnew file mode 100644index 0000000000..ab58c0b643--- /dev/null+++ b/test/large-pages/segmented-delete-crash.serial.test.ts@@ -0,0 +1,86 @@+/**+ * A soft delete of a file-backed page over the single-string ceiling killed after its file was removed and before its+ * commit (Wave B, PR 2 fix lane D).+ *+ * 1. Protects: the delete's recovery record names the prior file's staged copy by path and SHA-256 (no embedded+ * bytes, a record of a few hundred bytes); after SIGKILL at publication:after_publication or before_commit (file+ * removed, nothing committed) the owner's recovery pass renames the copy back, so the canonical file holds the+ * exact prior bytes, the page stays live, the request is requeued and its recovery bytes are released; a recovery+ * killed right after the rename finishes on its next pass with the same bytes and no stage left.+ * 2. Fails when: the record embeds the prior file (base64, ~36 MB for 27 MiB), the copy is cleaned before recovery+ * decides, or recovery restores anything but the recorded bytes.+ * 3. Existing coverage: persistence-skill-crash.slow.test.ts kills skill bundles (embedded before-images, 1 MiB files).+ * 4. Fault seams: the process-wide publication fault hook (fault-points.ts) and recoverPublication's fileBoundary.+ * Serial: SIGKILLs child processes that hold a brain. Runs on PGLite, and on Postgres when DATABASE_URL is set.+ */+import { expect, test } from 'bun:test';+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { randomUUID } from 'node:crypto';+import postgres from '#postgres';+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';+import { testBackends } from '../helpers/test-backends.ts';++const worker = join(import.meta.dir, '../fixtures/large-delete-crash-worker.ts');+const MiB = 1024 * 1024;++test('a large soft delete killed between file removal and commit recovers the exact prior bytes from its staged copy', async () => {+ for (const kind of testBackends()) {+ for (const seam of ['publication:after_publication', 'publication:before_commit']) {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-large-delete-crash-'));+ const configPath = join(home, 'worker.json');+ const database = `gbrain_test_large_delete_${randomUUID().replaceAll('-', '')}`;+ let admin: ReturnType<typeof postgres> | undefined;+ let databaseUrl: string | undefined;+ if (kind === 'postgres') {+ assertSafeE2eDatabaseUrl(process.env.DATABASE_URL!);+ admin = postgres(process.env.DATABASE_URL!, { max: 1, prepare: false });+ await admin.unsafe(`CREATE DATABASE ${database}`);+ const url = new URL(process.env.DATABASE_URL!); url.pathname = `/${database}`; databaseUrl = url.toString();+ }+ writeFileSync(configPath, JSON.stringify({ engine: kind, database_path: join(home, 'db'), database_url: databaseUrl, root: join(home, 'root'),+ sourceId: 'crash-example', slug: 'notes/large', bytes: 27 * MiB }));+ const env = { ...process.env, GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined,+ GBRAIN_SKIP_STARTUP_HOOKS: '1', GBRAIN_BACKUP_CHECK: '0', GBRAIN_SWEEP: '0', OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };+ const run = async (mode: string, boundary = ''): Promise<Record<string, any>> => {+ const child = Bun.spawn([process.execPath, worker, mode, configPath, boundary], { cwd: home, env, stdout: 'pipe', stderr: 'pipe' });+ const errors = new Response(child.stderr).text();+ const timer = setTimeout(() => child.kill('SIGKILL'), 600_000);+ let output = '';+ try {+ for await (const bytes of child.stdout) {+ output += new TextDecoder().decode(bytes);+ if (boundary && output.includes(`"boundary":"${boundary}"`)) { child.kill('SIGKILL'); break; }+ }+ const code = await child.exited;+ if (boundary) expect({ output, code }).toMatchObject({ output: expect.stringContaining(`"boundary":"${boundary}"`) });+ else expect({ code, stderr: code === 0 ? '' : await errors }).toEqual({ code: 0, stderr: '' });+ return JSON.parse(output.trim().split('\n').at(-1)!);+ } finally { clearTimeout(timer); if (child.exitCode === null) { child.kill('SIGKILL'); await child.exited; } }+ };+ try {+ const initialized = await run('initialize');+ expect(initialized).toMatchObject({ initialized: 'imported', body_storage: 'segmented' });++ await run('delete', seam);+ const crashed = await run('inspect');+ // The file is gone (or about to be) and nothing committed; the record names the copy instead of embedding it.+ expect(crashed).toMatchObject({ before: null, before_hash: initialized.sha, page_deleted: false });+ expect(crashed.recovery_chars).toBeLessThan(4096);+ expect(crashed.file_sha).toBeNull();+ expect(crashed.before_stage).toMatchObject({ hash: initialized.sha, bytes: initialized.size });+ expect(crashed.stages).toEqual([{ path: crashed.before_stage.path, sha: initialized.sha }]);++ // A recovery killed right after it renamed the copy back finishes on its next pass.+ await run('recover', 'restoration_file_replaced');+ expect(await run('inspect')).toMatchObject({ file_sha: initialized.sha, stages: [] });+ expect(await run('recover')).toMatchObject({ recovered: 'queued', recovery: null, blocked_reason: null });+ expect(await run('inspect')).toMatchObject({ state: 'queued', file_sha: initialized.sha, stages: [], page_deleted: false, recovery_bytes: 0, counters_zero: true });+ } finally {+ if (admin) { await admin.unsafe(`DROP DATABASE ${database} WITH (FORCE)`); await admin.end(); }+ rmSync(home, { recursive: true, force: true });+ }+ }+ }+}, 1_800_000);diff --git a/test/large-pages/segmented-delete-restore-file.slow.test.ts b/test/large-pages/segmented-delete-restore-file.slow.test.tsnew file mode 100644index 0000000000..9dcffddc3d--- /dev/null+++ b/test/large-pages/segmented-delete-restore-file.slow.test.ts@@ -0,0 +1,159 @@+/**+ * Delete and restore of a file-backed segmented page over the single-string ceiling, up to the engine's+ * `pages.max_bytes` (Wave B, PR 2 fix lane D).+ *+ * 1. Protects: on a managed source with a claimed worktree, a soft delete of a page over 24 MiB removes its+ * canonical file and restore_page writes it back byte for byte (the file in gbrain's serialization), at+ * 27 MiB (over the 25 MiB pre-push scan cap) and at 90 MiB (whose base64 recovery record once reserved more+ * than the 256 MiB worktree recovery budget); a purge then removes page and file. The restore streams the+ * file from the segments into its staging file and the delete stages the prior file by copy: no file read,+ * hash, copy or write piece is over one segment (`largeFileWork`), and nothing is left staged.+ * 2. Fails when: restore_page refuses a file over the push-scan cap (`request_too_large`: the file a delete+ * removed is lost), the restore concatenates the export into one buffer or reads the canonical file whole,+ * or the delete's recovery reservation does not fit the worktree budget.+ * 3. Existing coverage: segmented-file-drift.test.ts restores a page under the push-scan cap whose file sync+ * removed; no test deleted and restored a page above it.+ * 4. No production seam: `largeFileWork` is the module's own work counter.+ * Runs on PGLite, and on Postgres when DATABASE_URL is set.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { execFileSync } from 'node:child_process';+import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, statSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import type { BrainEngine } from '../../src/core/engine.ts';+import type { OperationContext } from '../../src/core/operations.ts';+import { SEGMENT_MAX_BYTES } from '../../src/core/page-body/limits.ts';+import { PAGE_MAX_BYTES } from '../../src/core/page-size-policy.ts';+import { claimWorktree } from '../../src/core/persistence/ownership.ts';+import { registerLocalWriter } from '../../src/core/persistence/identity.ts';+import { importManagedFile } from '../../src/core/persistence/import-mutations.ts';+import { submitPageMutation } from '../../src/core/persistence/page-mutations.ts';+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';+import * as largeFile from '../../src/core/persistence/large-file.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { withEnv } from '../helpers/with-env.ts';+import { fileSha, writeCanonicalPage } from '../helpers/large-page-file.ts';++const home = mkdtempSync(join(tmpdir(), 'gbrain-segmented-delete-restore-'));+const engines: BrainEngine[] = [];+let closePostgres: (() => Promise<void>) | undefined;+const env = { GBRAIN_HOME: home, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };+const logger = { info() {}, warn() {}, error() {} };+const MiB = 1024 * 1024;+// Imported as a namespace so the probe runs (and fails on the restore) on a tree that predates the counter.+const work = (largeFile as { largeFileWork?: Record<string, number> }).largeFileWork ?? { bytesRead: 0, bytesWritten: 0, bytesCopied: 0, largestPiece: 0 };++beforeAll(async () => {+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);+ if (process.env.DATABASE_URL) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL); engines.push(pg.engine); closePostgres = pg.close; }+}, 120_000);++afterAll(async () => {+ await withEnv(env, async () => {+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }+ await closePostgres?.();+ });+ rmSync(home, { recursive: true, force: true });+});++interface Fixture { sourceId: string; root: string; ctx: OperationContext }++async function managedSource(engine: BrainEngine): Promise<Fixture> {+ await disposePersistenceConsumer(engine);+ await engine.setConfig('pages.segmented_storage', 'on');+ const root = join(home, `src-${randomUUID().slice(0, 8)}`);+ mkdirSync(join(root, 'notes'), { recursive: true });+ execFileSync('git', ['init', '-q'], { cwd: root });+ const sourceId = `dr-${randomUUID().slice(0, 8)}`;+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [sourceId, root]);+ await registerLocalWriter(engine, 'cli');+ await claimWorktree(engine, sourceId, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const ctx = { engine, sourceId, remote: false, config: { engine: engine.kind, embedding_disabled: true } as never, dryRun: false, logger } as OperationContext;+ return { sourceId, root, ctx };+}++const revisionOf = async (engine: BrainEngine, f: Fixture, slug: string) => (await engine.readPageSnapshot(slug, { sourceId: f.sourceId, includeDeleted: true }))!.revision;++/** A write over 64 MiB can outlast the reply wait: the same call (same request_id) is repeated until it settles. */+async function settled<T>(call: () => Promise<T>): Promise<T> {+ for (;;) {+ try { return await call(); }+ catch (error) { if ((error as { code?: string }).code !== 'write_pending') throw error; await Bun.sleep(1000); }+ }+}++async function submit(engine: BrainEngine, f: Fixture, operation: 'delete_page' | 'restore_page', slug: string, extra: Record<string, unknown> = {}) {+ const params = { slug, expected_revision: await revisionOf(engine, f, slug), request_id: randomUUID(), ...extra };+ return settled(() => submitPageMutation(f.ctx, { operation, params }) as Promise<Record<string, any>>);+}++async function pageRow(engine: BrainEngine, f: Fixture, slug: string) {+ const [row] = await engine.executeRaw<{ deleted: boolean; body_storage: string; body_bytes: string }>(`SELECT deleted_at IS NOT NULL AS deleted, body_storage,+ body_bytes::text AS body_bytes FROM pages WHERE source_id=$1 AND slug=$2`, [f.sourceId, slug]);+ return row ?? null;+}++/** Staging leftovers (hidden `.<sha>.tmp.<uuid>` siblings) in the source's notes directory. */+const stagingLeft = (f: Fixture) => readdirSync(join(f.root, 'notes')).filter(name => name.includes('.tmp.'));+const resetWork = () => { for (const key of Object.keys(work)) work[key] = 0; };++async function roundTrip(engine: BrainEngine, bodyBytes: number, seed: number): Promise<void> {+ const f = await managedSource(engine);+ const slug = `notes/large-${seed}`;+ const file = join(f.root, `${slug}.md`);+ try {+ const original = writeCanonicalPage(file, bodyBytes, seed);+ expect(await settled(() => importManagedFile(engine, file, `${slug}.md`, { sourceId: f.sourceId, noEmbed: true }))).toMatchObject({ status: 'imported' });+ const imported = (await pageRow(engine, f, slug))!;+ expect(imported.body_storage).toBe('segmented');+ expect(Number(imported.body_bytes)).toBeGreaterThan(PAGE_MAX_BYTES);++ resetWork();+ expect(await submit(engine, f, 'delete_page', slug)).toMatchObject({ status: 'soft_deleted', noop: false });+ expect(existsSync(file)).toBe(false);+ expect((await pageRow(engine, f, slug))?.deleted).toBe(true);+ expect(stagingLeft(f)).toEqual([]);+ const deleted = { ...work };++ resetWork();+ const restored = await submit(engine, f, 'restore_page', slug).catch((error: Error & { code?: string }) => ({ refused: error.code, message: error.message }));+ expect(restored).toMatchObject({ status: 'restored', noop: false });+ expect((await pageRow(engine, f, slug))?.deleted).toBe(false);+ expect(existsSync(file)).toBe(true);+ expect(statSync(file).size).toBe(original.size);+ expect(fileSha(file)).toBe(original.sha);+ expect(stagingLeft(f)).toEqual([]);+ // The delete copied the prior file to its recovery stage (removed with the commit), never reading it whole; the+ // restore measured the file once in preparation, then streamed it into its staging file. No piece over a segment.+ expect(deleted.bytesCopied).toBe(original.size);+ expect(work.bytesWritten).toBe(original.size);+ for (const counted of [deleted, work]) {+ expect(counted.largestPiece).toBeGreaterThan(0);+ expect(counted.largestPiece).toBeLessThanOrEqual(SEGMENT_MAX_BYTES);+ }++ // The written file is the page's canonical file: a purge's drift check matches it and removes page and file.+ expect(await submit(engine, f, 'delete_page', slug, { purge: true })).toMatchObject({ status: 'purged' });+ expect(existsSync(file)).toBe(false);+ expect(await pageRow(engine, f, slug)).toBeNull();+ expect(stagingLeft(f)).toEqual([]);+ const counters = await engine.executeRaw<{ bytes: string }>('SELECT recovery_bytes::text AS bytes FROM persistence_counters');+ expect(counters.every(row => Number(row.bytes) === 0)).toBe(true);+ } finally {+ await disposePersistenceConsumer(engine);+ rmSync(f.root, { recursive: true, force: true });+ }+}++test('a 27 MiB page (over the push-scan cap) deletes and restores its file byte for byte, streamed', async () => withEnv(env, async () => {+ for (const engine of engines) await roundTrip(engine, 27 * MiB, 101);+}), 1_800_000);++test('a 90 MiB page deletes and restores its file byte for byte, streamed, within the recovery budget', async () => withEnv(env, async () => {+ for (const engine of engines) await roundTrip(engine, 90 * MiB, 201);+}), 3_600_000);diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 75dceb8de2..5d4159a66a 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -83,6 +83,8 @@ test/large-pages/segmented-append-reembed.test.tstest/large-pages/segmented-body-unreachable.test.tstest/large-pages/segmented-conversation-facts.test.tstest/large-pages/segmented-create-searchable.test.ts+test/large-pages/segmented-delete-crash.serial.test.ts+test/large-pages/segmented-delete-restore-file.slow.test.tstest/large-pages/segmented-derived-parity.test.tstest/large-pages/segmented-derived-passes.test.tstest/large-pages/segmented-derived-work.test.ts