Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(large-pages): withdrawals mirror and commit segmented pages' canonical files, streamed
garrytan3809d951b4e7
diff --git a/docs/architecture/key-files/core-persistence-request-indexes.md b/docs/architecture/key-files/core-persistence-request-indexes.mdindex 80c3094167..a692bf12c6 100644--- a/docs/architecture/key-files/core-persistence-request-indexes.md+++ b/docs/architecture/key-files/core-persistence-request-indexes.md@@ -5,5 +5,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGELThe online-built request-table indexes (the managed sync checkpoint pair, the page purge's slug index, dream postprocessing's request-id index), the checkpoint validation they serve, the named fault seams the persistence gate and the purge tests inject at, and the stuck-recovery resolution (`gbrain repair stuck-recovery`) that uses them.- `src/core/persistence/checkpoint-validation.ts` — the managed sync checkpoint's incomplete-receipt validation (#5762): `INCOMPLETE_SYNC_RECEIPT_SQL` is three `LIMIT 1` probes (recovery; an open page receipt of the run; a non-committed page receipt with no committed sibling at its index) served by `persistence_requests_recovery`, `persistence_requests_sync_run_open` and `persistence_requests_sync_run_committed`, with the same result as the former single predicate. `findIncompleteSyncReceipt` returns the blocking receipt's request id and maps only this statement's 57014 statement timeout to the terminal, non-transient `checkpoint_validation_timeout`. `readRequestIndexStates` reads each index of `PERSISTENCE_REQUEST_ONLINE_INDEXES` (or the list passed) as valid, missing, INVALID or building (Postgres `pg_stat_progress_create_index`); `formatCheckpointTimeoutHint` / `checkpointTimeoutHint` is the one formatter for the three-state hint and the filled retry (`gbrain sync --source <id> --no-pull --retry-failed` plus the cursor-selecting options the checkpoint intent records in `syncOptions` and the saved processing flags), used by the sync summary and `get_write_request`. Tests: `test/persistence-sync-checkpoint-validation.test.ts`, `test/e2e/persistence-request-indexes-postgres.test.ts`.-- `src/core/persistence/fault-points.ts` — named crash seams for the persistence gate. `faultPoint(point, detail)` is a no-op unless a gate worker installed a hook with `installFaultHook`; production never does. Seams: `publication:<boundary>` (the five `PublicationHooks.boundary` names, routed through `withFaultPoints` in `publishMutation`), `effect:<kind>:mid` for every `EffectKind` in `completeEffect` (after the side effect, before its completion is recorded; `EFFECT_FAULT_POINTS` is a `Record<EffectKind, FaultPoint>`), `effect_recovery:before_clear` (`effect-recovery.ts`), `publication_recovery:before_clear` (`recoverPublication`), `sync:mid_checkpoint` (after each committed cursor step in `sync-run.ts` `saveCursor`), `sync:after_freeze` (#6712 PR 0: at the end of `freezeEntry` for an import entry, after its bytes are read and before the request is admitted; detail carries `slug` and `path`), `consumer:prepared` (between preparing a claimed request and publishing it), `stuck_recovery:*` (between the steps of `recovery-resolve.ts`) and the purge lookups `purge:*` (page-purge.ts, intent-redaction.ts, facts/purge.ts; a hook throwing a 57014 models a statement timeout). Used by `scripts/persistence/crash-robot.ts`, the #6511 tests and `test/sync-convergence.serial.test.ts`, which installs it in real `serve`/`sync` processes through the `test/fixtures/convergence-fault-kill.ts` preload (one action registry: kill, uncommitted edit, stall until released, or throw a given SQLSTATE, at the nth hit).+- `src/core/persistence/fault-points.ts` — named crash seams for the persistence gate. `faultPoint(point, detail)` is a no-op unless a gate worker installed a hook with `installFaultHook`; production never does. Seams: `publication:<boundary>` (the five `PublicationHooks.boundary` names, routed through `withFaultPoints` in `publishMutation`), `effect:<kind>:mid` for every `EffectKind` in `completeEffect` (after the side effect, before its completion is recorded; `EFFECT_FAULT_POINTS` is a `Record<EffectKind, FaultPoint>`), `effect_recovery:before_clear` (`effect-recovery.ts`), `effect_recovery:before_stage` / `effect_recovery:staged` (a streamed, version 2 withdrawal mirror: once its record is durable, before its file is streamed into the publication stage, and after that step, before the recovery transaction renames the stage), `publication_recovery:before_clear` (`recoverPublication`), `sync:mid_checkpoint` (after each committed cursor step in `sync-run.ts` `saveCursor`), `sync:after_freeze` (#6712 PR 0: at the end of `freezeEntry` for an import entry, after its bytes are read and before the request is admitted; detail carries `slug` and `path`), `consumer:prepared` (between preparing a claimed request and publishing it), `stuck_recovery:*` (between the steps of `recovery-resolve.ts`) and the purge lookups `purge:*` (page-purge.ts, intent-redaction.ts, facts/purge.ts; a hook throwing a 57014 models a statement timeout). Used by `scripts/persistence/crash-robot.ts`, the #6511 tests and `test/sync-convergence.serial.test.ts`, which installs it in real `serve`/`sync` processes through the `test/fixtures/convergence-fault-kill.ts` preload (one action registry: kill, uncommitted edit, stall until released, or throw a given SQLSTATE, at the nth hit).- `src/core/persistence/recovery-resolve.ts` + `src/core/repair/stuck-recovery.ts` — `gbrain repair stuck-recovery [--source <id>] [--request-id <uuid>]` (#6650 §1.10), explicit-only, preview-bound and destructive (registry `consentText`; `--apply --expect <hash> --keep prior|disk --yes`, a non-interactive apply without `--yes` exits 3). `scanStuckRecoveries` (owner host only, else `owner_unavailable` for a named source) reads the source's queued head blocker (`readHeadBlockers`; its `request_recovery` ids select the records) and every non-terminal recovery record on the worktree blocked on `unexpected_file_bytes` or whose file matches neither recorded version; a v2 shared-skill bundle record refuses `recovery_bundle_unsupported` (catalogue entry, `docs/guides/repair.md#recovery-bundle-unsupported`), a withdrawal-mirror effect recovery on the worktree is listed in `refused` (residual `effect_recovery`; named with `--request-id` it refuses `recovery_effect_unsupported`), a blocked terminal request is listed in `refused` (residual `terminal_refused`; named with `--request-id` it refuses `recovery_choice_refused`, as does a choice the record cannot support), and unblocked terminal cleanups, staging-byte blocks and self-recovering records are residuals. Each item lists every file's prior (or absent) and disk (or deleted) fingerprints and what recovery sees; a local preview writes the prior, disk and unified-diff files 0600 under `~/.gbrain/backups/stuck-recovery/<request>/<digest>/` (a private directory outside every checkout) and prints the `diff -u` command. The item digest binds the recovery identity (attempt, owner epoch, path and published hash per file), the recorded prior hashes, each file's disk view and the page's `knowledge_revision`. `resolveStuckRecovery` runs under `acquireWorktree` with a bounded wait (10 s, then `writer_lock_unavailable`; so the resident recovery pass returns unchanged), re-verifies the digest (`preview_changed`) and journals in `op_checkpoints` op `stuck-recovery-resolution` keyed `<request row id>:<preview hash>` (exempt from the checkpoint purge; the finished row is the audit entry): `backed_up` (disk and prior bytes durable, always), then `written` (`--keep prior`: `upgradeRecoveryStaging` reserves an older record's restoration stage within the recovery budget, `queue_capacity` otherwise, then the prior bytes are published through `publishPersistenceFile` at that stage after `cleanupRecoveryStaging`, an absent prior unlinked) or `abandoned` (`--keep disk`, #6640's drop: `completeWrite` ends the live request `conflict` `source_changed`, or `finishUnpublishedFailure` with its recorded failure; the record is never rewritten, so its reserved bytes are released by the terminal path's `clearResolvedRecovery`), then `recoverPublication(…, alreadyLocked)` finishes by its unchanged rule and the journal records `done` with the result. A step refuses `unexpected_file_bytes` when the file changed again; a different `--keep` for the same hash refuses `idempotency_conflict`; an identical apply after `done` replays the result (also after the approved set aged out). A record the resident consumer (any version) or an earlier killed run already finished reports `finished_by: another_pass`. `--keep prior` on a request with no recorded failure requeues it (the accepted write publishes again). `--keep disk` hands off to `gbrain sources reconcile <source> <slug> --brain host --preview` and never reports the page repaired. Fault seams `stuck_recovery:{backed_up,written,abandoned,recovered}`. Tests: `test/repair-stuck-recovery.test.ts`, `test/e2e/repair-stuck-recovery-postgres.test.ts`.+- Segmented withdrawal mirror (`src/core/persistence/{effects,effect-recovery,effect-model,staging}.ts`, flip lane A) — a withdrawal's mirror and Git scans treat a page stored in segments as an inline page (older binaries skipped it with `page_body_segmented`). `mirrorPage` renders its file from the segments (`page-prepare.ts` `unreadPageFile`, a `StreamedFileContent`) and reserves a version 2 `EffectRecovery` (`after: null`; `staging.publication` names the streamed file by path and SHA-256; the reservation counts the file once). `recoverEffectPublication` writes that stage before its transaction (`stageStreamedMirror`: from the measured file, or after a crash from the segments at the recorded revision; seams `effect_recovery:before_stage` / `effect_recovery:staged`), then renames the verified stage (`staging.ts` `publishStreamedStage`). A segmented page's withdrawal is not materialized again: its rows were struck in its segments when the withdrawal committed. An older binary refuses a version 2 record (it has no embedded file) and leaves it for this one. Test: `test/large-pages/segmented-withdrawal-mirror.test.ts` (purge and forget twins, Git commits, two interruption seams, both engines).diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.mdindex 170b1a263d..ecdb1611e9 100644--- a/docs/architecture/key-files/core-persistence.md+++ b/docs/architecture/key-files/core-persistence.md@@ -39,7 +39,7 @@ Managed facts extraction (withdrawn-candidate skip and recovery, conversation fa- `src/core/persistence/params.ts` — runtime-leaf mutation parameter and receipt schemas shared with the frozen verb registry. Its operation-contract import is type-only; runtime validators live in separate modules to avoid a registry initialization cycle. `preconditions.ts` validates UUID/revision/force syntax. `purge-params.ts` validates local-only purge shape/trust before admission and publication, keeping purge diagnostics out of generic precondition imports and unrelated command flag scans. `test/persistence-cold-import.test.ts` loads each validator/contract/registry entry in a fresh process and preserves schema and typed-error identity.- `src/core/persistence/write-wait.ts` — the CLI write-wait and exit contract (#5232). `resolveCliWriteWaitMs` (`--wait` seconds > `GBRAIN_WRITE_WAIT_MS` > file-plane `persistence.write_wait_ms` > 30 s; agents keep `AGENT_WRITE_WAIT_MS`); `writeExchangeBudget` (transport deadline = wait + 15 s admission headroom; an explicit `--timeout` shortens the requested owner wait instead); `replayWhilePending` (replays the identical request ID while an older owner, a remote server or a subagent tool's own bounded wait reports pending; the caller-supplied `sleep` decides how each pause ends, which is how subagent tool writes stop on abort); `writeErrorExitCode` keys on an admitted non-terminal receipt (`admittedPendingReceipt` in `types.ts`): pending → `PENDING_WRITE_EXIT_CODE` (0 with `--accept-pending`/`GBRAIN_ACCEPT_PENDING=1`), anything else → 1. Pinned by `test/pending-write-exit.serial.test.ts` and `test/pending-write-exit-owner.test.ts`. `pollCommand` (#6255) renders the envelope's receipt `fix.argv` (`gbrain write-request --brain <id> -- <request_id>`), else pins that argv to the CLI routing; each argument is shell-quoted (`src/core/shell-quote.ts`, fix wave 13 P1.15).- `src/core/persistence/page-edit.ts` — `edit_page` (#5616): splits the canonical serialization into editable text and protected takes/facts segments whose remote view matches get_page's sanitized `content` byte for byte; `applyPageEdits` applies ordered exact-once replacements inside editable text only (typed `edit_no_match`/`edit_ambiguous_match`/`edit_protected_span`/`edit_invalid`), so canonical fences never move; `editDiff` caps the caller-view diff at 8 KB; `boundedUnifiedDiff` keeps its LCS table under `EDIT_PAGE_DIFF_CELL_BUDGET` (4M cells) by diffing only the window between common leading/trailing lines, and a window still over budget becomes one coarse hunk flagged `diff_coarse` (pinned by `test/large-pages/edit-diff-bounded.test.ts`). Called at submission (`page-mutations.ts`, before admission) and again on the locked snapshot in `page-prepare.ts`, which gives edit_page put_page's revision-bound `editing` timeline semantics. Pinned by `test/edit-page.test.ts`.-- `src/core/persistence/{effect-schema,effect-model,effect-journal,effect-recovery,effect-git,effects}.ts` — bounded postcommit outbox (migration 155). Canonical publication atomically queues Git and embedding work; withdrawals queue three versioned, bounded exact-page manifests with durable slug cursors. `effect-targets.ts` converts legacy source scans with complete bounded discovery keyed on the request's own forgotten fact (falling back to the whole source ledger only when that fact row is gone) while retaining each cursor; ambiguous or over-capacity legacy intent stays pending. Older workers must be quiesced before rollout. Independent mirror recovery reserves capacity before file effects, finishes forward without changing revision or receipt, and blocks only its worktree until reconciled. Git holds the native root lock, disables hooks, uses literal pathspecs and target-only commits, and pushes without pull/rebase. A claimed single-file Git effect brings up to 99 more ready single-file Git effects of its worktree (`claimCoalescedGitEffects`, same readiness, recovery and withdrawal-mirror ordering predicates, `SKIP LOCKED`); the runner validates each path under the worktree lock, makes one `commit --only` per group (`commitGitTargets`: one `ls-files`, `status`, `add` and `diff` for the group; untracked absent or ignored targets take the per-target refusal path) and pushes each root once at the end of the pass (`pushGitRoot`). A page file target's optional `commit` note (`GitCommitNote`, set only by trusted local preparers: a fence repair's `fenceRepairCommit`) is queued as `commit_subject`/`commit_line` in the Git effect's data and passed by the runner to `commitGitTargets`/`publishGitEffect`: a noted path committing alone takes its subject; a group keeps `gbrain: persist N canonical memory updates` and lists the noted paths' lines in the body, in path order; control characters are stripped, and targets without a note commit exactly as before (`test/fence-repair-receipts.test.ts`). A group yields to publications still queued or running for its worktree (one update requeues it with `publication_pending`, 250 ms apart) for at most 20 claims, so a serial producer publishes ahead and its Git work lands as one group, and a write admitted behind a backlog of full groups takes the worktree lock after the group already committing (wave 9; on master it waited out the backlog and its 5 s write wait); the v0.13.1 grandfather step admits a 50-page window (`admitCanonicalGrandfather`) before waiting for it. `claimCoalescedGitEffects` checks the worktree-wide conditions (owner, refresh fence, recovery blocks) once as an InitPlan, so the claim walks `persistence_effects_pending` in order and stops at its limit (351 → 25 ms per claim with 22k ready effects). A path failure fails only its effect; a push failure leaves the group queued with `git_push_unavailable`, and the next pass finds nothing to commit and pushes once. In a root without the durability hook a group runs no git command: it takes each root's lock once, guards each source incarnation once, validates every path as before and records the `durability_not_enabled` outcomes in one update (a 50k import's ~30k queued effects drain inside a minute of serve) (#5530; tests: `persistence-git-coalescing-5530.slow.test.ts` + Postgres wrapper). A Git effect for a declared db_only page completes as skipped (`reason: db_only`), keeping its gitignored cache file out of Git. A Git or withdrawal target parks after five consecutive execution failures (`data.target_failures` for `data.failing_target`, reset when the target advances or a different target fails; shutdown cancellation, contention, dependency waits (including recovery-capacity waits) and transient database failures do not count): a scan records it in `data.parked` and moves on, a single-target effect or a failure outside any target parks the whole effect, and an effect with parked targets finishes as `failed`/`targets_parked`, never committed. A mirror or Git scan never parks on a sync-skip metafile page (`RESOLVER.md` carries the managed durability block by design) or on a file whose bytes hold an uncoordinated local edit (`file_database_drift`): the mirror materializes the withdrawal in the database without touching the file, both scans record the page in `data.skipped` (at most 100) and advance, so the request's Git and embedding effects are no longer gated behind a parked mirror (#5396). Migration 170 indexes parked effects for the `parked_effects` doctor check. `retryParkedEffects` (the `retry-effects` admin path) previews parked targets or authorizes one more attempt per target (`data.retry_slugs`, visited before the cursor); tests: `persistence-effect-parking.test.ts`. Old targets resolve under the same hash/confinement checks without changing frozen data; ambiguous absent spellings refuse after scoped staged/unstaged deletion checks. Embedding runs outside transactions/OS locks and installs with projection CAS. Receipt helpers return only public effect state/reason/push. Consumer shutdown aborts providers and awaits workers; receipt compaction is bounded. Tests: `persistence-effects.test.ts`, `persistence-git-publication.test.ts`, `persistence-publication-native.serial.test.ts`. Embedding completion checks active column/vector, embedded stamp, text hash, model and page signature; partial work sends only stale chunks and preserves valid siblings. A partial synopsis rebuild completes before title demotion. Provider timeouts use the gateway budget, five durable page claims/backoff, execution-token CAS after provider work and atomic vector/stamp/effect completion. Keyless work skips cleanly. `retry-effects` is an explicit one-shot failed-effect allowance; current vectors reconcile provider-free without changing canonical receipts. A git refusal on an index lock (git's own message names the lock, so linked worktrees resolve) is `git_index_locked` contention (retried, not counted toward parking) while the lock is younger than 10 minutes, and `git_index_stale` (counted, naming the lock) when older or future-dated; the lock is never removed, because no timestamp proves its holder is gone.+- `src/core/persistence/{effect-schema,effect-model,effect-journal,effect-recovery,effect-git,effects}.ts` — bounded postcommit outbox (migration 155). Canonical publication atomically queues Git and embedding work; withdrawals queue three versioned, bounded exact-page manifests with durable slug cursors. `effect-targets.ts` converts legacy source scans with complete bounded discovery keyed on the request's own forgotten fact (falling back to the whole source ledger only when that fact row is gone) while retaining each cursor; ambiguous or over-capacity legacy intent stays pending. Older workers must be quiesced before rollout. Independent mirror recovery reserves capacity before file effects, finishes forward without changing revision or receipt, and blocks only its worktree until reconciled. Git holds the native root lock, disables hooks, uses literal pathspecs and target-only commits, and pushes without pull/rebase. A claimed single-file Git effect brings up to 99 more ready single-file Git effects of its worktree (`claimCoalescedGitEffects`, same readiness, recovery and withdrawal-mirror ordering predicates, `SKIP LOCKED`); the runner validates each path under the worktree lock, makes one `commit --only` per group (`commitGitTargets`: one `ls-files`, `status`, `add` and `diff` for the group; untracked absent or ignored targets take the per-target refusal path) and pushes each root once at the end of the pass (`pushGitRoot`). A page file target's optional `commit` note (`GitCommitNote`, set only by trusted local preparers: a fence repair's `fenceRepairCommit`) is queued as `commit_subject`/`commit_line` in the Git effect's data and passed by the runner to `commitGitTargets`/`publishGitEffect`: a noted path committing alone takes its subject; a group keeps `gbrain: persist N canonical memory updates` and lists the noted paths' lines in the body, in path order; control characters are stripped, and targets without a note commit exactly as before (`test/fence-repair-receipts.test.ts`). A group yields to publications still queued or running for its worktree (one update requeues it with `publication_pending`, 250 ms apart) for at most 20 claims, so a serial producer publishes ahead and its Git work lands as one group, and a write admitted behind a backlog of full groups takes the worktree lock after the group already committing (wave 9; on master it waited out the backlog and its 5 s write wait); the v0.13.1 grandfather step admits a 50-page window (`admitCanonicalGrandfather`) before waiting for it. `claimCoalescedGitEffects` checks the worktree-wide conditions (owner, refresh fence, recovery blocks) once as an InitPlan, so the claim walks `persistence_effects_pending` in order and stops at its limit (351 → 25 ms per claim with 22k ready effects). A path failure fails only its effect; a push failure leaves the group queued with `git_push_unavailable`, and the next pass finds nothing to commit and pushes once. In a root without the durability hook a group runs no git command: it takes each root's lock once, guards each source incarnation once, validates every path as before and records the `durability_not_enabled` outcomes in one update (a 50k import's ~30k queued effects drain inside a minute of serve) (#5530; tests: `persistence-git-coalescing-5530.slow.test.ts` + Postgres wrapper). A Git effect for a declared db_only page completes as skipped (`reason: db_only`), keeping its gitignored cache file out of Git. A Git or withdrawal target parks after five consecutive execution failures (`data.target_failures` for `data.failing_target`, reset when the target advances or a different target fails; shutdown cancellation, contention, dependency waits (including recovery-capacity waits) and transient database failures do not count): a scan records it in `data.parked` and moves on, a single-target effect or a failure outside any target parks the whole effect, and an effect with parked targets finishes as `failed`/`targets_parked`, never committed. A mirror or Git scan never parks on a sync-skip metafile page (`RESOLVER.md` carries the managed durability block by design) or on a file whose bytes hold an uncoordinated local edit (`file_database_drift`): the mirror materializes the withdrawal in the database without touching the file, both scans record the page in `data.skipped` (at most 100) and advance, so the request's Git and embedding effects are no longer gated behind a parked mirror (#5396). A page stored in segments is mirrored and committed too, streamed (see the segmented withdrawal mirror entry in `core-persistence-request-indexes.md`). Migration 170 indexes parked effects for the `parked_effects` doctor check. `retryParkedEffects` (the `retry-effects` admin path) previews parked targets or authorizes one more attempt per target (`data.retry_slugs`, visited before the cursor); tests: `persistence-effect-parking.test.ts`. Old targets resolve under the same hash/confinement checks without changing frozen data; ambiguous absent spellings refuse after scoped staged/unstaged deletion checks. Embedding runs outside transactions/OS locks and installs with projection CAS. Receipt helpers return only public effect state/reason/push. Consumer shutdown aborts providers and awaits workers; receipt compaction is bounded. Tests: `persistence-effects.test.ts`, `persistence-git-publication.test.ts`, `persistence-publication-native.serial.test.ts`. Embedding completion checks active column/vector, embedded stamp, text hash, model and page signature; partial work sends only stale chunks and preserves valid siblings. A partial synopsis rebuild completes before title demotion. Provider timeouts use the gateway budget, five durable page claims/backoff, execution-token CAS after provider work and atomic vector/stamp/effect completion. Keyless work skips cleanly. `retry-effects` is an explicit one-shot failed-effect allowance; current vectors reconcile provider-free without changing canonical receipts. A git refusal on an index lock (git's own message names the lock, so linked worktrees resolve) is `git_index_locked` contention (retried, not counted toward parking) while the lock is younger than 10 minutes, and `git_index_stale` (counted, naming the lock) when older or future-dated; the lock is never removed, because no timestamp proves its holder is gone.- `src/core/persistence/native-file-target.ts` — shared preparation/Git execution spelling resolution. Native directory-entry inode/device identity proves aliases; no global case folding or separator rewrite. Missing suffixes retain exact spelling, descendant symlinks and ambiguous aliases refuse, and physical root identity is rechecked. Exact POSIX case-distinct names and literal backslashes remain distinct. #5032: `isWindowsColonTarget(rel)` and `colonSlugWindowsRefusal(slug, sourceId)` name the one Windows-only refusal (`colon_slug_windows_write_through`: `:` names an NTFS alternate data stream); `submitPageMutation` raises it before admission when this host publishes the file, `prepareFileTarget` at publication, and managed (`fileRefusals`) and unmanaged (`failedFiles`) sync skip each such path by name (`test/colon-slug-windows-5032.test.ts`).diff --git a/docs/architecture/key-files/core-services-2-continued.md b/docs/architecture/key-files/core-services-2-continued.mdindex cdd4ac3d51..537a5ec9c9 100644--- a/docs/architecture/key-files/core-services-2-continued.md+++ b/docs/architecture/key-files/core-services-2-continued.md@@ -26,7 +26,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`, `extract --stale` (the stale list includes segmented pages since PR 2 fix lane J1; test `test/large-pages/segmented-extraction-stale.test.ts`), 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.slow.test.ts` (SIGKILL between file removal and commit, and after the restoration rename).+- `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`). Flip lane A: the withdrawal mirror of a segmented page (`effects.ts` `mirrorPage`, any size) renders its file with `page-prepare.ts` `unreadPageFile` (a `StreamedFileContent`) and writes it with `stageStreamedContent` before its recovery transaction (`effect-recovery.ts` `stageStreamedMirror`); `existsAt` is the lstat-based leaf check it uses. Test: `test/large-pages/segmented-withdrawal-mirror.test.ts`. 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.slow.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 ccf2418893..6786dc0259 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. 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/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. `publishStreamedStage` is the forward half of a version 2 withdrawal-mirror record (`effect-model.ts`): its verified publication stage, streamed from a segmented page's segments, is renamed over the canonical file; a missing stage refuses `unexpected_staging_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/memory-boundaries.md b/docs/guides/memory-boundaries.mdindex 820232667e..8a545d5dba 100644--- a/docs/guides/memory-boundaries.md+++ b/docs/guides/memory-boundaries.md@@ -191,6 +191,18 @@ page is searchable when the restore commits, or, when its chunks were neverbuilt, right after it (`gbrain projections drain` builds it if that builddies).+<a id="segmented-withdrawal-mirror"></a>+**Withdrawals rewrite a segmented page's file.** `forget`, `forget_fact` and+`purge_fact` on a page stored in segments, on a source backed by files,+rewrite its canonical file as they rewrite an inline page's: the file shows the+row forgotten, or loses the purged row, and holds the bytes `gbrain export`+writes for the page; the withdrawal's Git effect commits it. The file is+streamed from the segments into its staging file, one segment at a time, and+never held whole. Its recovery record names that staging file by path and+SHA-256 instead of holding the file, so the mirror reserves the file once in+the recovery budget. A mirror interrupted before or after writing the staging+file finishes on the writer's next pass.+<a id="segmented-doctor-skips"></a>**What doctor does not read on a segmented page.** Some doctor checks read apage's whole body as one string, and a page stored in segments has none.diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 43632f4b29..e1d936628a 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -763,6 +763,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.290.0', text: 'Semantic writes on a page stored in segments (`pages.segmented_storage` on): `add_tag` and `remove_tag` now work at any page size as a metadata change (the tag rows, `content_hash` and a version; no segment, chunk or embedding is rewritten), and a page backed by a file gets the new frontmatter in that file with its body unchanged; an `external_untrusted` writer, whose write gate scans the whole body, takes the put path below. `add_timeline_entry`, `takes_add` / `takes_update` / `takes_supersede` / `takes_resolve` / `takes_remove`, the facts fence write of `extract_facts`, `gbrain core add` / `remove` / `diff` and `gbrain sources reconcile` now read a segmented page up to 24 MiB back whole and write it as a normal put, with the result an inline page with the same body gets. Above 24 MiB they still refuse with `page_body_segmented` (wire error `invalid_params` for the memory verbs, not retryable), and the refusal now names the 24 MiB limit.' },{ since: '0.60.290.0', text: '`revert_version` of a page stored in segments, or to a version stored in segments, is refused with `page_body_segmented` (reason `segmented_revert`) before anything is written; it arrives with the segment writer in a later release. With `pages.segmented_storage` on, this includes pages between 1 MiB and 24 MiB that `revert_version` restores today. The versions stay readable: `get_versions` lists them, and a versioned `get_page` window reads one. Write the content you want back with `put_page`.' },{ since: '0.60.290.0', text: 'Core memory and `gbrain repair frontmatter` on a page stored in segments (`pages.segmented_storage` on): a core page (`always_load: true`) stored in segments up to 24 MiB is now read back whole and rendered, budgeted and listed as its inline twin is; before, it counted as its title alone, and once a fact was withdrawn from it (or a `*` withdrawal existed in its source) session-start core, `context_pack`, `gbrain core status` and every core page write failed with `page_body_segmented`. A core page over 24 MiB is left out of core and doctor `core_memory` counts it (`skipped_segmented`), which now counts only those. `gbrain repair frontmatter --include-ambiguous` re-imports a page stored in segments up to 24 MiB whose title was derived from its slug, as it re-imports an inline page; over 24 MiB the file is listed `needs_review` with `page_body_segmented`, naming the 24 MiB limit, and nothing is written. Before, either case failed the whole preview.' },+ // Switch-on flip lane A (withdrawal mirror of segmented pages). `since` is 'TBD' until the merge-slot stamp.+ { since: 'TBD', text: 'With `pages.segmented_storage` on, a withdrawal (`forget`, `forget_fact`, `purge_fact`) now rewrites the canonical file of a page stored in segments on a source backed by files, as it rewrites an inline page\'s: the file loses the withdrawn or purged row, its bytes are those `gbrain export` writes for the page, and the withdrawal\'s Git effect commits it. The file is streamed from the segments into its staging file one segment at a time, and its recovery record names that staging file by path and SHA-256 instead of holding the file. Before, the withdrawal-mirror and Git effects passed such a page by (`skipped` reason `page_body_segmented`) and its file kept the withdrawn text.' },// FIFO claim foreground guard (fgp-park-before-claim, #6862).{ since: '0.60.271.0', text: 'A foreground write no longer loses to an idle drain\'s sync head. While a managed sync drains, a page write that may go ahead of the queued sync groups (none of them names its page) now holds back the next sync group even when the drain\'s lanes are idle and the write\'s own process is still claiming it; before, the drain could start a group in that moment and the write waited for it. The sync side still gets one group after each such write commits, so a stream of writes cannot stall it.' },// #6858 (GBRA-121; Garry: "take care of fixing" #6858 asks 1-5; ask 5 contained per GBRA-108). `since` is a placeholder equal to the branch's VERSION; the integrator sets it to the merge-slot stamp by hand.diff --git a/src/core/persistence/effect-model.ts b/src/core/persistence/effect-model.tsindex bcd95e4ecc..d4fb834bb8 100644--- a/src/core/persistence/effect-model.ts+++ b/src/core/persistence/effect-model.ts@@ -29,17 +29,23 @@ export function contentRepairCommit(path: string, receipt: Pick<ContentRepairRecreturn { subject: contentRepairCommitSubject(path), line: `${safe(path)} (frontmatter_slug_conflict)`, trailer: contentRepairTrailer(receipt) };}export interface ParkedTarget { slug?: string; error_code: string }+/** `page_body_segmented`: a segmented page an older binary's mirror or Git scan passed by; this one mirrors and commits it. */export interface SkippedTarget { slug: string; reason: 'metafile' | 'file_database_drift' | 'page_body_segmented' }/** A Git or withdrawal target parks after this many consecutive execution failures. */export const PARK_AFTER_FAILURES = 5;+/**+ * A withdrawal mirror's recovery record. Version 1 embeds the mirrored file (`after`, base64). Version 2 is a segmented+ * page's file, never held whole: `after` is null and `staging.publication` names the file streamed from the page's+ * segments by path, SHA-256 (`afterHash`) and length, written once the record is durable (effect-recovery.ts).+ */export interface EffectRecovery {- version: 1;+ version: 1 | 2;kind: 'withdrawal-mirror';path: string;root: string;beforeHash: string | null;afterHash: string;- after: string;+ after: string | null;mode: number | null;ownerEpoch: string;pageId: number;diff --git a/src/core/persistence/effect-recovery.ts b/src/core/persistence/effect-recovery.tsindex 7df3982df9..7e8c675b10 100644--- a/src/core/persistence/effect-recovery.ts+++ b/src/core/persistence/effect-recovery.ts@@ -15,7 +15,10 @@ import { withFilesystemPublication } from './filesystem-guard.ts';import { persistenceFileHash, publishPersistenceFile } from './coordinator.ts';import type { EffectRecovery, PersistenceEffect } from './effect-model.ts';import { tryAcquirePublicationCapacity } from './pool-capacity.ts';-import { assertRecoveryStagingAbsent, cleanupRecoveryStaging, upgradeRecoveryStaging } from './staging.ts';+import { assertRecoveryStagingAbsent, cleanupRecoveryStaging, publishStreamedStage, upgradeRecoveryStaging } from './staging.ts';+import { existsAt, stageStreamedContent, type StreamedFileContent } from './large-file.ts';+import { unreadPageFile } from './page-prepare.ts';+import { isSegmentedPage } from '../page-body/page-shape.ts';import { declarePersistenceProtocol } from './protocol.ts';import { advanceEffectCursor } from './effect-journal.ts';import { faultPoint } from './fault-points.ts';@@ -97,15 +100,52 @@ async function clearRecovery(tx: BrainEngine, effect: PersistenceEffect): Promisawait tx.executeRaw('UPDATE persistence_effects SET recovery=NULL,recovery_bytes=0 WHERE id=$1', [effect.id]);}+/** Whether a mirror record belongs to the effect's current canonical binding (owner epoch, root and file path). */+function recordBelongs(record: EffectRecovery, effect: PersistenceEffect, binding: WorktreeBinding | null): binding is WorktreeBinding & { local_path: string } {+ return !!binding?.local_path && record.kind === 'withdrawal-mirror' && record.sourceIncarnation === effect.source_incarnation+ && String(binding.owner_epoch) === record.ownerEpoch && isWriteTargetContained(record.path, binding.local_path)+ && isWriteTargetContained(record.path, record.root) && isWriteTargetContained(record.root, binding.local_path)+ && resolve(record.root) === resolve(join(binding.local_path, binding.relative_path));+}++/**+ * A version 2 record's publication stage (effect-model.ts) is written before the recovery transaction, as a streamed+ * publication's is (coordinator.ts `stageLargeFiles`), one piece at a time: from `content`, the file the effect measured,+ * or after a crash from the page's segments at the recorded revision (`unreadPageFile`). Nothing is staged when the file+ * no longer holds its prior bytes, a leaf already holds the stage's name (the transaction verifies or refuses it), the+ * record no longer belongs to the binding (the transaction refuses it) or the page moved on (the transaction clears it).+ */+async function stageStreamedMirror(engine: BrainEngine, effect: PersistenceEffect, hostId: string, content?: StreamedFileContent): Promise<void> {+ const [row] = await engine.executeRaw<{ recovery: EffectRecovery | null }>(+ 'SELECT recovery FROM persistence_effects WHERE id=$1 AND execution_token=$2::uuid', [effect.id, effect.execution_token]);+ const record = row?.recovery;+ const stage = record?.version === 2 ? record.staging?.publication : undefined;+ if (!record || !stage || !recordBelongs(record, effect, await getWorktreeBinding(engine, effect.source_id, hostId))) return;+ const detail = { effectId: effect.id, requestId: effect.request_id, sourceId: effect.source_id, slug: record.slug, path: stage.path };+ await faultPoint('effect_recovery:before_stage', detail);+ await withFilesystemPublication([record.root], async () => {+ if (existsAt(stage.path) || record.beforeHash === record.afterHash || persistenceFileHash(record.path) !== record.beforeHash) return;+ let file = content;+ if (!file) {+ const snapshot = await engine.readPageSnapshot(record.slug, { sourceId: effect.source_id, includeDeleted: true });+ if (!snapshot || snapshot.page.id !== record.pageId || snapshot.revision !== record.revision) return;+ file = await unreadPageFile(engine, snapshot);+ }+ await stageStreamedContent(engine, record.path, file, stage, record.mode);+ });+ await faultPoint('effect_recovery:staged', detail);+}+/** Under the native lock: finish forward, never restore withdrawn bytes. */export async function recoverEffectPublication(engine: BrainEngine, effect: PersistenceEffect, hostId: string,- hooks: { boundary?: (name: 'before_mirror_file' | 'after_mirror_file' | 'before_mirror_commit') => Promise<void> } = {}): Promise<void> {+ hooks: { boundary?: (name: 'before_mirror_file' | 'after_mirror_file' | 'before_mirror_commit') => Promise<void>; content?: StreamedFileContent } = {}): Promise<void> {const releaseCapacity = tryAcquirePublicationCapacity(engine);if (!releaseCapacity) throw opError('writer_pool_capacity', 'Mirror recovery is waiting for publication capacity.',`Every publication slot of the writer pool is busy, so mirror recovery for source ${effect.source_id} has not started; the worker tries again once a slot frees. Nothing needs resubmitting.`,{ fix: effectStatusFix(effect) });try {if (effect.recovery) await upgradeRecoveryStaging(engine, 'persistence_effects', effect.id, effect.worktree_id!, 'forward');+ await stageStreamedMirror(engine, effect, hostId, hooks.content);await engine.transaction(async tx => {await tx.executeRaw("SELECT set_config('synchronous_commit','on',true),set_config('lock_timeout','1s',true),set_config('statement_timeout','5s',true)");const binding = await guardEffectSource(tx, effect, hostId);@@ -113,15 +153,16 @@ export async function recoverEffectPublication(engine: BrainEngine, effect: Persconst current = await lockedEffect(tx, effect);const record = current.recovery;if (!record) return;- if (!binding?.local_path || record.kind !== 'withdrawal-mirror' || record.sourceIncarnation !== current.source_incarnation- || String(binding.owner_epoch) !== record.ownerEpoch || !isWriteTargetContained(record.path, binding.local_path)- || !isWriteTargetContained(record.path, record.root) || !isWriteTargetContained(record.root, binding.local_path)- || resolve(record.root) !== resolve(join(binding.local_path, binding.relative_path))- || sha256(Buffer.from(record.after, 'base64')) !== record.afterHash) throw opError('recovery_required', 'Mirror recovery no longer belongs to this canonical binding.',+ const streamed = record.version === 2;+ if (!recordBelongs(record, current, binding) || (streamed ? record.staging?.publication?.hash !== record.afterHash+ : sha256(Buffer.from(record.after ?? '', 'base64')) !== record.afterHash)) throw opError('recovery_required', 'Mirror recovery no longer belongs to this canonical binding.',`The recorded mirror recovery for page ${record.slug} no longer matches source ${current.source_id}'s current canonical binding (owner epoch, root or file path changed), so recovery left the file untouched and the effect stays blocked. Inspect the owner and tell the user; repairing the binding is their decision.`,{ fix: effectStatusFix(current) });- await withFilesystemPublication([record.root], async () => cleanupRecoveryStaging(record));const actual = persistenceFileHash(record.path);+ const forward = actual === record.beforeHash && actual !== record.afterHash;+ // A streamed record's verified publication stage holds the bytes a forward publication renames into place.+ const cleanup = () => withFilesystemPublication([record.root], async () => cleanupRecoveryStaging(record));+ if (!streamed || !forward) await cleanup();if (actual !== record.beforeHash && actual !== record.afterHash) {throw opError('unexpected_file_bytes', 'Physical mirror recovery found unexpected bytes; the root remains blocked.',`The file of page ${record.slug} in source ${current.source_id} holds bytes that match neither its pre-withdrawal nor its mirrored version, so recovery did not overwrite it and the root stays blocked. Inspect the owner and ask the user which version to keep; do not delete the file to unblock it.`,@@ -132,20 +173,23 @@ export async function recoverEffectPublication(engine: BrainEngine, effect: Pers// A newer withdrawal may have committed independently of this root. Do// not publish the older prepared representation; render the latest next.if (!snapshot || snapshot.page.id !== record.pageId || snapshot.revision !== record.revision) {+ if (streamed && forward) await cleanup();await clearRecovery(tx, current);await tx.executeRaw(`UPDATE persistence_effects SET state='queued',execution_token=NULL,claim_expires_at=NULL,next_attempt_at=now(),error_code=NULL,updated_at=now() WHERE id=$1`, [current.id]);return;}- if (actual === record.beforeHash && actual !== record.afterHash) {+ if (forward) {await hooks.boundary?.('before_mirror_file');await withFilesystemPublication([record.root], async () => {- publishPersistenceFile({ path: record.path, root: record.root, content: Buffer.from(record.after, 'base64') }, record.staging?.publication?.path);+ if (streamed) publishStreamedStage(record);+ else publishPersistenceFile({ path: record.path, root: record.root, content: Buffer.from(record.after!, 'base64') }, record.staging?.publication?.path);if (record.mode !== null && existsSync(record.path)) chmodSync(record.path, record.mode);});await hooks.boundary?.('after_mirror_file');}- await materializePageSnapshot(tx, snapshot);+ // A segmented page's withdrawn rows were struck in its segments when the withdrawal committed: nothing to persist.+ if (!isSegmentedPage(snapshot.page)) await materializePageSnapshot(tx, snapshot);await clearRecovery(tx, current);// One page per transaction/cursor checkpoint bounds work and restart cost;// a retried parked target is consumed without rewinding the cursor.diff --git a/src/core/persistence/effects.ts b/src/core/persistence/effects.tsindex d1706ca832..bfd6ae9004 100644--- a/src/core/persistence/effects.ts+++ b/src/core/persistence/effects.ts@@ -32,7 +32,9 @@ import type { ResolvedColumn } from '../types.ts';import { acquireWorktree, getWorktreeBinding, type WorktreeBinding } from './ownership.ts';import { persistenceFileHash, transientDatabaseFailure } from './coordinator.ts';import { sha256 } from './digest.ts';-import { prepareFileTarget } from './page-prepare.ts';+import { prepareFileTarget, unreadPageFile } from './page-prepare.ts';+import { isStreamedContent } from './large-file.ts';+import { atomicStagingPath } from '../atomic-write.ts';import { isSourceDbOnlySlug } from './source-storage.ts';import { advanceEffectCursor, claimCoalescedGitEffects, claimPersistenceEffect, completeEffect, failEffect, parkEffect, renewPersistenceEffectClaim, requeueEffect, retryEffect, singleFileGitEffect } from './effect-journal.ts';import { guardEffectSource, recoverEffectPublication, reserveEffectRecovery } from './effect-recovery.ts';@@ -121,7 +123,9 @@ async function materializeAndAdvance(engine: BrainEngine, effect: PersistenceEffif (current?.revision !== snapshot.revision || current.page.id !== snapshot.page.id) throw opError('revision_conflict', 'The withdrawal page changed during preparation.',`Page ${snapshot.page.slug} in source ${effect.source_id} changed while its withdrawal was materializing; the effect worker picks up the new revision on its next pass. Nothing needs resubmitting.`,{ fix: effectStatusFix(effect) });- await materializePageSnapshot(tx, current);+ // A segmented page's withdrawn rows were struck in its segments when the withdrawal committed (withdrawal.ts,+ // purge.ts), so it has no overlay left to persist.+ if (!isSegmentedPage(current.page)) await materializePageSnapshot(tx, current);if (skipped) await recordSkippedTarget(tx, effect, { slug: current.page.slug, reason: skipped });await finishPage(tx, effect, current);});@@ -178,9 +182,8 @@ async function mirrorPage(engine: BrainEngine, effect: PersistenceEffect, bindin`Source ${effect.source_id} was replaced after this withdrawal mirror was queued, so the effect ends without writing; the new source has its own effects. Check the owner if files still look stale.`,{ fix: effectStatusFix(effect) });if (isMetafilePage(snapshot)) { await materializeAndAdvance(engine, effect, snapshot, opts.hostId, 'metafile'); return; }- // Wave B PR 1: a segmented body has no whole-body mirror yet (per-segment mirror in PR 2).- if (isSegmentedPage(snapshot.page)) { await skipTarget(engine, effect, snapshot, 'page_body_segmented'); return; }- const content = serializePageToMarkdown(snapshot.page, snapshot.tags);+ // A segmented page's file is streamed from its segments (unreadPageFile), never rendered as one string.+ const content = isSegmentedPage(snapshot.page) ? await unreadPageFile(engine, snapshot) : serializePageToMarkdown(snapshot.page, snapshot.tags);let file: Awaited<ReturnType<typeof prepareFileTarget>>;try {file = binding?.local_path ? await prepareFileTarget(engine, { ...effect, slug: snapshot.page.slug }, snapshot, content, opts.hostId, { allowMissing: true }) : undefined;@@ -194,11 +197,19 @@ async function mirrorPage(engine: BrainEngine, effect: PersistenceEffect, bindinawait materializeAndAdvance(engine, effect, snapshot, opts.hostId);return;}- const after = Buffer.from(content);- const record: EffectRecovery = { version: 1, kind: 'withdrawal-mirror', path: file.path, root: file.root,- beforeHash: file.expectedBeforeHash ?? null, afterHash: sha256(after), after: after.toString('base64'),+ const target = { kind: 'withdrawal-mirror' as const, path: file.path, root: file.root, beforeHash: file.expectedBeforeHash ?? null,mode: statSync(file.path).mode & 0o7777, ownerEpoch: String(binding!.owner_epoch), pageId: snapshot.page.id,- sourceIncarnation: snapshot.sourceIncarnation, slug: snapshot.page.slug, revision: snapshot.revision,+ sourceIncarnation: snapshot.sourceIncarnation, slug: snapshot.page.slug, revision: snapshot.revision };+ if (isStreamedContent(content)) {+ // Version 2: the file is staged by path and digest, never embedded; the reservation counts its one staged copy.+ const record: EffectRecovery = { ...target, version: 2, afterHash: content.hash, after: null,+ staging: { publication: { path: atomicStagingPath(file.path), hash: content.hash, bytes: content.bytes } } };+ await reserveEffectRecovery(engine, effect, record, Buffer.byteLength(JSON.stringify(record)) + content.bytes + 4096, opts.hostId);+ await recoverEffectPublication(engine, effect, opts.hostId, { boundary: opts.boundary, content });+ return;+ }+ const after = Buffer.from(content);+ const record: EffectRecovery = { ...target, version: 1, afterHash: sha256(after), after: after.toString('base64'),staging: { publication: recoveryStagingFile(file.path, after) } };await reserveEffectRecovery(engine, effect, record, Buffer.byteLength(JSON.stringify(record)) * 2 + 4096, opts.hostId);await recoverEffectPublication(engine, effect, opts.hostId, opts);@@ -253,11 +264,11 @@ async function gitPage(engine: BrainEngine, effect: PersistenceEffect, binding:if (!snapshot) { await completeEffect(engine, effect); return; }attempt.target = snapshot.page.slug;if (isMetafilePage(snapshot)) { await skipTarget(engine, effect, snapshot, 'metafile'); return; }- if (isSegmentedPage(snapshot.page)) { await skipTarget(engine, effect, snapshot, 'page_body_segmented'); return; }let file: Awaited<ReturnType<typeof prepareFileTarget>>;try {file = await prepareFileTarget(engine, { ...effect, slug: snapshot.page.slug }, snapshot,- snapshot.page.deleted_at ? null : serializePageToMarkdown(snapshot.page, snapshot.tags), opts.hostId, { allowMissing: true });+ snapshot.page.deleted_at ? null : isSegmentedPage(snapshot.page) ? await unreadPageFile(engine, snapshot) : serializePageToMarkdown(snapshot.page, snapshot.tags),+ opts.hostId, { allowMissing: true });} catch (error) {if (!isFileDatabaseDrift(error)) throw error;await skipTarget(engine, effect, snapshot, 'file_database_drift');diff --git a/src/core/persistence/fault-points.ts b/src/core/persistence/fault-points.tsindex e81f086bba..db8e344e30 100644--- a/src/core/persistence/fault-points.ts+++ b/src/core/persistence/fault-points.ts@@ -14,7 +14,11 @@ import type { WriteRequest } from './model.ts';export type PublicationBoundary = Parameters<NonNullable<PublicationHooks['boundary']>>[0];export type FaultPoint = `publication:${PublicationBoundary}` | `effect:${EffectKind}:mid` | 'effect:embedding:settle'- | 'effect_recovery:before_clear' | 'publication_recovery:before_clear' | 'sync:mid_checkpoint' | 'sync:before_group_admission' | 'sync:mid_waiver_run' | 'sync:prescreened' | 'consumer:prepared'+ | 'effect_recovery:before_clear' | 'publication_recovery:before_clear'+ // A streamed (version 2) withdrawal mirror (effect-recovery.ts): once its record is durable and before its file is+ // streamed into the publication stage, and after that step (the stage written and flushed, or left as it was found),+ // before the recovery transaction renames it.+ | 'effect_recovery:before_stage' | 'effect_recovery:staged' | 'sync:mid_checkpoint' | 'sync:before_group_admission' | 'sync:mid_waiver_run' | 'sync:prescreened' | 'consumer:prepared'| 'consumer:preparing' | 'lane:applied'// Before each claim attempt of the consumer, a FIFO claim or a lane head's: a stalling hook keeps this process from starting// another request or lane group meanwhile, while the requests it already holds run on.diff --git a/src/core/persistence/large-file.ts b/src/core/persistence/large-file.tsindex 93eb954b12..af6e8d6588 100644--- a/src/core/persistence/large-file.ts+++ b/src/core/persistence/large-file.ts@@ -212,6 +212,6 @@ export async function stageBeforeCopy(path: string, stage: RecoveryStagingFile,flushDirectory(dirname(stage.path));return true;}-function existsAt(path: string): boolean {+export function existsAt(path: string): boolean {try { lstatSync(path); return true; } catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false; throw error; }}diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.tsindex 1d5a656602..fefcec18dd 100644--- a/src/core/persistence/page-prepare.ts+++ b/src/core/persistence/page-prepare.ts@@ -545,8 +545,9 @@ async function prepareUnreadRestore(engine: BrainEngine, row: WriteRequest, snap/*** 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.+ * A withdrawal mirror of a segmented page (effects.ts, effect-recovery.ts) renders its file the same way.*/-async function unreadPageFile(engine: BrainEngine, snapshot: PageSnapshot): Promise<StreamedFileContent> {+export async function unreadPageFile(engine: BrainEngine, snapshot: PageSnapshot): Promise<StreamedFileContent> {const head = serializePageToMarkdown({ ...withoutBody(snapshot.page), compiled_truth: '', timeline: '' }, snapshot.tags).slice(0, -1);const ledger = snapshotLedger(snapshot);return StreamedFileContent.measure(engine, exec => segmentedExportMarkdown(exec, snapshot.page, ledger, head));diff --git a/src/core/persistence/staging.ts b/src/core/persistence/staging.tsindex 5b24bf6271..e0a772b0fc 100644--- a/src/core/persistence/staging.ts+++ b/src/core/persistence/staging.ts@@ -127,6 +127,17 @@ export function restoreBeforeStage(record: StagedRecovery & { mode: number | nulboundary?.('directory_flushed');}+/**+ * A version 2 mirror record's forward publication (effect-recovery.ts): its verified publication stage, streamed from+ * the page's segments, is renamed over the canonical path. A missing stage refuses (`unexpected_staging_bytes`).+ */+export function publishStreamedStage(record: StagedRecovery): void {+ const stage = record.staging?.publication;+ if (!stage || !stages(record).includes(stage)) throw blocked();+ if (!withVerifiedStage(stage, () => renameSync(stage.path, record.path))) throw blocked();+ flushDirectory(dirname(record.path));+}+/** 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/large-pages/purge-fact-segmented-preimage.test.ts b/test/large-pages/purge-fact-segmented-preimage.test.tsindex c660899e43..c8f377d579 100644--- a/test/large-pages/purge-fact-segmented-preimage.test.ts+++ b/test/large-pages/purge-fact-segmented-preimage.test.ts@@ -114,8 +114,8 @@ for (const kind of testBackends()) {expect(strip(after.segmented)).toEqual(strip(after.inline));expect(after.segmented.events.filter(e => e.moved).every(e => e.preimage === true)).toBe(true);expect(after.segmented.versions.some(v => v.claim)).toBe(false);- // The canonical file is left out: the purge's withdrawal-mirror effect does not rewrite a segmented page's file yet- // (src/core/persistence/effects.ts mirrorPage skips it with page_body_segmented), a gap outside this test.+ // The canonical file is left out: this test does not wait for the purge's withdrawal-mirror effect, which rewrites+ // it (test/large-pages/segmented-withdrawal-mirror.test.ts).const view = async (slug: string) => { const { file, ...rest } = await brain.view(slug); return rest; };expect(await view(SEGMENTED)).toEqual(await view(INLINE));expect(JSON.stringify(await view(SEGMENTED))).not.toContain(CLAIMS[SEGMENTED]);diff --git a/test/large-pages/segmented-withdrawal-mirror.test.ts b/test/large-pages/segmented-withdrawal-mirror.test.tsnew file mode 100644index 0000000000..a7a0da5f3f--- /dev/null+++ b/test/large-pages/segmented-withdrawal-mirror.test.ts@@ -0,0 +1,250 @@+/**+ * Switch-on blocker 1: a withdrawal mirrors a segmented page into its canonical file.+ *+ * 1. Protects: on a managed, file-backed source with `pages.segmented_storage` on, purge_fact (and forget_fact) of a+ * claim in a segmented page's facts fence rewrites the page's canonical file as the inline twin's is rewritten: the+ * file loses the purged claim (or shows the row forgotten) and keeps everything else, its bytes are the page's+ * streamed export (the serializer the inline path uses, over the segments), and the withdrawal's Git effect commits+ * it as the inline twin's is committed (for a purge, under the purge's subject).+ * The file is produced from the segments in pieces: every piece the mirror reads or stages is at most one segment+ * (`largeFileWork`), and the bytes it stages are exactly the file's. Its recovery record names the staged file by+ * path and digest instead of embedding it, and a mirror interrupted before or after writing that stage recovers+ * forward: the stage is written from the segments, or the written one renamed, exactly once.+ * 2. Fails when: the withdrawal-mirror effect skips a segmented page (`page_body_segmented`) and leaves the purged claim+ * on disk, the Git walk skips it, the mirror renders the body as one string (nothing staged in pieces), the record+ * embeds the file or reserves it twice, or recovery cannot finish an interrupted mirror.+ * 3. PGLite always; PostgreSQL when DATABASE_URL is set (test/postgres-unit-arms.txt). The switch is off for the inline+ * twin's writes and on for the segmented twin's. The interruptions are modelled at the `effect_recovery:before_stage`+ * and `effect_recovery:staged` seams (fault-points.ts) with a hook that throws once.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { createHash, randomUUID } from 'node:crypto';+import { readdirSync, readFileSync, statSync } from 'node:fs';+import { basename, join } from 'node:path';+import { exportBodyLedger, readExportPage, readExportWithdrawals, segmentedExportMarkdown } from '../../src/core/export-snapshot.ts';+import { serializeMarkdown, slugStampedFrontmatter } from '../../src/core/markdown.ts';+import { SEGMENT_MAX_BYTES } from '../../src/core/page-body/limits.ts';+import { runPersistenceEffects } from '../../src/core/persistence/effects.ts';+import { installFaultHook } from '../../src/core/persistence/fault-points.ts';+import { localHostId } from '../../src/core/persistence/identity.ts';+import { largeFileWork } from '../../src/core/persistence/large-file.ts';+import { durableGitRepo, gitAsync } from '../helpers/git-publication.ts';+import { openTwinBrain, type TwinBrain } from '../helpers/segmented-twins.ts';+import { testBackends } from '../helpers/test-backends.ts';+import { waitFor } from '../helpers/wait-for.ts';+import { withEnv } from '../helpers/with-env.ts';++const INLINE = 'people/ina-example';+const SEGMENTED = 'people/sei-example';+/** Each twin's claim has its own fingerprint, so one twin's purge never reaches the other's rows or effects. */+const CLAIMS: Record<string, string> = { [INLINE]: 'Twin Example locker code is 3306', [SEGMENTED]: 'Twin Example locker code is 7781' };+/** Each twin's claim that forget_fact withdraws (the row stays in the fence, marked forgotten). */+const FORGOTTEN: Record<string, string> = { [INLINE]: 'Twin Example bike lock is 5150', [SEGMENTED]: 'Twin Example bike lock is 8462' };+const KEPT = 'Twin Example adopted a narwhalbot';+/** The claim each modelled interruption's purge removes. */+const CRASH_CLAIMS = { 'effect_recovery:before_stage': 'Twin Example vault code is 1902', 'effect_recovery:staged': 'Twin Example vault code is 6640' };++const fileOf = (brain: TwinBrain, slug: string) => join(brain.root, slug + '.md');+const sha = (bytes: Buffer) => createHash('sha256').update(bytes).digest('hex');+/** A twin's file as `view` neutralizes it, with its own forgotten claim (the twins' only differing text) neutralized too. */+const twinFile = async (brain: TwinBrain, slug: string) => String((await brain.view(slug)).file).split(FORGOTTEN[slug]!).join('<forgotten>');+const resetWork = () => { for (const key of Object.keys(largeFileWork) as (keyof typeof largeFileWork)[]) largeFileWork[key] = 0; };+/** Staging leftovers (hidden `.<sha>.tmp.<uuid>` siblings) next to the twins' files. */+const stagingLeft = (brain: TwinBrain) => readdirSync(join(brain.root, 'people')).filter(name => name.includes('.tmp.'));++/**+ * Runs effect passes on this host until the source's mirror and Git effects have all settled; the persistence consumer+ * runs them too, so a claim it holds settles meanwhile. Past the deadline the assertions report the effects' state.+ */+const settle = (brain: TwinBrain, kind: 'pglite' | 'postgres') => waitFor(async () => {+ const [open] = await brain.engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM persistence_effects+ WHERE source_id=$1 AND kind IN ('withdrawal-mirror','git') AND (state<>'committed' OR recovery IS NOT NULL)`, [brain.sourceId]);+ if (!open!.n) return true;+ await withEnv(brain.env(), async () => {+ await brain.engine.executeRaw(`UPDATE persistence_effects SET next_attempt_at=now() WHERE source_id=$1 AND state='queued'`, [brain.sourceId]);+ await runPersistenceEffects(brain.engine, { engine: kind, embedding_disabled: true } as never, { hostId: localHostId(), limit: 20 });+ });+ return false;+}, { timeoutMs: 120_000, intervalMs: 100, label: 'the mirror and Git effects settled' }).catch(() => undefined);++/** The page's export, streamed as `gbrain export` streams a segmented page (export.ts), concatenated here only to compare. */+const exported = (brain: TwinBrain, slug: string) => brain.engine.transaction(async tx => {+ const [key] = await tx.executeRaw<{ id: string; source_id: string; slug: string }>(+ 'SELECT id::text AS id, source_id, slug FROM pages WHERE source_id=$1 AND slug=$2', [brain.sourceId, slug]);+ const withdrawals = await readExportWithdrawals(tx, brain.sourceId);+ const { page, tags } = await readExportPage(tx, key!, withdrawals);+ const head = serializeMarkdown(slugStampedFrontmatter(page.slug, page.frontmatter ?? {}), '', '', { type: page.type, title: page.title, tags }).slice(0, -1);+ const parts: Buffer[] = [];+ for await (const piece of segmentedExportMarkdown(tx, page, exportBodyLedger(page.slug, withdrawals), head)) parts.push(Buffer.from(piece));+ return Buffer.concat(parts);+});++const effectsOf = async (brain: TwinBrain, requestId: string) => (await brain.engine.executeRaw<{ kind: string; state: string; error_code: string | null; data: any }>(+ `SELECT e.kind, e.state, e.error_code, e.data FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id+ WHERE r.request_id=$1::uuid AND e.kind IN ('withdrawal-mirror','git') ORDER BY e.kind`, [requestId]))+ .map(e => ({ kind: e.kind, state: e.state, error: e.error_code, skipped: (typeof e.data === 'string' ? JSON.parse(e.data) : e.data)?.skipped ?? [] }));+const SETTLED = [{ kind: 'git', state: 'committed', error: null, skipped: [] }, { kind: 'withdrawal-mirror', state: 'committed', error: null, skipped: [] }];++async function purge(brain: TwinBrain, kind: 'pglite' | 'postgres', slug: string, claim: string) {+ const [fact] = await brain.engine.executeRaw<{ id: number }>('SELECT id FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 AND fact=$3', [brain.sourceId, slug, claim]);+ const dry = await brain.call('purge_fact', { id: Number(fact!.id), dry_run: true }, slug);+ expect(dry.confirm_token).toBeString();+ const requestId = randomUUID();+ const done = await brain.call('purge_fact', { id: Number(fact!.id), confirm: dry.confirm_token, expected_revision: dry.expected_revision, request_id: requestId }, slug);+ expect(done.state).toBe('committed');+ await settle(brain, kind);+ return { requestId, hash8: String(done.purge.hash8) };+}++async function extract(brain: TwinBrain, slug: string, facts: string[]) {+ brain.setChatReply(JSON.stringify({ facts: facts.map(fact => ({ fact, kind: 'fact', entity: slug, confidence: 1, notability: 'high' })) }));+ expect(await brain.call('extract_facts', { turn_text: 'Synthetic meeting record. ' + facts.join('. ') + '.', visibility: 'world', valid_from: '2026-10-15T00:00:00Z' }, slug))+ .toMatchObject({ inserted: facts.length });+}++for (const kind of testBackends()) {+ describe(kind + ': a withdrawal mirrors a segmented page into its canonical file', () => {+ let brain: TwinBrain;++ beforeAll(async () => {+ brain = await openTwinBrain(kind, [INLINE], async seed => {+ await seed.setSwitch(false);+ await seed.put(INLINE, 1_100_000);+ await seed.setSwitch(true);+ await seed.put(SEGMENTED, 1_100_000);+ });+ for (const slug of [INLINE, SEGMENTED]) await extract(brain, slug, [CLAIMS[slug]!, FORGOTTEN[slug]!, KEPT]);+ expect([await brain.storageOf(INLINE), await brain.storageOf(SEGMENTED)]).toEqual(['inline', 'segmented']);+ await settle(brain, kind);+ // The checkout becomes a durability-hardened repository holding both files, so each purge's Git effect commits for real.+ durableGitRepo(brain.root, [INLINE + '.md', SEGMENTED + '.md']);+ }, 600_000);++ afterAll(() => brain.close(), 120_000);++ test('purge_fact rewrites the segmented file without the claim, as the inline twin\'s, streamed and committed', async () => {+ for (const slug of [INLINE, SEGMENTED]) expect(readFileSync(fileOf(brain, slug), 'utf8')).toContain(CLAIMS[slug]!);++ const inline = await purge(brain, kind, INLINE, CLAIMS[INLINE]!);+ resetWork();+ const segmented = await purge(brain, kind, SEGMENTED, CLAIMS[SEGMENTED]!);+ const work = { ...largeFileWork };++ // Neither twin's mirror or Git walk passed its page by: both effects committed with nothing skipped.+ expect(await effectsOf(brain, segmented.requestId)).toEqual(await effectsOf(brain, inline.requestId));+ expect(await effectsOf(brain, segmented.requestId)).toEqual(SETTLED);++ // The file lost the purged claim, kept the rest, and is the inline twin's file and the page's streamed export.+ const file = readFileSync(fileOf(brain, SEGMENTED));+ expect(file.toString('utf8')).not.toContain(CLAIMS[SEGMENTED]!);+ expect(file.toString('utf8')).toContain(KEPT);+ expect(await twinFile(brain, SEGMENTED)).toBe(await twinFile(brain, INLINE));+ expect(file.equals(await exported(brain, SEGMENTED))).toBe(true);+ expect(stagingLeft(brain)).toEqual([]);++ // Git: each twin's file is committed by its purge's Git effect, under the purge's subject, and nothing is left dirty.+ for (const [slug, receipt] of [[INLINE, inline], [SEGMENTED, segmented]] as const) {+ expect((await gitAsync(brain.root, 'log', '-1', '--format=%s', '--', slug + '.md')).trim()).toBe(`gbrain: purge fact ${receipt.hash8}`);+ expect(await gitAsync(brain.root, 'status', '--porcelain', '--', slug + '.md')).toBe('');+ expect(await gitAsync(brain.root, 'show', `HEAD:${slug}.md`)).toBe(readFileSync(fileOf(brain, slug), 'utf8'));+ }++ // Streamed: the mirror staged exactly the file's bytes, and no piece it read or wrote was over one segment.+ expect(work.bytesWritten).toBe(file.length);+ expect(work.bytesRead).toBeGreaterThanOrEqual(work.bytesWritten);+ expect(work.largestPiece).toBeGreaterThan(0);+ expect(work.largestPiece).toBeLessThanOrEqual(SEGMENT_MAX_BYTES);+ }, 600_000);++ test('forget_fact rewrites the segmented file with the row withdrawn, as the inline twin\'s, and commits it', async () => {+ const before = { [INLINE]: readFileSync(fileOf(brain, INLINE), 'utf8'), [SEGMENTED]: readFileSync(fileOf(brain, SEGMENTED), 'utf8') };+ const receipts: Record<string, string> = {};+ for (const slug of [INLINE, SEGMENTED]) {+ const [fact] = await brain.engine.executeRaw<{ id: number }>('SELECT id FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 AND fact=$3', [brain.sourceId, slug, FORGOTTEN[slug]]);+ receipts[slug] = randomUUID();+ expect(await brain.call('forget_fact', { id: Number(fact!.id), request_id: receipts[slug] }, slug)).toMatchObject({ state: 'committed' });+ if (slug === INLINE) resetWork();+ await settle(brain, kind);+ }+ const work = { ...largeFileWork };++ expect(await effectsOf(brain, receipts[SEGMENTED]!)).toEqual(await effectsOf(brain, receipts[INLINE]!));+ expect(await effectsOf(brain, receipts[SEGMENTED]!)).toEqual(SETTLED);+ const file = readFileSync(fileOf(brain, SEGMENTED));+ expect(file.toString('utf8')).not.toBe(before[SEGMENTED]);+ expect(readFileSync(fileOf(brain, INLINE), 'utf8')).not.toBe(before[INLINE]);+ expect(await twinFile(brain, SEGMENTED)).toBe(await twinFile(brain, INLINE));+ expect(file.equals(await exported(brain, SEGMENTED))).toBe(true);+ expect(stagingLeft(brain)).toEqual([]);+ for (const slug of [INLINE, SEGMENTED]) {+ expect(await gitAsync(brain.root, 'status', '--porcelain', '--', slug + '.md')).toBe('');+ expect(await gitAsync(brain.root, 'show', `HEAD:${slug}.md`)).toBe(readFileSync(fileOf(brain, slug), 'utf8'));+ }+ expect(work.bytesWritten).toBe(file.length);+ expect(work.largestPiece).toBeGreaterThan(0);+ expect(work.largestPiece).toBeLessThanOrEqual(SEGMENT_MAX_BYTES);+ }, 600_000);+ });++ describe(kind + ': an interrupted streamed mirror recovers forward', () => {+ let brain: TwinBrain;++ beforeAll(async () => {+ brain = await openTwinBrain(kind, [], async seed => {+ await seed.setSwitch(true);+ await seed.put(SEGMENTED, 1_100_000);+ });+ await extract(brain, SEGMENTED, [...Object.values(CRASH_CLAIMS), KEPT]);+ expect(await brain.storageOf(SEGMENTED)).toBe('segmented');+ await settle(brain, kind);+ }, 600_000);++ afterAll(() => brain.close(), 120_000);++ for (const seam of Object.keys(CRASH_CLAIMS) as (keyof typeof CRASH_CLAIMS)[]) {+ test(`a mirror interrupted at ${seam} publishes on recovery, staged once`, async () => {+ const claim = CRASH_CLAIMS[seam];+ expect(readFileSync(fileOf(brain, SEGMENTED), 'utf8')).toContain(claim);+ const hits: { stages: string[]; recovery: any; bytes: number }[] = [];+ installFaultHook(async (point, detail) => {+ if (point !== seam || hits.length) return;+ const [row] = await brain.engine.executeRaw<{ recovery: unknown; bytes: string }>(+ 'SELECT recovery, recovery_bytes::text AS bytes FROM persistence_effects WHERE id=$1', [detail.effectId]);+ hits.push({ stages: stagingLeft(brain), recovery: typeof row!.recovery === 'string' ? JSON.parse(row!.recovery) : row!.recovery, bytes: Number(row!.bytes) });+ throw new Error(`modelled crash at ${seam}`);+ });+ resetWork();+ let receipt: Awaited<ReturnType<typeof purge>>;+ try { receipt = await purge(brain, kind, SEGMENTED, claim); } finally { installFaultHook(undefined); }+ const work = { ...largeFileWork };+ const file = readFileSync(fileOf(brain, SEGMENTED));++ // The interruption left a durable record naming the stage by path and digest, never the file's bytes, reserving+ // the file once; before the stage was written nothing was staged, after it the flushed stage was on disk.+ expect(hits).toHaveLength(1);+ const [hit] = hits;+ expect(hit!.recovery).toMatchObject({ version: 2, kind: 'withdrawal-mirror', after: null, afterHash: sha(file),+ staging: { publication: { hash: sha(file), bytes: file.length } } });+ expect(hit!.bytes).toBe(Buffer.byteLength(JSON.stringify(hit!.recovery)) + file.length + 4096);+ expect(hit!.stages).toEqual(seam === 'effect_recovery:staged' ? [basename(hit!.recovery.staging.publication.path)] : []);++ // Recovery finished the mirror forward: the file is the page's export without the claim, nothing is left staged+ // or reserved, and the effects settled.+ expect(file.toString('utf8')).not.toContain(claim);+ expect(file.toString('utf8')).toContain(KEPT);+ expect(file.equals(await exported(brain, SEGMENTED))).toBe(true);+ expect(await effectsOf(brain, receipt!.requestId)).toEqual(SETTLED);+ expect(stagingLeft(brain)).toEqual([]);+ await waitFor(async () => (await brain.engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM persistence_requests+ WHERE source_id=$1 AND recovery IS NOT NULL`, [brain.sourceId]))[0]!.n === 0, { timeoutMs: 30_000, label: 'request recovery records cleared' });+ const counters = await brain.engine.executeRaw<{ bytes: string }>('SELECT recovery_bytes::text AS bytes FROM persistence_counters');+ expect(counters.every(row => Number(row.bytes) === 0)).toBe(true);++ // Staged exactly once, in pieces of at most one segment: from the segments on recovery, or the flushed stage renamed.+ expect(work.bytesWritten).toBe(file.length);+ expect(work.largestPiece).toBeGreaterThan(0);+ expect(work.largestPiece).toBeLessThanOrEqual(SEGMENT_MAX_BYTES);+ }, 600_000);+ }+ });+}diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 5a7bc953e8..0394e1b330 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -170,6 +170,7 @@ test/large-pages/segmented-think-compile-leads.serial.test.tstest/large-pages/segmented-timeline-heap.test.tstest/large-pages/segmented-timeline-retract-versions.test.tstest/large-pages/segmented-versions.test.ts+test/large-pages/segmented-withdrawal-mirror.test.tstest/large-pages/segmented-withdrawn-fence-delete.test.tstest/large-pages/streamed-import-drift.test.tstest/large-pages/v252-master-reader-compat.test.ts