Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

large pages hardening (f)(g): name the split-fence row limit in withdrawal_capacity; stop the file digest at the fence bound

garrytanf4f3615b3526
diff --git a/docs/architecture/key-files/core-services-2-continued.md b/docs/architecture/key-files/core-services-2-continued.md
index ee8d3d6b5e..d05ca9ad94 100644
--- a/docs/architecture/key-files/core-services-2-continued.md
+++ b/docs/architecture/key-files/core-services-2-continued.md
@@ -27,7 +27,7 @@ The page-state concurrency foundation under `src/core/page-state/` and the share
- `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` (read-range.ts) 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: streamed into an in-progress sibling (`streamingStagePath`, `<stage>.streaming`), verified, fsynced and only then renamed to the stage's name, so a stream a crash cut short is never at that name and recovery removes it unread; a mismatch removes the stream and refuses `revision_conflict`; seam `large_file:stage_streaming` after each piece), 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. `prepareFileTarget` reads the prior file through `FileBytes` at any size for a page stored in segments or a streamed target (never `readFileSync` whole), so its drift check reads in pieces of at most a segment. 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/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). `overlaidFileBodyDigests` overlays the file one complete fence block at a time; inside an open block a read stops at FENCE_MAX_BYTES plus `FENCE_READ_LOOKAHEAD` (4 bytes), so an over-bound fence refuses `page_body_segmented` without reading a further segment (`test/pathological/lp-g-file-digest-fence-bound.test.ts`). 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`.
- `src/core/page-window/document.ts` — the one read projection every remote window, outline and lead slices: `projectPageText` (fence overlay split, `sanitizeRemoteBody` + `credentialSafeProjection`, timeline after `TIMELINE_SEPARATOR`), `pageDocument` / `readPageDocument` (UTF-8 bytes + timeline byte offset, with the page's fence overlay), `chunkDocumentSpan` + `spanHoldsChunk` (a chunk's stored `projected_byte_*` span mapped into the document and verified), `boundedProjectedPrefix`, `locateChunksByStoredSpans` (byte spans to string offsets in one pass), `DEFAULT_INLINE_BODY_BYTES` (256 KB).
diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.md
index ba6a597c12..ab90f12111 100644
--- a/docs/architecture/key-files/core-services-2.md
+++ b/docs/architecture/key-files/core-services-2.md
@@ -18,7 +18,7 @@ Fact and page purge modules (`src/core/facts/purge*.ts`, `deletion-inventory.ts`
- `src/core/facts/queue.ts:FactsQueue.drainPending` — method `drainPending({timeout?: number}): Promise<{drained, unfinished}>`. Semantically distinct from `shutdown()` (which calls `this.internalAbort.abort()` and would abort the very facts:absorb worker trying to log its post-completion event). Drain lets in-flight finish; only the wait is bounded. Default timeout `1000ms` so commands that don't enqueue facts pay one fast 0ms check before exit. `src/cli.ts` op-dispatch finally block awaits `getFactsQueue().drainPending({timeout: 1000})` BEFORE `engine.disconnect()`. Lazy-import keeps the facts-queue module off the hot path for ops that never touch it. Prevents a trailing `'No database connection'` line after `gbrain capture` (a post-page-write facts:absorb outliving the CLI process). Pinned by `test/facts-queue-drain-pending.test.ts` (4 cases: empty fast-path, in-flight settled without abort, unfinished count on timeout, default timeout = 1000ms).
-- `src/core/facts/withdrawal.ts` + `withdrawal-schema.ts` + `withdrawal-discovery.ts` — durable withdrawal key is `(source_id, visibility, subject, SHA256(normalized claim))`. `subject` is the forgotten row's `entity_slug`; '*' (all subjects) covers subjectless facts and rows recorded before v169. A withdrawal matches when `subject = '*' OR subject = entity_slug`, so forgetting one entity's claim never touches the same claim about another entity. Fence rows belong to their page's entity: the import overlay, prepared-import check (`preserveWithdrawnFenceRows` / `assertPreparedFactWithdrawals`), snapshot overlay and Markdown export match on the page slug. `updateSlug` (both engines, via `moveSlugBindings`) and the phantom-redirect merge move subjects to the new slug (`MOVE_WITHDRAWAL_SUBJECT_SQL`), so rename and index recreation do not restore a claim. Normalization (`gbrain_fact_normalize`, mirrored in JS by `normalizeLoweredClaim`) folds case, whitespace and an explicit punctuation set, not meaning (migration v174); `+`, `#` and in-word dots are kept ("C++" ≠ "C"); pre-v174 ledger rows keep their exact `gbrain_fact_fingerprint_v1` hash and every ledger match checks both. v174 adds a folded row wherever a fact row still holds the claim text, expires facts that became matching, and builds `idx_facts_withdrawal_fingerprint` (the fingerprint inlines normalization: index builds use a restricted search_path). Discovery (`withdrawal-discovery.ts`) is keyed on claim, subject and fingerprint: SQL shortlists pages and chunks whose lowercased text contains every normalized token of the claim (one `lower(text) LIKE ALL(patterns)` fold per text with `%`, `_` and `\` escaped, #6270; necessary for any match; nothing is normalized in SQL), streams them by keyset, then verifies exactly; a subject-scoped claim reads only its entity's page plus provenance of that entity's facts. There is no source-inventory limit (#5674): refusals come from the matched set (>256 pages, reported with the count and sample slugs), the 10s scan budget, per-batch input limits or matching malformed evidence. Only an existing withdrawal covering the same subject skips discovery. Only affected page revisions/chunks are invalidated. The source row lock serializes withdrawal with the facts trigger; the trigger prevents insert/update from reactivating a matching claim. Import and snapshot overlays cover every complete legacy fence, including inactive rows; withdrawal markers precede preserved context and retain earlier expiry dates before hashing/chunking; malformed fences retain their existing diagnostics and the DB trigger still protects derived facts. `writeSingleFact` refuses an identical withdrawn claim for the resolved entity before embedding, using the protocol error envelope. `writeFactsToFence` rechecks each input under the page lock and drops claims withdrawn for the page's entity (reporting `withdrawnSkipped`), and the backstop skips them in phase 1, so a withdrawn claim is never appended to Markdown as an active row (audit B-10). TTL/supersession expiry creates no withdrawal; backfill trusts only explicit `forgotten:` markers; Markdown-only copies do not preserve DB-only withdrawals. Pinned by `test/facts-withdrawal-subject.test.ts`, `test/fact-withdrawal-normalized.test.ts`, `test/withdrawal-bounded-safety.test.ts` (both engines) and the Postgres scale gate `test/e2e/fact-withdrawal-scope-postgres.test.ts`. `recordFactWithdrawal(…, { semanticReview })` also queues a `withdraw` review row in `decide_review_queue` inside the same transaction when `decide.slots.conflict.review_withdraw` is on (unset counts as on; `reviewWithdrawOn`) and the caller did not opt out, and runs every `registerWithdrawalInvalidation` hook in that transaction for projections beyond pages and chunks. `src/core/facts/similar-active.ts` — `similarActiveAfterForget`: after a committed `forget`, up to five active facts with the same source, entity and visibility (world only for remote callers) at cosine >= 0.80 to the withdrawn fact's stored embedding, returned as ids and scores with the overnight review state and a `next` line (zero model calls; pinned by `test/decide/review-withdraw.serial.test.ts`). Segmented affected pages are struck segment by segment through `rewriteLiveSegmentedFences` (a new generation whose flip replaces only the rewritten occurrences' chunks); discovery also scans live manifest rows with `facts_slots`, reading only each slot's bytes, and joins a fence a forced cut split from its slots' bytes (`splitFactsFences`; above `PAGE_MAX_BYTES` it refuses with `page_body_segmented`), so a private row, which never reaches chunks, is found wherever the cut falls.
+- `src/core/facts/withdrawal.ts` + `withdrawal-schema.ts` + `withdrawal-discovery.ts` — durable withdrawal key is `(source_id, visibility, subject, SHA256(normalized claim))`. `subject` is the forgotten row's `entity_slug`; '*' (all subjects) covers subjectless facts and rows recorded before v169. A withdrawal matches when `subject = '*' OR subject = entity_slug`, so forgetting one entity's claim never touches the same claim about another entity. Fence rows belong to their page's entity: the import overlay, prepared-import check (`preserveWithdrawnFenceRows` / `assertPreparedFactWithdrawals`), snapshot overlay and Markdown export match on the page slug. `updateSlug` (both engines, via `moveSlugBindings`) and the phantom-redirect merge move subjects to the new slug (`MOVE_WITHDRAWAL_SUBJECT_SQL`), so rename and index recreation do not restore a claim. Normalization (`gbrain_fact_normalize`, mirrored in JS by `normalizeLoweredClaim`) folds case, whitespace and an explicit punctuation set, not meaning (migration v174); `+`, `#` and in-word dots are kept ("C++" ≠ "C"); pre-v174 ledger rows keep their exact `gbrain_fact_fingerprint_v1` hash and every ledger match checks both. v174 adds a folded row wherever a fact row still holds the claim text, expires facts that became matching, and builds `idx_facts_withdrawal_fingerprint` (the fingerprint inlines normalization: index builds use a restricted search_path). Discovery (`withdrawal-discovery.ts`) is keyed on claim, subject and fingerprint: SQL shortlists pages and chunks whose lowercased text contains every normalized token of the claim (one `lower(text) LIKE ALL(patterns)` fold per text with `%`, `_` and `\` escaped, #6270; necessary for any match; nothing is normalized in SQL), streams them by keyset, then verifies exactly; a subject-scoped claim reads only its entity's page plus provenance of that entity's facts. There is no source-inventory limit (#5674): refusals come from the matched set (>256 pages, reported with the count and sample slugs), the 10s scan budget, per-batch input limits or matching malformed evidence. One facts fence a forced cut splits is checked as one batch; over 16,384 rows or 8 MiB it refuses with reason `split_fence_rows`, naming the page and the fence (`test/pathological/lp-f-split-fence-withdrawal-capacity.test.ts`). Only an existing withdrawal covering the same subject skips discovery. Only affected page revisions/chunks are invalidated. The source row lock serializes withdrawal with the facts trigger; the trigger prevents insert/update from reactivating a matching claim. Import and snapshot overlays cover every complete legacy fence, including inactive rows; withdrawal markers precede preserved context and retain earlier expiry dates before hashing/chunking; malformed fences retain their existing diagnostics and the DB trigger still protects derived facts. `writeSingleFact` refuses an identical withdrawn claim for the resolved entity before embedding, using the protocol error envelope. `writeFactsToFence` rechecks each input under the page lock and drops claims withdrawn for the page's entity (reporting `withdrawnSkipped`), and the backstop skips them in phase 1, so a withdrawn claim is never appended to Markdown as an active row (audit B-10). TTL/supersession expiry creates no withdrawal; backfill trusts only explicit `forgotten:` markers; Markdown-only copies do not preserve DB-only withdrawals. Pinned by `test/facts-withdrawal-subject.test.ts`, `test/fact-withdrawal-normalized.test.ts`, `test/withdrawal-bounded-safety.test.ts` (both engines) and the Postgres scale gate `test/e2e/fact-withdrawal-scope-postgres.test.ts`. `recordFactWithdrawal(…, { semanticReview })` also queues a `withdraw` review row in `decide_review_queue` inside the same transaction when `decide.slots.conflict.review_withdraw` is on (unset counts as on; `reviewWithdrawOn`) and the caller did not opt out, and runs every `registerWithdrawalInvalidation` hook in that transaction for projections beyond pages and chunks. `src/core/facts/similar-active.ts` — `similarActiveAfterForget`: after a committed `forget`, up to five active facts with the same source, entity and visibility (world only for remote callers) at cosine >= 0.80 to the withdrawn fact's stored embedding, returned as ids and scores with the overnight review state and a `next` line (zero model calls; pinned by `test/decide/review-withdraw.serial.test.ts`). Segmented affected pages are struck segment by segment through `rewriteLiveSegmentedFences` (a new generation whose flip replaces only the rewritten occurrences' chunks); discovery also scans live manifest rows with `facts_slots`, reading only each slot's bytes, and joins a fence a forced cut split from its slots' bytes (`splitFactsFences`; above `PAGE_MAX_BYTES` it refuses with `page_body_segmented`), so a private row, which never reaches chunks, is found wherever the cut falls.
- `src/core/facts/write-single.ts` — `writeSingleFact(fact, ctx)`: the zero-LLM single-fact seam behind `remember`. `runFactsPipeline` is extraction-first (LLM-gated) and cannot back a pre-formed fact; this reuses the pipeline's post-extraction stages directly: resolve → embedding-cosine dedup (per-model threshold) → fence-first write with the same legacy DB-only fallbacks (thin-client, unparented, stub-guard). Supersession: deterministic rule — same entity_slug + same kind + similarity ≥ threshold + DIFFERENT text ⇒ the new fact supersedes (fence path: append new + `forgetFactInFence(old, { supersededBy })`, which strikes the old row with a page-local `#N` supersession reference and records no withdrawal, + superseded_by link; DB path: engine insertFact supersedeId). Pinned by `test/facts-supersede-not-withdrawal.test.ts`. Provenance lands on NewFact.source verbatim (no FactsBackstopCtx). No embedding provider ⇒ `degraded_dedup: true` (near-duplicates may insert — documented). `isNullLikeEntity(entity)` (exported) normalizes null-like entity tokens (`"null"`, `"undefined"`, `"none"`, `"n/a"`, `"nil"`, `"-"`, empty/whitespace) to ABSENT before resolution — applied here rather than only at the verb boundary so EVERY writeSingleFact caller gets the guard and the `resolved?.slug ?? entityRef` fallback can never adopt `"null"` as a slug. On a managed brain, after the withdrawal check and embedding, the fact publishes through `publishManagedEntityFacts` (`src/core/facts/managed-fact-write.ts`, the `managed_facts_entity` intent: fence row, index row and file together, dedup at publication, and the same-kind near-duplicate supersession rule via the intent's `supersede` flag, which strikes the old fence row and expires and links the old fact in the same transaction; an explicit per-fact context is kept; an entity without a live page lands database-only on `memory/unattributed` and, through the intent's opt-in `attribute_fallback` flag, which only writeSingleFact sets, keeps the resolver's fallback slug as `entity_slug` with no row number, so dedup and withdrawal checks stay per entity; the facts backstop never sets it and keeps those rows unattributed). `writeFactsToFence` (`fence-write.ts`) takes the same path on a managed brain, after dropping withdrawn claims. A fence append refused because the page's facts fence does not parse cleanly rethrows the typed `fenceRefusal` (`invalid_fence` / `target_fence_malformed`). On an unmanaged brain, #6398 (fix wave 13): when the page's file is missing but a source-scoped row exists (live, with a vanished `source_path` file, or tombstoned), `writeFactsToFence` returns `stubGuardBlocked` with audit reason `db_only_page` and the caller records the facts DB-only, so no stub overwrites the DB body or resurrects a deleted page; an unreadable row returns `fenceWriteFailed`; the #4872 page mirror runs only for a body read from a real file. Doctor `stub_guard_24h` (`commands/doctor/checks/local-audits.ts`) counts `unprefixed`, `fallback_resolution` and `db_only_page` separately; `db_only_page` never feeds the WARN threshold. Tests: `test/fence-write-db-only.test.ts`, `test/doctor-stub-guard.test.ts`.
- `src/core/facts/managed-fact-write.ts` — `publishManagedEntityFacts(engine, sourceId, entity, facts)` builds one managed facts session per visibility (request identity derived from the write, so a retried job replays its receipt; `attributeFallback` sets the intent's `attribute_fallback`), keeps a caller's vector only when it matches the brain's facts embedding signature, and returns ids in input order; `managedFactWritePreflight` runs the same session checks before a caller's model call.
diff --git a/docs/guides/concurrent-writes.md b/docs/guides/concurrent-writes.md
index a071ce388f..3acd067c3d 100644
--- a/docs/guides/concurrent-writes.md
+++ b/docs/guides/concurrent-writes.md
@@ -503,6 +503,12 @@ on providers. `withdrawal_capacity` or `withdrawal_provenance` refuses the
attempt before ledger, expiry, revision or chunk changes. Matching malformed
fences need canonical repair.
+A facts fence that crosses a forced segment cut is read whole and checked in
+one batch, so one such fence over 16,384 rows (or 8 MiB of rows to check)
+refuses `withdrawal_capacity` with reason `split_fence_rows`, naming the page
+and the fence's row count. Split that fence into fences of at most 16,384 rows,
+write the page again, then retry.
+
When the claim itself is carried by more than 256 pages, the refusal names the
matched count and up to 20 matched pages. Reduce the matched set, then retry:
forget the entity-scoped copies of the fact first (each withdrawal changes only
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 3d3753be42..9139625085 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -903,6 +903,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.299.0', text: 'Doctor `segmented_storage` no longer tells you to upgrade this host when the only writes holding segmented storage off are this host\'s own from before its upgrade and the upgraded gbrain has since made the same kind of write (the same import or sync type, resident kind or managed principal), after the last of them: it reports the hold as information with the time it clears. Another host, an older `serve` or worker still running on this host, or an older write this build has not matched (a cron job or `npx` run on this host) keeps the warning and the `gbrain upgrade` fix.' },
{ since: '0.60.299.0', text: 'Managed sync of a Markdown file over 24 MiB whose origin another page records (a page renamed with its file) now imports it into that page, as for a smaller file, instead of failing it `revision_conflict` ("A different page already owns this file identity") and stopping the source\'s sync at it.' },
{ since: '0.60.299.0', text: '`gbrain repair stuck-recovery` now resolves a page recovery whose file is over 24 MiB, which used to be listed as refused (`recovery_large_file_unsupported`) with no exit while it stopped every write on its source\'s worktree. The preview lists it with both fingerprints and the state of the staged copy of the prior file, backs up both versions, and writes a summary instead of a full diff (both hashes and sizes, the first byte where they differ, and a window of at most 1 KiB); `--apply --expect <hash> --keep prior|disk --yes` resolves it as it does a small file. Every read, hash and copy of the large file is done in pieces of at most a segment. When the staged copy of the prior file is missing or damaged, `--keep prior` refuses with `recovery_prior_stage_unavailable`, whose fix is the `--keep disk` apply, which keeps a damaged copy in the backup directory and removes it from the checkout.' },
+ // Large-pages hardening (f).
+ { since: 'TBD', text: 'A withdrawal (`forget`, `forget_fact`, `purge_fact`) of a claim in a facts fence that crosses a forced segment cut, when that one fence holds more than 16,384 rows (or more than 8 MiB of rows to check), is still refused `withdrawal_capacity` (the bound is unchanged), but the refusal now says why: it carries reason `split_fence_rows`, names the page, the fence\'s row count and the limit, and its fix asks you to split that fence into fences of at most 16,384 rows and write the page again. It used to say discovery "could not prove a bounded complete target set" and told you not to split the source.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/facts/withdrawal-discovery.ts b/src/core/facts/withdrawal-discovery.ts
index 24d37bf8d6..71efaaefc6 100644
--- a/src/core/facts/withdrawal-discovery.ts
+++ b/src/core/facts/withdrawal-discovery.ts
@@ -1,13 +1,14 @@
import type { BrainEngine } from '../engine.ts';
-import { OperationError } from '../ops/contract.ts';
+import { OperationError, opError } from '../ops/contract.ts';
import { getCode } from '../retry-matcher.ts';
import { parseRowCells, isSeparatorRow, stripStrikethrough } from '../fence-shared.ts';
import { withdrawalFenceBlocks, ambiguousWithdrawalFenceSegments } from './withdrawal-overlay.ts';
import { fenceTooLargeError, readStoredFence } from '../page-body/read-range.ts';
import { FENCE_MAX_BYTES } from '../page-body/limits.ts';
+import { FACTS_FENCE_BEGIN, FACTS_FENCE_END } from '../facts-fence.ts';
import type { BodyRegion } from '../page-body/types.ts';
-export const WITHDRAWAL_LIMITS = { targets: 256, targetBytes: 1024 * 1024, scanMs: 10_000, batch: 128 } as const;
+export const WITHDRAWAL_LIMITS = { targets: 256, targetBytes: 1024 * 1024, scanMs: 10_000, batch: 128, matchRows: 16_384, matchBytes: 8 * 1024 * 1024 } as const;
export interface WithdrawalTarget { slug: string; page_id: number; revision: string }
/** `subject` is the ledger subject ('*' = every entity); `claim` is the fact text when the caller already holds it. */
export interface WithdrawalClaim { visibility: string; fact_hash: string; subject?: string | null; claim?: string | null }
@@ -39,6 +40,21 @@ export function ambiguousFenceClaims(body: string): Array<{ claim: string; visib
return claims;
}
+/**
+ * One facts fence a forced cut split is matched whole, in one check bounded by WITHDRAWAL_LIMITS.matchRows/matchBytes:
+ * a fence over that bound refuses, naming the fence and how to bring it under the bound.
+ */
+function splitFenceTooLarge(sourceId: string, slug: string, rows: number, bytes: number): never {
+ throw opError('withdrawal_capacity',
+ `Page ${slug} (source ${sourceId}) has a facts fence split across stored segments with ${rows} rows (${bytes} bytes to check), over the ${WITHDRAWAL_LIMITS.matchRows}-row / ${WITHDRAWAL_LIMITS.matchBytes / 1024 ** 2} MiB limit withdrawal discovery checks one split fence within. Source size and the withdrawal ledger are not the limit; this fence is. Nothing was committed; earlier durable intent remains retained.`,
+ `Split that facts fence into smaller fences of at most ${WITHDRAWAL_LIMITS.matchRows} rows each (close it with ${FACTS_FENCE_END}, open the next with ${FACTS_FENCE_BEGIN} and the header row), write the page again, then retry. ${RECOVERY}`,
+ { reason: 'split_fence_rows', why: `Discovery reads a fence a forced segment cut splits whole and checks every row of it at once, up to ${WITHDRAWAL_LIMITS.matchRows} rows.`,
+ fix: { ask_user: true, actor: 'user', consent: [], requires_exclusive: false,
+ why: 'Only an edit of the page brings the fence under the bound; it changes the page layout, not its facts.',
+ user_message: `Page ${slug} has a facts fence of ${rows} rows, more than the ${WITHDRAWAL_LIMITS.matchRows} rows a withdrawal checks in one fence. Split it into fences of at most ${WITHDRAWAL_LIMITS.matchRows} rows each and write the page again? Then retry the withdrawal.`,
+ verify: { argv: ['gbrain', 'get', '--source', sourceId, '--', slug], mcp: { tool: 'get_page', arguments: { slug, source_id: sourceId, body: 'none' } } } } });
+}
+
/** A fence's claims as discovery matches them: every row of a clean block, and every ambiguous row. */
function fenceClaims(id: number, slug: string, body: string): Array<{ id: number; slug: string; claim: string; visibility: string | null; ambiguous: boolean }> {
return [
@@ -117,9 +133,13 @@ export async function discoverWithdrawalTargets(engine: BrainEngine, sourceId: s
JOIN pages p ON p.source_id=f.source_id AND p.slug=COALESCE(f.source_markdown_slug,f.entity_slug)`, [sourceId, keys]);
for (const row of provenance) affected.add(row.id);
if (affected.size > WITHDRAWAL_LIMITS.targets) await refuseAffected(engine, sourceId, affected);
- const match = async (incoming: Array<{ id: number; slug: string; claim: string; visibility: string | null; ambiguous: boolean }>) => {
+ const match = async (incoming: Array<{ id: number; slug: string; claim: string; visibility: string | null; ambiguous: boolean }>, splitFence?: string) => {
if (!incoming.length) return;
- if (incoming.length > 16_384 || Buffer.byteLength(JSON.stringify(incoming)) > 8 * 1024 * 1024) refuse();
+ const bytes = Buffer.byteLength(JSON.stringify(incoming));
+ if (incoming.length > WITHDRAWAL_LIMITS.matchRows || bytes > WITHDRAWAL_LIMITS.matchBytes) {
+ if (splitFence !== undefined) splitFenceTooLarge(sourceId, splitFence, incoming.length, bytes);
+ refuse();
+ }
const matches = await engine.executeRaw<{ id: number; ambiguous: boolean }>(`SELECT DISTINCT i.id,i.ambiguous
FROM jsonb_to_recordset($1::text::jsonb) i(id integer,slug text,claim text,visibility text,ambiguous boolean)
JOIN jsonb_to_recordset($2::text::jsonb) w(visibility text,fact_hash text,subject text)
@@ -159,7 +179,7 @@ export async function discoverWithdrawalTargets(engine: BrainEngine, sourceId: s
if (rows.length < WITHDRAWAL_LIMITS.batch) break;
after = [Number(rows[rows.length - 1].id), Number(rows[rows.length - 1].occurrence_id)];
}
- for await (const split of splitFactsFences(engine, sourceId, keyed, subjects, deadline)) await match(fenceClaims(split.id, split.slug, split.fence));
+ for await (const split of splitFactsFences(engine, sourceId, keyed, subjects, deadline)) await match(fenceClaims(split.id, split.slug, split.fence), split.slug);
for (let after = 0; ;) {
if (performance.now() > deadline) refuse();
const chunks = await engine.executeRaw<{ id: number; page_id: number; slug: string; chunk_text: string }>(`SELECT c.id,c.page_id,p.slug,c.chunk_text
diff --git a/src/core/page-body/body-digests.ts b/src/core/page-body/body-digests.ts
index 2bd2c48168..a3511e1255 100644
--- a/src/core/page-body/body-digests.ts
+++ b/src/core/page-body/body-digests.ts
@@ -87,6 +87,8 @@ export function fileBodyDigests(bytes: ByteSource, reading: FileReading, filePat
/** A fence opener keeps at most this much of its line before it (UTF-16 units): the stored side overlays a segment, so it sees at most that much. */
const OPENER_CONTEXT = SEGMENT_MAX_BYTES;
const MARKER_KEEP = Math.max(FACTS_FENCE_BEGIN.length, FACTS_FENCE_END.length) - 1;
+/** Bytes a read inside an open fence block may pass FENCE_MAX_BYTES by: a UTF-8 sequence the decoder holds back (3) and the byte that proves the block longer. */
+export const FENCE_READ_LOOKAHEAD = 4;
/**
* The digest of each file region after `overlay` (the withdrawal overlay of one complete text, overlayCanonicalBodies),
@@ -94,7 +96,8 @@ const MARKER_KEEP = Math.max(FACTS_FENCE_BEGIN.length, FACTS_FENCE_END.length) -
* and before any marker the next bytes could complete, so a block is always overlaid whole. The text held is the open
* block, with at most OPENER_CONTEXT of the line before its opener, or that much of the current line when no block is
* open, plus the piece just read: never a whole long line. A block longer than FENCE_MAX_BYTES, counted from its begin
- * marker, calls `refuse` with its length so far before anything more is held or overlaid. `between` runs after each
+ * marker, calls `refuse` with its length so far before anything more is held or overlaid; inside an open block no read
+ * passes the bound by more than FENCE_READ_LOOKAHEAD bytes. `between` runs after each
* piece (an effect's claim renewal).
*/
export async function overlaidFileBodyDigests(bytes: ByteSource, reading: FileReading, regions: Record<BodyRegion, readonly BodyPiece[]>,
@@ -117,25 +120,32 @@ export async function overlaidFileBodyDigests(bytes: ByteSource, reading: FileRe
const lastEnd = pending.lastIndexOf(FACTS_FENCE_END, at - FACTS_FENCE_END.length);
return Math.max(pending.lastIndexOf('\n', at - 1) + 1, at - OPENER_CONTEXT, lastEnd === -1 ? 0 : lastEnd + FACTS_FENCE_END.length);
};
+ // Bytes of the open fence block held so far (0 when none is open): the next read stops where the block would pass FENCE_MAX_BYTES.
+ let openBytes = 0;
const drain = async (final: boolean) => {
const { tail } = partialFenceRuns(pending, false);
- if (tail < pending.length) {
- const fence = Buffer.byteLength(pending.slice(tail), 'utf8');
- if (fence > FENCE_MAX_BYTES) throw refuse(fence);
- }
+ openBytes = tail < pending.length ? Buffer.byteLength(pending.slice(tail), 'utf8') : 0;
+ if (openBytes > FENCE_MAX_BYTES) throw refuse(openBytes);
const lastEnd = pending.lastIndexOf(FACTS_FENCE_END);
const closedAt = Math.max(0, pending.length - MARKER_KEEP, lastEnd === -1 ? 0 : lastEnd + FACTS_FENCE_END.length);
const cut = final ? pending.length : keepFrom(tail < pending.length ? tail : closedAt);
if (cut > 0) await emit(pending.slice(0, cut));
pending = pending.slice(cut);
};
+ const take = async (part: Uint8Array) => {
+ pending += decoder.decode(count(part, 'fileBytes'), { stream: true });
+ if (pending.length > bodyDigestWork.largestHeld) bodyDigestWork.largestHeld = pending.length;
+ await drain(false);
+ await between?.();
+ };
for (const piece of regions[region]) {
- const parts = 'text' in piece ? [Buffer.from(piece.text, 'utf8')] : virtualSlice(bytes, reading, piece.start, piece.end);
- for (const part of parts) {
- pending += decoder.decode(count(part, 'fileBytes'), { stream: true });
- if (pending.length > bodyDigestWork.largestHeld) bodyDigestWork.largestHeld = pending.length;
- await drain(false);
- await between?.();
+ if ('text' in piece) { await take(Buffer.from(piece.text, 'utf8')); continue; }
+ // Each read is a segment at most, and within an open block at most what is left of FENCE_MAX_BYTES plus
+ // FENCE_READ_LOOKAHEAD: enough to see its end marker at the bound, or to prove the block longer.
+ for (let at = piece.start; at < piece.end;) {
+ const size = Math.min(SEGMENT_MAX_BYTES, piece.end - at, openBytes ? FENCE_MAX_BYTES - openBytes + FENCE_READ_LOOKAHEAD : Infinity);
+ for (const part of virtualSlice(bytes, reading, at, at + size)) await take(part);
+ at += size;
}
}
pending += decoder.decode();
diff --git a/test/pathological/lp-f-split-fence-withdrawal-capacity.test.ts b/test/pathological/lp-f-split-fence-withdrawal-capacity.test.ts
new file mode 100644
index 0000000000..32c64cc81f
--- /dev/null
+++ b/test/pathological/lp-f-split-fence-withdrawal-capacity.test.ts
@@ -0,0 +1,95 @@
+/**
+ * Large-pages hardening (f): a withdrawal from a facts fence a forced segment cut splits, over the rows discovery
+ * checks one such fence within, is refused with a message that names the fence and the row limit.
+ *
+ * 1. Protects: withdrawal discovery (facts/withdrawal-discovery.ts splitFactsFences) reads a facts fence a forced
+ * cut split whole and checks every row of it in one statement, bounded by WITHDRAWAL_LIMITS.matchRows (16,384
+ * rows) and matchBytes (8 MiB). Over that bound it refuses `withdrawal_capacity` (bound unchanged) with reason
+ * `split_fence_rows`: the message names the page, its row count and the limit, says source size and the ledger
+ * are not the limit, and the fix asks the user to split the fence into fences of at most 16,384 rows.
+ * 2. Fails when: the refusal is the generic one ("could not prove a bounded complete target set ... inspect the source
+ * with the host operator"), which reads as a capacity or budget problem and tells the user not to split the source.
+ * 3. A purge plan (planFactPurge, what `purge_fact`'s dry run and commit run) of a claim in a 17,000-row split fence on a
+ * segmented page. Runs on PGLite, and on Postgres when DATABASE_URL is set.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { importFromFile } from '../../src/core/import-file.ts';
+import { readPageBodyPolicy } from '../../src/core/page-body/limits.ts';
+import { planFactPurge, type PurgeTarget } from '../../src/core/facts/purge.ts';
+import { WITHDRAWAL_LIMITS } from '../../src/core/facts/withdrawal-discovery.ts';
+import { OperationError } from '../../src/core/ops/contract.ts';
+import { registerLocalWriter } from '../../src/core/persistence/identity.ts';
+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { withEnv } from '../helpers/with-env.ts';
+import { pathologicalArms } from './harness.ts';
+
+const ROWS = 17_000;
+const CLAIM = 'Fence Example vault code is 6201';
+const HEADER = '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n'
+ + '|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|\n';
+const row = (n: number, claim: string) => `| ${n} | ${claim} | fact | 1.0 | world | medium | 2026-01-01 | | chat | |`;
+function page(): string {
+ const rows = Array.from({ length: ROWS }, (_, i) => row(i + 1, `Routine note number ${i + 1} about the weekly planning meeting`));
+ rows.splice(ROWS / 2, 0, row(ROWS + 1, CLAIM));
+ return `---\ntitle: Fence Example\ntype: person\n---\n\n# Fence Example\n\n<!--- gbrain:facts:begin -->\n${HEADER}${rows.join('\n')}\n<!--- gbrain:facts:end -->\n\nAfter the fence.\n`;
+}
+
+const homes: string[] = [];
+afterAll(() => { for (const home of homes) rmSync(home, { recursive: true, force: true }); });
+
+for (const { backend, databaseUrl } of pathologicalArms()) describe(`a purge from a split fence over the row limit names the fence (${backend})`, () => {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-lp-f-'));
+ homes.push(home);
+ const env = () => ({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined });
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ beforeAll(async () => withEnv(env(), async () => {
+ if (databaseUrl) ({ engine, close } = await isolatedPersistencePostgres(databaseUrl));
+ else { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); close = () => engine.disconnect(); }
+ }), 120_000);
+ afterAll(async () => withEnv(env(), async () => { await disposePersistenceConsumer(engine); await close?.(); }), 120_000);
+
+ test('withdrawal_capacity with reason split_fence_rows, the page, its rows, the limit and a split-the-fence fix', async () => {
+ await withEnv(env(), async () => {
+ await registerLocalWriter(engine, 'cli');
+ await engine.setConfig('pages.segmented_storage', 'on');
+ const slug = 'people/fence-example';
+ const file = join(home, 'fence-example.md');
+ writeFileSync(file, page());
+ expect(await importFromFile(engine, file, `${slug}.md`, { noEmbed: true, bodyPolicy: await readPageBodyPolicy(engine) })).toMatchObject({ status: 'imported' });
+ const [split] = await engine.executeRaw<{ storage: string; split: number }>(`SELECT p.body_storage AS storage,
+ (SELECT count(*)::int FROM page_body_manifest m CROSS JOIN LATERAL jsonb_array_elements(m.facts_slots) s
+ WHERE m.page_id=p.id AND m.gen_to IS NULL AND m.staging_id IS NULL AND s ? 'open_start') AS split
+ FROM pages p WHERE p.source_id='default' AND p.slug=$1`, [slug]);
+ expect(split).toEqual({ storage: 'segmented', split: expect.any(Number) });
+ expect(split!.split).toBeGreaterThan(1);
+
+ const [{ hash }] = await engine.executeRaw<{ hash: string }>('SELECT gbrain_fact_fingerprint($1) AS hash', [CLAIM]);
+ const target: PurgeTarget = { id: 1, source_id: 'default', visibility: 'world', fact: CLAIM, entity_slug: slug, source_markdown_slug: slug,
+ fact_hash: hash, embedding: null, embedding_model: null };
+ let refused: unknown;
+ try { await planFactPurge(engine, target, false); } catch (error) { refused = error; }
+ expect(refused).toBeInstanceOf(OperationError);
+ const error = refused as OperationError;
+ console.log(`[lp-f] ${backend}: ${error.code}: ${error.message} | ${error.suggestion}`);
+ expect(error.code).toBe('withdrawal_capacity');
+ expect(error.reason).toBe('split_fence_rows');
+ expect(error.message).toContain(`Page ${slug} (source default) has a facts fence split across stored segments with ${ROWS + 1} rows`);
+ expect(error.message).toContain(`over the ${WITHDRAWAL_LIMITS.matchRows}-row / ${WITHDRAWAL_LIMITS.matchBytes / 1024 ** 2} MiB limit`);
+ expect(error.message).toContain('Source size and the withdrawal ledger are not the limit');
+ expect(error.message).not.toContain('could not prove a bounded complete target set');
+ expect(error.suggestion).toContain(`Split that facts fence into smaller fences of at most ${WITHDRAWAL_LIMITS.matchRows} rows each`);
+ expect(error.suggestion).not.toContain('split/delete the source');
+ const wire = JSON.parse(JSON.stringify(error)) as { fix?: { next?: string; user_message?: string; verify?: { argv?: string[] } } };
+ expect(wire.fix?.next).toBe('ask_user');
+ expect(wire.fix?.user_message).toContain(`Page ${slug} has a facts fence of ${ROWS + 1} rows`);
+ expect(wire.fix?.verify?.argv).toEqual(['gbrain', 'get', '--source', 'default', '--', slug]);
+ });
+ }, 600_000);
+});
diff --git a/test/pathological/lp-g-file-digest-fence-bound.test.ts b/test/pathological/lp-g-file-digest-fence-bound.test.ts
new file mode 100644
index 0000000000..e1d4ac9f79
--- /dev/null
+++ b/test/pathological/lp-g-file-digest-fence-bound.test.ts
@@ -0,0 +1,191 @@
+/**
+ * Large-pages hardening (g): the file side of a segmented page's drift check stops reading a facts fence at its bound.
+ *
+ * 1. Protects: overlaidFileBodyDigests (page-body/body-digests.ts), the overlaid file digest the drift check of a
+ * segmented page over the single-string ceiling computes when the source has a withdrawal ledger that applies,
+ * refuses a facts fence longer than FENCE_MAX_BYTES (counted from its begin marker) with `page_body_segmented`
+ * after reading at most the bound plus a small fixed lookahead of that fence, never a further segment. A fence of
+ * exactly the bound, begin marker through end marker, is still overlaid (the lookahead sees its end marker).
+ * 2. Fails when: the overlay reads the region in fixed 1 MiB steps and checks the open block only after each step, so
+ * a fence whose bound falls on a step boundary is read up to a whole segment (1 MiB) past the bound before it refuses.
+ * 3. The first two tests call the digest directly through a ByteSource that records the furthest byte read (no
+ * database is involved, so they run once). The third runs the real drift check (delete_page of a segmented page whose
+ * file gained a fence over the bound) on PGLite, and on Postgres when DATABASE_URL is set, measuring the file bytes
+ * the overlay pass read (`bodyDigestWork.fileBytes` less the scan pass, which reads the file once whole).
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import type { OperationContext } from '../../src/core/operations.ts';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { FENCE_MAX_BYTES, SEGMENT_MAX_BYTES } from '../../src/core/page-body/limits.ts';
+import { bodyDigestWork, fileBodyDigests, overlaidFileBodyDigests, type ByteSource } from '../../src/core/page-body/body-digests.ts';
+import { PAGE_MAX_BYTES } from '../../src/core/page-size-policy.ts';
+import { claimWorktree } from '../../src/core/persistence/ownership.ts';
+import { registerLocalWriter } from '../../src/core/persistence/identity.ts';
+import { importManagedFile } from '../../src/core/persistence/import-mutations.ts';
+import { submitPageMutation } from '../../src/core/persistence/page-mutations.ts';
+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { conversationPage } from '../helpers/conversation-page.ts';
+import { withEnv } from '../helpers/with-env.ts';
+import { pathologicalArms } from './harness.ts';
+
+/** The most a refusing read may pass the bound by inside the fence: a held-back UTF-8 sequence and the proving byte, with room to spare. */
+const LOOKAHEAD = 16;
+const M = SEGMENT_MAX_BYTES;
+const BEGIN = '<!--- gbrain:facts:begin -->';
+const END = '<!--- gbrain:facts:end -->';
+const HEADER = '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n'
+ + '|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|\n';
+const row = (n: number) => `| ${n} | Routine note € number ${n} about the weekly planning meeting | fact | 1.0 | world | medium | 2026-01-01 | | chat | |\n`;
+/** An unclosed fence block of at least `bytes` bytes. */
+function openFence(bytes: number): string {
+ const rows: string[] = [BEGIN, '\n', HEADER];
+ for (let n = 1, size = Buffer.byteLength(BEGIN + '\n' + HEADER); size < bytes; n++) { const r = row(n); rows.push(r); size += Buffer.byteLength(r); }
+ return rows.join('');
+}
+/** A complete fence block of exactly `bytes` bytes, begin marker through end marker. */
+function exactFence(bytes: number): string {
+ const head = openFence(bytes - Buffer.byteLength(END) - 2 * M);
+ const left = bytes - Buffer.byteLength(head) - Buffer.byteLength(END) - 1;
+ return head + ' '.repeat(left) + '\n' + END;
+}
+
+/** A Buffer read through `subarray` only, recording the furthest byte any read reached. */
+function recorded(buffer: Buffer): ByteSource & { furthest: number } {
+ const source = { length: buffer.length, furthest: 0, subarray(start?: number, end?: number) {
+ const to = Math.min(end ?? buffer.length, buffer.length);
+ if (to > source.furthest) source.furthest = to;
+ return buffer.subarray(start, to);
+ } };
+ return source;
+}
+
+const HEAD = '---\ntitle: Fence bound\ntype: note\n---\n\n';
+/** The file's truth region start in its virtual stream (no prefix, no BOM), as the scan splits it. */
+function truthStart(content: string): number {
+ const file = fileBodyDigests(Buffer.from(content, 'utf8'), { prefix: new Uint8Array(0), skip: 0 }, 'probe.md', {});
+ if (file.kind !== 'ok') throw new Error(file.reason);
+ const first = file.regions.truth[0];
+ if (!first || !('start' in first)) throw new Error('the truth region is not a byte range');
+ return first.start;
+}
+/** Padding after `offset` bytes of the truth region that puts the next byte on a 1 MiB step (where a fixed-step reader passes the bound by a segment). */
+const padTo = (offset: number) => { const left = (M - (offset % M)) % M; return left === 0 ? '' : left === 1 ? '\n' : 'p'.repeat(left - 1) + '\n'; };
+
+describe('the overlaid file digest reads a fence up to its bound and a fixed lookahead', () => {
+ test('a fence over the bound refuses after reading at most the bound and the lookahead of it', async () => {
+ const lead = HEAD + '# Fence bound\n';
+ const start = truthStart(lead);
+ const before = lead + padTo(Buffer.byteLength(lead) - start);
+ expect((Buffer.byteLength(before) - start) % M).toBe(0);
+ const buffer = Buffer.from(before + openFence(FENCE_MAX_BYTES + 3 * M) + '\n', 'utf8');
+ const fenceAt = Buffer.byteLength(before);
+ const reading = { prefix: new Uint8Array(0), skip: 0 };
+ const file = fileBodyDigests(buffer, reading, 'bound.md', {});
+ if (file.kind !== 'ok') throw new Error(file.reason);
+ expect(file.factsFence).toBe(true);
+ const source = recorded(buffer);
+ let refusedAt = 0;
+ await expect(overlaidFileBodyDigests(source, reading, file.regions, async text => text, bytes => { refusedAt = bytes; return new Error('fence refused'); }))
+ .rejects.toThrow('fence refused');
+ const read = source.furthest - fenceAt;
+ console.log(`[lp-g] fence read ${read} bytes before refusing (bound ${FENCE_MAX_BYTES}, ${read - FENCE_MAX_BYTES} past it); refused at ${refusedAt}`);
+ expect(refusedAt).toBeGreaterThan(FENCE_MAX_BYTES);
+ expect(read).toBeGreaterThan(FENCE_MAX_BYTES);
+ expect(read).toBeLessThanOrEqual(FENCE_MAX_BYTES + LOOKAHEAD);
+ }, 300_000);
+
+ test('a fence of exactly the bound is overlaid whole, its end marker seen within the lookahead', async () => {
+ const lead = HEAD + '# Fence bound\n';
+ const start = truthStart(lead);
+ const before = lead + padTo(Buffer.byteLength(lead) - start);
+ const fence = exactFence(FENCE_MAX_BYTES);
+ expect(Buffer.byteLength(fence)).toBe(FENCE_MAX_BYTES);
+ const buffer = Buffer.from(before + fence + '\n\nAfter the fence.\n', 'utf8');
+ const reading = { prefix: new Uint8Array(0), skip: 0 };
+ const file = fileBodyDigests(buffer, reading, 'exact.md', {});
+ if (file.kind !== 'ok') throw new Error(file.reason);
+ const overlays: string[] = [];
+ const digests = await overlaidFileBodyDigests(recorded(buffer), reading, file.regions, async text => { overlays.push(text); return text; },
+ bytes => new Error(`refused at ${bytes}`));
+ expect(digests).toEqual(file.digests);
+ expect(overlays.some(text => text.includes(BEGIN) && text.includes(END))).toBe(true);
+ }, 300_000);
+});
+
+const homes: string[] = [];
+afterAll(() => { for (const home of homes) rmSync(home, { recursive: true, force: true }); });
+
+for (const { backend, databaseUrl } of pathologicalArms()) describe(`the drift check refuses an over-bound fence within the lookahead (${backend})`, () => {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-lp-g-'));
+ homes.push(home);
+ const env = () => ({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined });
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ beforeAll(async () => withEnv(env(), async () => {
+ if (databaseUrl) ({ engine, close } = await isolatedPersistencePostgres(databaseUrl));
+ else { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); close = () => engine.disconnect(); }
+ }), 120_000);
+ afterAll(async () => withEnv(env(), async () => { await disposePersistenceConsumer(engine); await close?.(); }), 120_000);
+
+ test('delete_page of a segmented page whose file gained a fence over the bound: page_body_segmented, the overlay stops at the bound', async () => {
+ await withEnv(env(), async () => {
+ await engine.setConfig('pages.segmented_storage', 'on');
+ const root = join(home, 'src');
+ mkdirSync(join(root, 'notes'), { recursive: true });
+ execFileSync('git', ['init', '-q'], { cwd: root });
+ const sourceId = `lp-g-${randomUUID().slice(0, 8)}`;
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [sourceId, root]);
+ await registerLocalWriter(engine, 'cli');
+ await claimWorktree(engine, sourceId, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const ctx = { engine, sourceId, remote: false, config: { engine: engine.kind, embedding_disabled: true } as never, dryRun: false,
+ logger: { info() {}, warn() {}, error() {} } } as OperationContext;
+
+ const slug = 'notes/fence-bound';
+ const file = join(root, `${slug}.md`);
+ const huge = conversationPage(PAGE_MAX_BYTES + 512 * 1024, { seed: 97, needles: [{ at: 0.5, word: 'midpointmarker' }] });
+ writeFileSync(file, huge);
+ expect(await importManagedFile(engine, file, `${slug}.md`, { sourceId, noEmbed: true })).toMatchObject({ status: 'imported' });
+ const [page] = await engine.executeRaw<{ body_storage: string }>('SELECT body_storage FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, slug]);
+ expect(page!.body_storage).toBe('segmented');
+ // Any '*' withdrawal applies to every page of the source, so the drift check overlays the file's fences.
+ await engine.executeRaw(`INSERT INTO fact_withdrawals (source_id, visibility, subject, fact_hash)
+ VALUES ($1, 'world', '*', gbrain_fact_fingerprint('Some unrelated withdrawn claim')) ON CONFLICT DO NOTHING`, [sourceId]);
+
+ // The fence begins on a 1 MiB step of the truth region, so its bound falls on a step boundary.
+ const cut = huge.indexOf('midpointmarker') + 'midpointmarker'.length;
+ const start = truthStart(huge);
+ const head = huge.slice(0, cut) + '\n\n';
+ const before = head + padTo(Buffer.byteLength(head) - start);
+ expect((Buffer.byteLength(before) - start) % M).toBe(0);
+ writeFileSync(file, before + openFence(FENCE_MAX_BYTES + 2 * M) + END + '\n' + huge.slice(cut));
+ const fileBytes = statSync(file).size;
+ // `bodyDigestWork.fileBytes` counts the scan (the file once whole), the region digests (each region once) and the overlay pass:
+ // the truth region before the fence read and hashed as emitted (twice its bytes), then the fence as far as it was read.
+ const scanned = fileBodyDigests(Buffer.from(readFileSync(file)), { prefix: new Uint8Array(0), skip: 0 }, 'probe.md', {});
+ if (scanned.kind !== 'ok') throw new Error(scanned.reason);
+ const regionBytes = [...scanned.regions.truth, ...scanned.regions.timeline].reduce((n, piece) => n + ('text' in piece ? Buffer.byteLength(piece.text) : piece.end - piece.start), 0);
+
+ const snapshot = await engine.readPageSnapshot(slug, { sourceId, includeDeleted: true });
+ bodyDigestWork.fileBytes = 0;
+ let refusal: { code?: string; message: string } | undefined;
+ try {
+ await submitPageMutation(ctx, { operation: 'delete_page', params: { slug, expected_revision: snapshot!.revision, request_id: randomUUID() } });
+ } catch (error) { refusal = { code: (error as { code?: string }).code, message: (error as Error).message }; }
+ expect(refusal?.code).toBe('page_body_segmented');
+ expect(refusal?.message).toContain(`over the ${FENCE_MAX_BYTES}-byte bound`);
+ const fenceRead = bodyDigestWork.fileBytes - fileBytes - regionBytes - 2 * (Buffer.byteLength(before) - start);
+ console.log(`[lp-g] ${backend}: the overlay pass read ${fenceRead} bytes of the fence (bound ${FENCE_MAX_BYTES}, ${fenceRead - FENCE_MAX_BYTES} past it)`);
+ expect(fenceRead).toBeGreaterThan(FENCE_MAX_BYTES);
+ expect(fenceRead).toBeLessThanOrEqual(FENCE_MAX_BYTES + LOOKAHEAD);
+ });
+ }, 900_000);
+});
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 36e1413f6a..105832eaf9 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -254,6 +254,8 @@ test/pathological/b-9-enrich-retired-alias.test.ts
test/pathological/b6-triage-verdict-surrogate.test.ts
test/pathological/c-23-override-and-doctor-fixes.test.ts
test/pathological/c-9-facts-absorb-dead.test.ts
+test/pathological/lp-f-split-fence-withdrawal-capacity.test.ts
+test/pathological/lp-g-file-digest-fence-bound.test.ts
test/persistence-background-pause.test.ts
test/persistence-bounded-read-session.test.ts
test/persistence-capacity-forecast.test.ts