Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Wave B PR 2 lane F: segment reader and per-segment read projection

garrytanae68e0c11c9f
diff --git a/docs/architecture/key-files/core-services-2-continued.md b/docs/architecture/key-files/core-services-2-continued.md
index f27ebadcc7..9c2cbb0a9b 100644
--- a/docs/architecture/key-files/core-services-2-continued.md
+++ b/docs/architecture/key-files/core-services-2-continued.md
@@ -17,3 +17,4 @@ The page-state concurrency foundation under `src/core/page-state/` and the share
- `src/core/progressive-batch/` — shared ramp-up + cost-cap + verification primitive (trial 10 → ramp 100 → ramp 500 → full, with verification at each stage), with verifier+policy injection (callers describe HOW TO MEASURE SUCCESS, not WHEN TO WAIT FOR CTRL-C). Modules: `types.ts` (Stage, StageVerdict, AbortReason, discriminated `Verifier` union `OutputCountVerifier | IdempotentMutationVerifier | NoopVerifier`, Policy, StageReport), `orchestrator.ts` (`runProgressiveBatch(items, verifier, policy, runner)` — reads `getCurrentBudgetTracker()` ahead of `Policy.maxCostUsd` fail-closed; null both ways triggers `abort_cost_cap reason='no_budget_safety_net'`), `audit.ts` (ISO-week JSONL at `~/.gbrain/audit/progressive-batch-YYYY-Www.jsonl` via the shared `audit-writer` primitive), `stage-report.ts` (ASCII formatter for the default `Policy.onStageReport`). Env knobs: `GBRAIN_PROGRESSIVE_BATCH_DISABLED=1`, `GBRAIN_PROGRESSIVE_BATCH_AUTO=1` (skip Ctrl-C grace), `GBRAIN_PROGRESSIVE_BATCH_STAGES=10,100,500`. Sites that "jump straight to full" stay that way by default; ramp is opt-in per-site via `Policy.interactiveAbortMs > 0`. Pinned by `test/progressive-batch/orchestrator.test.ts` (35 cases, every verdict path).
- `src/core/page-body/page-shape.ts` — Wave B PR 1 (spec 1.5): segmented page bodies are unreachable as strings. `guardSegmentedBody` (called by `rowToPage` for a row with `body_storage = 'segmented'`, so by every snapshot and `getPage` read) replaces `compiled_truth` / `timeline` with enumerable getters and setters that throw `page_body_segmented`, so property reads, spread, `JSON.stringify`, `structuredClone` and assignment all fail loud instead of seeing an empty body. `isSegmentedPage`, `assertInlineBody(page, site)` (explicit refusal where a writer would otherwise act before a getter fires, e.g. SQL-only writers), `pageBodyBytes(page)` (`body_bytes` for segmented pages) and `pageBodySegmentedError`. `bodyUnread(page)` says a segmented page's body was not read back as strings (over the single-string ceiling, see `materializedPage`); such a body was written by the streamed import, which holds fenced files, so `fenceBody(page)` reads it as empty for the fence merges and `withoutBody(page)` copies the page's other fields for a render whose body comes from the incoming write (a shrunk file rewrites such a page: `test/large-pages/segmented-shrink-below-ceiling.test.ts`). `Page` stays one shape (`body_storage?`, `body_bytes?`); the static half is `scripts/check-page-body-readers.ts` with `scripts/page-body-readers-baseline.tsv` (docs/TESTING.md#page-body-readers). Pinned by `test/large-pages/segmented-body-unreachable.test.ts`.
+- `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), `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`).
diff --git a/docs/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.md
index 02d7294950..11c9b138b4 100644
--- a/docs/architecture/key-files/core-utilities-2.md
+++ b/docs/architecture/key-files/core-utilities-2.md
@@ -46,7 +46,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/timeline-citations.ts` — `parseInlineCitationTimelineEntries`: inline `[Source: <source>, YYYY-MM-DD]` citations become timeline candidates whose summary is the citing paragraph without the citation; a page with no `[Source:` returns none before any paragraph is built. #6184: a comment-only line is a paragraph boundary and `stripHtmlComments` removes `<!-- … -->` spans (and dangling `<!--`/`-->`) before the summary is built, so section and materialized-row markers are never filed as entries. #6226: a citation files one entry per dated `source, date` segment (a `;` splits sources only after a date), summaries unwrap paired emphasis, and `supersededInlineCitationEntries` returns what the older one-source reading filed and the current reading no longer does; `timeline-extract.ts:supersededCitationTimeline` runs it with both extractors' bullet skips and `retractRemovedTimelineEntries` retracts those rows when their detail is extractor-written (`hasExtractorDetail`: empty or `Source: <source>`). The dated-bullet regexes (`TIMELINE_LINE_RE`, `_CN`, `isDatedTimelineLine`) live here and `link-extraction.ts` imports them.
- `src/core/transcripts.ts` — `listRecentTranscripts(engine, opts)` library reused by both the `gbrain transcripts recent` CLI and the `get_recent_transcripts` MCP op. Reads `dream.synthesize.session_corpus_dir` + `dream.synthesize.meeting_transcripts_dir` config (same as `discoverTranscripts`); walks `.txt` files within `days`; applies the `isDreamOutput` guard from `transcript-discovery.ts` (skips dream-generated files); returns `{path, date, mtime, length, summary}[]` sorted newest-first. Summary mode (default true) = first non-empty line + ~250 trailing chars; full mode caps at 100KB/file. Missing/non-existent corpus dirs return `[]`, not error. Trust gate lives in the op handler, not here: the op throws `permission_denied` for `ctx.remote === true`; this is a trusted library function used by both the gated op and the local CLI.
-- `src/core/eligibility/fence-overlay.ts` + `src/core/trust/fence-append.ts` — the facts-fence eligibility overlay for chunks (#5575 ENG-1). `loadFenceChunkOverlay(engine, { sourceId, slug, compiled_truth, timeline })` reads, in one query and only when the body has world fence rows, which rows to omit (a `write_gate_holds` hold on the row's fingerprint, through the `registerFactHoldFingerprint` seam for the write gate's `holdFingerprint`; a `fact_purges` tombstone, the backstop to L3's import overlay) and which to demote (stored `facts.trust_tier` below the page tier, or a row a fence append is publishing, declared with `withPendingFenceRows`). `prepareMarkdownChunks(page, maxTokens, overlay)` (`markdown-chunks.ts`) drops both from the page's chunks and emits demoted rows as trailing chunks whose first line is `fenceTrustMarker(tier)` (a `compactTrustLabel` line with origin `facts-fence`); without overlay rows the output is byte-identical. The importer (`prepareFenceAwareMarkdownChunks`), projection rebuilds (`ProjectionSnapshot.fenceOverlay`), embed's chunkless rebuilds (`prepareProseChunks`) and evidence delivery's page document (`pageEvidenceText`) all cut through it; `healOversizedChunks` keeps the marker on every split piece. `eligibility/stamp.ts` labels a row carrying a marker min(page tier, marker tier) with origin `facts-fence` and applies floors at that tier; a marker can only lower. `withPageTierKept(tx, page, fn)` restores the page's prior `trust_tier`/`write_origin` after a fence append's page write (promotion capped at the prior tier when raising back), used by `fence-write.ts` (legacy mirror), `memory-prepare.ts` (remember) and `facts-prepare.ts` (managed entity facts). Tests: `test/fence-chunk-overlay.test.ts` (PGLite and Postgres via `test/e2e/fence-chunk-overlay-postgres.test.ts`).
+- `src/core/eligibility/fence-overlay.ts` + `src/core/trust/fence-append.ts` — the facts-fence eligibility overlay for chunks (#5575 ENG-1). `loadFenceChunkOverlay(engine, { sourceId, slug, compiled_truth, timeline })` reads, in one query and only when the body has world fence rows, which rows to omit (a `write_gate_holds` hold on the row's fingerprint, through the `registerFactHoldFingerprint` seam for the write gate's `holdFingerprint`; a `fact_purges` tombstone, the backstop to L3's import overlay) and which to demote (stored `facts.trust_tier` below the page tier, or a row a fence append is publishing, declared with `withPendingFenceRows`). `prepareMarkdownChunks(page, maxTokens, overlay)` (`markdown-chunks.ts`) drops both from the page's chunks and emits demoted rows as trailing chunks whose first line is `fenceTrustMarker(tier)` (a `compactTrustLabel` line with origin `facts-fence`); without overlay rows the output is byte-identical. The importer (`prepareFenceAwareMarkdownChunks`), projection rebuilds (`ProjectionSnapshot.fenceOverlay`), embed's chunkless rebuilds (`prepareProseChunks`) and evidence delivery's page document (`pageEvidenceText`) all cut through it; `healOversizedChunks` keeps the marker on every split piece. `fenceLowTierRows` / `renderFenceLowTier` give the demoted rows of one text for the segment reader's low-tier block. `eligibility/stamp.ts` labels a row carrying a marker min(page tier, marker tier) with origin `facts-fence` and applies floors at that tier; a marker can only lower. `withPageTierKept(tx, page, fn)` restores the page's prior `trust_tier`/`write_origin` after a fence append's page write (promotion capped at the prior tier when raising back), used by `fence-write.ts` (legacy mirror), `memory-prepare.ts` (remember) and `facts-prepare.ts` (managed entity facts). Tests: `test/fence-chunk-overlay.test.ts` (PGLite and Postgres via `test/e2e/fence-chunk-overlay-postgres.test.ts`).
- `src/core/types.ts` extension + `src/core/operations.ts:search` + `src/core/import-file.ts` + `src/cli.ts` + `src/core/search/telemetry.ts` — the wiring layer for the retrieval-quality stack. `SearchResult` carries `evidence`, `create_safety`, `title_match_boost`, `alias_hit` (all optional; evidence/create_safety reference the union types in `evidence.ts`). The `search` MCP op uses a cheap-hybrid path by default and accepts a per-call `mode` (conservative|balanced|tokenmax) honored ONLY for trusted/local callers (`resolvePerCallMode(ctx, ...)` — remote callers use the configured mode so a remote provider can't force tokenmax spend); every search path stamps evidence fail-soft. `importFromContent` projects frontmatter `aliases:` into `page_aliases` via `normalizeAliasList` + `engine.setPageAliases` so new + changed pages register aliases at ingest. `src/cli.ts` carries the `gbrain search diagnose` dispatch (lazy import) and reconciles the `search` CLI path with the cheap-hybrid op. `src/core/search/telemetry.ts` carries in its rollup the rank-1 base_score drift signal (sum/count + 3 coarse buckets, aggregate not per-query), surfaced via `gbrain search stats`, backed by migration v111's `search_telemetry` columns. Tests: `test/cli-search-dispatch.test.ts`, `test/search/per-call-mode.test.ts`, `test/search/telemetry-rank1.test.ts`, `test/search/title-boost-stage.test.ts`, `test/search/alias-hop.test.ts`, `test/search/evidence.test.ts`, `test/search/searchvector-maxpool.test.ts`, `test/search/pre-migration-failopen.test.ts`.
- `src/core/url-redact.ts` — Postgres-URL + free-text credential redaction, sibling of `redact-connection-info.ts`. `redactPgUrl(url)` strips userinfo from a single postgres/postgresql URL, preserving scheme/host/port/db/query (non-URL input collapses to `<redacted-url>`). `redactUrlsInText(text)` sweeps free text (error messages, log lines) for credential shapes of any word-character scheme (the pattern is `\w+://`, so scheme names containing `+`/`-`/`.` are not matched — postgres shapes are the target): the userinfo match is greedy up to the LAST `@` in the token so a raw `@` inside a password can't leak its tail (over-redacts toward safety), and libpq keyword/value forms (`password=` / `sslpassword=`, including quoted values with spaces) are masked too; text without a credential shape passes through untouched. `redactDeep(value)` recursively redacts postgres URLs inside structured payloads about to be stringified. Consumers: the upgrade-errors + connection-events audit JSONL sites, and cli.ts's doctor DB-fallback stderr note (layered with `redactConnectionInfo`). CI guard: `scripts/check-pg-url-redaction.sh` fails the build when a new code path emits an unredacted postgres URL. Pinned by `test/url-redact.test.ts`.
diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.md
index 9a99cac429..67689cebbd 100644
--- a/docs/architecture/key-files/google-and-loops-continued.md
+++ b/docs/architecture/key-files/google-and-loops-continued.md
@@ -22,7 +22,7 @@
- **`src/core/persistence/links-maintenance.ts`** — `extractManagedStaleLinks` (then the mention pass unless `mentions: false`, which sync passes) derives links for pages whose extraction watermark is stale with `prepareAutomaticLinks` (put_page's replace contract; other producers' edges stay) and adds the coordinator's unrecorded canonical timeline tuples (insert-only) and each page's watermark in the same `withCoordinatedWrite` transaction, bound to the revision it read; an edited page or unresolved attendance stays stale. A page skipped for unresolved attendance is marked attendance-blocked at that revision (`pages.links_attendance_blocked_revision` / `_at`, written by `markPagesAttendanceBlocked` in `engine-sql/pages.ts` only while the revision still matches, cleared by `markPagesExtractedBatch` with the watermark); it is still reconsidered every run, and the `links_extraction_lag` doctor check counts it apart from lag while the marker equals the page's current revision. It is the one managed extraction path: managed sync, `extractStaleFromDB` on a managed brain, and the owner delegation all run it. `runManagedStaleExtraction` backs `gbrain extract --stale` on managed brains, locally or through the `writer_extract_stale` administration operation inside a PGLite owner (`src/commands/extract-stale-delegate.ts`, trusted CLI registration only). `links-preparation.ts` retargets a link written against a renamed page's old slug to the live canonical page through `slug_aliases`, as `get_page` does. Tests: `persistence-managed-lifecycle.test.ts`, `persistence-sync-stdio-owner.serial.test.ts`.
- **`src/core/persistence/sync-authority.ts`** — trusted CLI or original remote generic job authority; rejects stdio bulk privilege promotion and runtime option expansion, intersects original grants with current principal/source policy.
-- `src/core/facts/withdrawal-overlay.ts` — pure legacy-fence enumeration and withdrawal rendering shared by coherent snapshots, stale imports and physical forget mirrors. The shared snapshot overlay and import pre-publication validator recognize canonical prefixed/inline markers and distinguish malformed live segments. Discovery refuses matching ambiguous claims before mutation. Fingerprints match independently in each fence, including inactive history, against both the folded (v174) and exact legacy hashes; parser-recognized markers precede preserved evidence context and earlier expiry remains intact. Regression: `test/withdrawal-overlay-concurrency.test.ts` on both engines.
+- `src/core/facts/withdrawal-overlay.ts` — pure legacy-fence enumeration and withdrawal rendering shared by coherent snapshots, stale imports and physical forget mirrors. The shared snapshot overlay and import pre-publication validator recognize canonical prefixed/inline markers and distinguish malformed live segments. Discovery refuses matching ambiguous claims before mutation. `partialFenceRuns` finds the fence runs a forced segment cut splits. Fingerprints match independently in each fence, including inactive history, against both the folded (v174) and exact legacy hashes; parser-recognized markers precede preserved evidence context and earlier expiry remains intact. Regression: `test/withdrawal-overlay-concurrency.test.ts` on both engines.
- **`src/commands/sync-persistence-delegate.ts` + `src/core/persistence/{sync-wire,sync-administration}.ts`** — pre-connect authenticated CLI sync ingress for any resident PGLite owner, including stdio MCP. The CLI JSON renderer shares the direct sync envelope. Strict options preserve source/brain selection and filtering; only current CLI credentials can advance bounded durable cursor slices. Unactivated delegation also forces import-only work and queues the owner embed drain, preserving the inline cost gate; backlogs are per-engine source sets and shutdown waits for actual provider settlement before releasing datastore ownership; the real serve E2E observes a committed receipt before SIGKILL and proves same-ID cursor recovery without breaking locks. The env and default deadlines stay progress-aware across slices (`DelegatedSyncDeadline`): past the deadline the client keeps re-entering while a slice advanced the managed cursor within one progress window, and each slice gets at least one window; `--timeout` and `--hard-deadline` stay strict. Legacy shared-secret sync refuses managed brains. `test/persistence-sync-stdio-owner.test.ts` starts a real stdio owner and exercises CLI import/read/admin, remote-lane denial and revocation without a competing datastore open. #6696: the wire accepts an `explicitProcessing` list (processing keys only, no duplicates) and the owner keeps a supplied list exactly; a payload without one counts only its true-valued processing keys as typed (`typedSyncProcessing`), so a flagless resume adopts the cursor's stored options (`test/sync-owner-lane-processing-6696.test.ts`).
- `src/core/facts/backstop.ts` + `src/core/entities/resolve-on-save.ts` — saved facts retain their content and provenance but use a NULL entity target when resolution falls back to slugification. Legacy extraction uses the shared exact source/entity/visibility fingerprint decision before identity-gated cosine candidates, so old facts without vector provenance still deduplicate identical text without relabeling their vectors. The conversation save caller also clears the target on ordinary resolution errors, preserves diagnostic counters, and propagates abort/budget failures. It never treats an invented slug as a verified page. #5836: `src/core/facts/subject-infer-write.ts` `inferMissingSubjects` links facts with no or fallback-only entity via `inferFactSubject` (remote callers: written page only, readable pages, caller fences, managed grant), never on the unmanaged DB-only branch, marks `entity_inferred` (context note; exact-text dedup only in both writers); `test/facts-backstop-entity-inference.test.ts`, `test/managed-facts-entity-inference.test.ts`. #6159: every writer (both backstop buckets, the fence writes and `persistence/facts-maintenance.ts`) dates a fact with `facts/event-time.ts` `factEventTime` (extractor date, then `validFrom`, then `turnAt`, then now) and the extraction prompt's observation date falls back to `turnAt`; the sweep's corpus pass sets `turnAt` from the session file's write time, vetted by `context/corpus-windows.ts` `corpusFactTime` (finite, from 2000, at most 60 s ahead; otherwise logged and dated at extraction) (`test/sweep-corpus-fact-time.test.ts`). #6113: `resolveManagedFactsEmbedding` (`persistence/facts-maintenance.ts`) reads the brain's DB-plane model only; a legacy row without a provider refuses `embedding_configuration` naming `gbrain migrate embeddings --to <gateway provider>:<model> --dry-run` (the read-only preview; applying it needs paid authorization). Test: `test/facts-embedding-bare-model.serial.test.ts`. The notability-filter vocabulary (`NOTABILITY_FILTERS`, `coerceNotabilityFilter`) lives in import-light `src/core/facts/notability-filter.ts` (re-exported here) beside the page-write key resolver. The unmanaged pipeline counts entity groups held on a facts fence that does not parse cleanly as `fence_refused` (nothing written for them). Large pages A7: the page entry (`runPipeline`) plans with the `facts_backstop` watermark (`src/core/extraction-watermark.ts`, cap `MAX_TURN_TEXT_CHARS`): past a matching watermark the extractor reads only the appended text (`PipelineInput.extractText`; `turnText` stays the full body, which the managed preparer compares with the page), an unchanged long page makes no model call, and a head or tail-window read returns `input_truncated` on the inline result; the plan commits after an extraction that neither failed nor aborted. Test: `test/extraction-watermark-facts.test.ts`.
- `src/commands/migrations/v0_32_2.ts` + `src/core/facts/unfenced-facts.ts` — Phase B is the shared core pass `planUnfencedFacts` / `fenceUnfencedFacts`, which the `extract_facts` cycle phase also runs on every cycle (#5299). It fences live unfenced facts (`row_num IS NULL`) only onto an existing source-scoped page, and never ontology observations (`dimension IS NOT NULL`, #6264: they belong to the ontology, keyed by their own provenance) and its recorded canonical file; a managed brain publishes each page as one coordinator `managed_maintenance_adopt_fact_fence` request (database-only pages included; a read-only pre-pass of `planManagedPage` counts the pages that will submit for the up-front lifetime-ID check, so suppressed or unadoptable pages never refuse the step, and the submit loop replans each page right before it submits; `test/fact-fence-adoption-exits.test.ts`), and an unmanaged page is written under the source filesystem lock and page lock (`.tmp` + parse + rename), mirrored into `pages` and stamped in one maintenance transaction, and committed when the checkout is durability-hardened. Missing pages/files are counted as `skipped_no_page` (a recorded canonical file absent on this host is also listed in `missing_files`), never materialized as stubs. #6610: an unmanaged database-only page (no `source_path`/`source_uri`, no file at its slug path) is fenced in its database body through the coordinator (`fenceDatabaseOnlyPage`, no file target) when `resolveFactWriteTarget` makes the write database-only; an unbound source without `persistence.unbound_write=database_only` leaves its rows in `unbound_refused`, which `extract_facts` holds out of reconciliation without gating and doctor `fence_integrity` reports as `unbound_legacy_facts` with the opt-in (`ask_user`). The migration adds a dirty-tree refusal that stays inside the source subdirectory; fence row allocation respects both database-owned row numbers and the parsed fence, preserving idempotent recovery without collisions. Dry runs use the same eligibility checks, and historical drift remains visible rather than silently repaired. #6278: `planFence` uses the fence codec as the oracle (`adoptableClaim`): a legacy row adopts only when `parseFactsFence(renderFactsTable([row]))` hands its claim back active and non-empty with the same kind, visibility, validity and source, differing from the stored text by whitespace and line endings alone (trim, CRLF/CR to LF, NBSP), and the parsed text is written into `facts.fact` with the row number on both the managed and the unmanaged path, so the projection keeps the row's id, vectors and provenance. A row the codec would change further (whitespace-only, `~~x~~`, a literal `<br>`) or a second row whose normalized claim, source and visibility the page already carries stays a legacy row exactly as it is, recorded as an `UnadoptableFactRecord` (source, page, fact id, reason class; never the claim text) and named in `failed_pages` as `FACTS_FENCE_FAILED: <slug> (fence_unrenderable: N row(s), <class>)` in the cycle and the migration output; the page's other rows still adopt. Tests: `test/facts-fence-adoption-roundtrip.test.ts`, `test/extract-facts-unfenced-rows.test.ts`, `test/migrations-v0_32_2-managed.test.ts`.
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 6e02e66a37..51878cc5d1 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -2190,6 +2190,16 @@ More: [docs/guides/windowed-reads.md#page_body_segmented](../../docs/guides/wind
More: [docs/guides/repair.md#page-projection-conflict](../../docs/guides/repair.md#page-projection-conflict)
+### page_projection_stale
+
+<a id="page_projection_stale"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| A segment of this large page has projection metadata gbrain cannot use, so the read returned nothing for it rather than unsanitized text. | Windows of a segmented page are cut from each segment's stored protected regions; when they are stale (another segmenter version, a text that does not match its hash) gbrain recomputes them from the segment's carried parser state, and refuses when that state is missing or of another version, or when a facts fence block crosses a forced cut while the source has withdrawals. | Rewrite the page body (import or sync its file again), which segments it with this gbrain version, then read it again; other windows and the outline still work. | host_admin | `gbrain doctor --json` | 1 | no |
+
+More: [docs/guides/windowed-reads.md#page_projection_stale](../../docs/guides/windowed-reads.md#page_projection_stale)
+
### page_shrink_refused
<a id="page_shrink_refused"></a>
diff --git a/docs/guides/windowed-reads.md b/docs/guides/windowed-reads.md
index 3523de1f39..ca5fbdbffd 100644
--- a/docs/guides/windowed-reads.md
+++ b/docs/guides/windowed-reads.md
@@ -105,6 +105,18 @@ derived-link passes (a trusted page write's links, the managed stale-links
pass, post-batch auto-link) read a segmented page up to 24 MiB as one string;
the extraction and link passes skip a larger one with this code.
+## page_projection_stale
+
+A read of a segmented page reached a segment whose stored projection metadata
+(its protected regions, written when the segment was stored) cannot be used:
+it was written by another segmenter version or the text does not match its
+hash, and the parser state carried with the segment is missing or of another
+version. A trusted body read also refuses when a facts fence block crosses a
+forced segment cut while the source has withdrawals. gbrain returns nothing for
+that segment rather than text it cannot sanitize. Rewrite the page body (import
+or sync its file again), which segments it with this gbrain version, then read
+it again; other windows and the outline still work.
+
## page_shrink_refused
A remote `put_page` would replace a page over the inline size with content under
diff --git a/scripts/check-orphan-modules.mjs b/scripts/check-orphan-modules.mjs
index 4fd946fb5b..df505a90bc 100644
--- a/scripts/check-orphan-modules.mjs
+++ b/scripts/check-orphan-modules.mjs
@@ -72,7 +72,7 @@ const PERMITTED_TEST_ONLY = [
{ path: 'src/core/ingestion/sources/file-watcher.ts', reason: 'held: ingestion cluster awaits a wire-up vs delete product decision' },
{ path: 'src/core/ingestion/sources/gstack-learnings.ts', reason: 'held: ingestion cluster awaits a wire-up vs delete product decision' },
{ path: 'src/core/ingestion/sources/inbox-folder.ts', reason: 'held: ingestion cluster awaits a wire-up vs delete product decision (docs/guides/data-ingestion.md promises the inbox folder)' },
- { path: 'src/core/ingestion/sources/markdown-greenfield.ts', reason: 'held: ingestion cluster awaits a wire-up vs delete product decision (docs/migrations/v0.41.2-markdown-greenfield.md)' },
+ { path: 'src/core/ingestion/sources/markdown-greenfield.ts', reason: 'held: ingestion cluster awaits a wire-up vs delete product decision (docs/migrations/v0.41.2-markdown-greenfield.md)' }, { path: 'src/core/page-body/read-range.ts', reason: 'held: Wave B PR 2 segment reader (lane F); the get_page, page-window and evidence lanes of the same PR wire it into their reads' },
];
const RULES = {
diff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsv
index f9d8d7d9cf..2e3fdf947c 100644
--- a/scripts/page-body-readers-baseline.tsv
+++ b/scripts/page-body-readers-baseline.tsv
@@ -322,6 +322,7 @@ src/core/page-body/ingest.ts stageBody field NONE not a stored body: the write's
src/core/page-body/page-shape.ts fenceBody field INLINE reads a body that is a string (inline or materialized); an unread segmented body holds no fences and reads as empty
src/core/page-body/page-shape.ts pageBodyBytes field INLINE inline branch of pageBodyBytes; a segmented page answers body_bytes
src/core/page-body/schema.ts PAGE_GENERATION_BUMP_FN_SQL sql STREAM trigger DDL: compares the body columns of inline rows; segmented rows compare body_generation (lane 1a)
+src/core/page-body/segment-ledger.ts overlaySegmentText field NONE not the page body: compiled_truth of overlayCanonicalBodies over one segment's text (at most one segment, never the whole body)
src/core/page-body/streamed-import.ts importScanned field LEAD bounded heads of the streamed file's regions for the sanity and type checks; the body itself streams to the segmenter
src/core/page-embedding-budget.ts planPageEmbedding field META lane 1e file: body_bytes for segmented pages
src/core/page-embedding-budget.ts readPageSizeStates sql META lane 1e file: body_bytes for segmented pages
@@ -411,6 +412,7 @@ src/core/persistence/reconcile-prepare.ts prepareReconcileResult field INLINE
src/core/persistence/reconcile-state.ts readReconcileState sql INLINE
src/core/persistence/reconcile.ts runReconcilePreview call:serializePageToMarkdown SEGW
src/core/persistence/segmented-apply.ts demoteSegmentedPage sql INLINE demotion: the row turns inline with an empty body that the inline write in the same transaction fills
+src/core/persistence/segmented-apply.ts sealSegmentedPage field LEAD the withdrawal overlay of the stored timeline_lead (a bounded prefix), indexed sanitized
src/core/persistence/segmented-apply.ts stageSegmentedImport field INLINE input.page is the parsed incoming write (strings within PAGE_MAX_BYTES), never a stored segmented row
src/core/persistence/semantic-pages.ts prepareSemanticPageMutation call:serializePageToMarkdown SEGW assertInlineBody first
src/core/persistence/semantic-pages.ts prepareSemanticPageMutation field SEGW assertInlineBody after the identity check (tag and timeline writes refuse)
diff --git a/src/core/eligibility/fence-overlay.ts b/src/core/eligibility/fence-overlay.ts
index 5bc4271c93..f8d9eae7cd 100644
--- a/src/core/eligibility/fence-overlay.ts
+++ b/src/core/eligibility/fence-overlay.ts
@@ -106,22 +106,44 @@ export interface FenceOverlaySplit {
export function splitFenceOverlay(text: string, overlay: FenceChunkOverlay | null | undefined): FenceOverlaySplit {
if (fenceOverlayIsEmpty(overlay) || !text.includes('gbrain:facts:begin')) return { main: text, lowTier: [] };
const { omit, demote } = overlay!;
+ const main = dropFactFenceRowsByNumber(text, row => !omit.has(row.rowNum) && !demote.has(row.rowNum));
+ return { main, lowTier: renderFenceLowTier(fenceLowTierRows(text, overlay)) };
+}
+
+/** A visible world fence row of a body whose tier is below the page tier, with that tier, in body order. */
+export interface FenceLowTierRow { tier: TrustTier; unconfirmed: boolean; row: ParsedFact }
+
+/**
+ * The rows `splitFenceOverlay` moves out of a body, in order. Fence blocks never cross a segment cut, so the rows of a
+ * segmented body are its segments' rows concatenated, and `renderFenceLowTier` over them equals the whole-body split.
+ */
+export function fenceLowTierRows(text: string, overlay: FenceChunkOverlay | null | undefined): FenceLowTierRow[] {
+ if (fenceOverlayIsEmpty(overlay) || !text.includes('gbrain:facts:begin')) return [];
+ const { omit, demote } = overlay!;
const flagged = overlay!.unconfirmed ?? new Set<number>();
- const groups = new Map<string, ParsedFact[]>();
+ const rows: FenceLowTierRow[] = [];
for (const block of withdrawalFenceBlocks(text)) {
if (block.parsed.warnings.length) continue;
for (const row of block.parsed.facts) {
const tier = demote.get(row.rowNum);
if (!tier || omit.has(row.rowNum) || row.visibility !== 'world' || row.forgotten) continue;
- const group = `${tier}|${flagged.has(row.rowNum)}`;
- groups.set(group, [...(groups.get(group) ?? []), row]);
+ rows.push({ tier, unconfirmed: flagged.has(row.rowNum), row });
}
}
- const main = dropFactFenceRowsByNumber(text, row => !omit.has(row.rowNum) && !demote.has(row.rowNum));
- return { main, lowTier: TRUST_TIERS.flatMap(tier => [false, true].flatMap(unconfirmed => {
- const rows = groups.get(`${tier}|${unconfirmed}`);
- return rows ? [{ tier, unconfirmed, body: renderFactsTable(rows) }] : [];
- })) };
+ return rows;
+}
+
+/** One rendered facts fence per demoted tier and unconfirmed state, least trusted last (`FenceOverlaySplit.lowTier`). */
+export function renderFenceLowTier(rows: readonly FenceLowTierRow[]): FenceOverlaySplit['lowTier'] {
+ const groups = new Map<string, ParsedFact[]>();
+ for (const { tier, unconfirmed, row } of rows) {
+ const group = `${tier}|${unconfirmed}`;
+ groups.set(group, [...(groups.get(group) ?? []), row]);
+ }
+ return TRUST_TIERS.flatMap(tier => [false, true].flatMap(unconfirmed => {
+ const grouped = groups.get(`${tier}|${unconfirmed}`);
+ return grouped ? [{ tier, unconfirmed, body: renderFactsTable(grouped) }] : [];
+ }));
}
/** World fence rows of a body, every complete block. */
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index a3df8e2a0b..6907d1bc6a 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -348,6 +348,7 @@ export const CODES = {
page_identity_changed: { class: 'caller', summary: "The page was deleted or replaced while the operation ran.", fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}' } }, consent: [], actor: 'agent', why: "Shows which page holds the slug now and its revision; a new attempt needs a new request_id.", requires_exclusive: false } },
page_projection_conflict: { class: 'retryable', summary: "Another worker installed a newer search projection of the page while this command prepared its own.", why: "The projection guard keeps the newer installation instead of overwriting it; the canonical page revision did not change.", docs: 'docs/guides/repair.md#page-projection-conflict', suggestion: "Re-run the same command; it re-reads the current projection. If it conflicts again, wait for the other worker to finish." },
page_not_found: { class: 'caller', summary: "No page with that slug exists in the selected source.", legacy_error: 'page_identity_changed', fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}' } }, consent: [], actor: 'agent', why: "Confirms whether the page exists in this source before anything is recreated.", requires_exclusive: false } },
+ page_projection_stale: { class: 'server', summary: "A segment of this large page has projection metadata gbrain cannot use, so the read returned nothing for it rather than unsanitized text.", why: "Windows of a segmented page are cut from each segment's stored protected regions; when they are stale (another segmenter version, a text that does not match its hash) gbrain recomputes them from the segment's carried parser state, and refuses when that state is missing or of another version, or when a facts fence block crosses a forced cut while the source has withdrawals.", docs: 'docs/guides/windowed-reads.md#page_projection_stale', suggestion: 'Rewrite the page body (import or sync its file again), which segments it with this gbrain version, then read it again; other windows and the outline still work.' },
page_body_segmented: { class: 'caller', summary: "This page's body is stored in segments, and the path that hit it reads or writes the whole body as one string, so it stopped before reading or changing anything.", why: "With pages.segmented_storage on, a page over 1 MiB keeps its body in segments instead of the page row; a whole-body path would otherwise see an empty body and could overwrite the page or drop the unread rest. Windowed reads and segment-aware writers replace these paths.", docs: 'docs/guides/windowed-reads.md#page_body_segmented', suggestion: "Read the page's revision and stored size with get_page body: 'none' (size.body_bytes); windowed reads of a segmented body arrive with the segment reader.", fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--body', 'none', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}', body: 'none' } }, consent: [], actor: 'agent', why: "Returns the page's revision and size without its body.", requires_exclusive: false } },
page_shrink_refused: { class: 'caller', summary: "put_page refused to replace a large page with content much smaller than the stored body; nothing was written.", why: "Above the inline read size (mcp.inline_body_bytes, 256 KB) a get_page read returns a window, not the body, so a replacement far smaller than the page is most often a window sent back as the whole page, which would delete the unread rest.", docs: 'docs/guides/windowed-reads.md#page_shrink_refused', suggestion: "Change part of the page with edit_page (revision from get_page body: 'none'). Pass allow_shrink: true only when the smaller content is the intended complete page.", fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}', body: 'none' } }, consent: [], actor: 'agent', why: "Returns the page's revision and size without its body; edit_page with that revision changes only the text it names.", requires_exclusive: false } },
page_too_large_for_inline: { class: 'caller', summary: "The whole page does not fit one result on this connection, so get_page did not return its body.", why: "A result is measured as the complete encoded frame; a body over the connection's cap (mcp.max_result_bytes_stdio, 4 MiB; mcp.max_result_bytes_http, 1 MiB) would be cut or rejected by the client. Nothing was truncated: windowed reads cover the whole page in pieces.", docs: 'docs/guides/windowed-reads.md#page_too_large_for_inline', legacy_error: 'invalid_params', suggestion: "Read the outline (body: 'outline'), then windows (body: 'window' with lines, bytes, around_chunk_id or the returned next_cursor). To replace the page, edit it with edit_page and the revision from body: 'none'.", fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}', body: 'outline' } }, consent: [], actor: 'agent', why: "Returns the page's size, revision and outline; each entry names the lines to read with body: 'window'.", requires_exclusive: false, verify: { mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}', body: 'none' } } } } },
diff --git a/src/core/facts/withdrawal-overlay.ts b/src/core/facts/withdrawal-overlay.ts
index 623cb95370..43c30af979 100644
--- a/src/core/facts/withdrawal-overlay.ts
+++ b/src/core/facts/withdrawal-overlay.ts
@@ -125,6 +125,28 @@ export function fenceClaimHashes(normalizedTexts: readonly string[]): string[] {
return [...hashes];
}
+/**
+ * Wave B: the per-segment form of the overlay's block walk. A segment is overlaid alone (`overlayWithdrawalBody` over
+ * its text, so the WITHDRAWAL_MARKER_LIMIT applies to one segment), which is exact for every block inside it: the
+ * segmenter never cuts inside a fence block except at a forced cut. Returns the runs of a block a forced cut splits,
+ * which a lone segment cannot overlay: `[0, head)`, the end of a block opened in an earlier segment (`entryOpen`), and
+ * `[tail, length)`, a block still open at the segment's end (`tail = 0` when the whole segment is inside one).
+ */
+export function partialFenceRuns(text: string, entryOpen: boolean): { head: number; tail: number } {
+ let open: number | null = entryOpen ? -1 : null;
+ let head = 0;
+ for (const marker of literalFenceMarkers(text)) {
+ if (marker.kind === 'begin') {
+ if (!marker.inlineCode) open = marker.start;
+ continue;
+ }
+ if (open === null) continue;
+ if (open === -1) head = marker.end;
+ open = null;
+ }
+ return { head, tail: open === null ? text.length : Math.max(open, 0) };
+}
+
/** Apply hashes from DB-normalized companion text to the original Markdown. */
export function overlayWithdrawalBody(body: string, normalizedBody: string, withdrawals: PageWithdrawal[]): string {
if (!withdrawals.length || !body.includes('gbrain:facts:begin')) return body;
diff --git a/src/core/page-body/ingest.ts b/src/core/page-body/ingest.ts
index 6295c1bba3..ab83d91fe5 100644
--- a/src/core/page-body/ingest.ts
+++ b/src/core/page-body/ingest.ts
@@ -25,13 +25,15 @@ import { stepFenceWalk, type FenceWalk } from '../fence-scan.ts';
import { BODY_LEAD_BYTES, BODY_STAGING_HARD_MS, BODY_STAGING_IDLE_MS, STAGE_BATCH_BYTES } from './limits.ts';
import type { BodyRegion, BodyStagingKind, BodyStorage, JsonObject, ManifestRow, ManifestRowInput, SegmentChunkInput,
SegmentedBodyColumns, SegmentTextInput } from './types.ts';
-import { segmentProjectionParts, segmentStream, SEGMENTER_VERSION, type StoredRegion } from './segmenter.ts';
+import { segmentStream, SEGMENTER_VERSION, type StoredRegion } from './segmenter.ts';
import { initialEntryState, readEntryState, timelineEntryState, type EntryState } from './entry-state.ts';
import { ContentHashStream } from './content-hash-stream.ts';
import { prepareSegmentChunks } from './segment-chunks.ts';
import { reuseSegmentChunkVectors } from '../import-chunk-reuse.ts';
import { newFenceChunkBudget } from '../markdown-chunks.ts';
import { loadFenceChunkOverlay } from '../eligibility/fence-overlay.ts';
+import { withdrawalFenceBlocks } from '../facts/withdrawal-overlay.ts';
+import { overlaySegmentText, readBodyLedger, type BodyLedger } from './segment-ledger.ts';
const utf8 = new TextDecoder('utf-8', { fatal: true });
@@ -360,6 +362,7 @@ export async function stageOccurrenceChunks(engine: BrainEngine, input: { pageId
if (input.chunking.quarantined || !input.occurrences.length) return { rows: 0, occurrences: 0, indexes: [] };
const batchBytes = STAGE_BATCH_BYTES[engine.kind];
const fenceBudget = newFenceChunkBudget();
+ let ledger: BodyLedger | undefined;
let rows = 0, done = 0;
const indexes: number[] = [];
for (let start = 0; start < input.occurrences.length;) {
@@ -368,21 +371,22 @@ export async function stageOccurrenceChunks(engine: BrainEngine, input: { pageId
const batch = input.occurrences.slice(start, end);
start = end;
const texts = await engine.readSegmentTexts(input.sourceId, batch.map(row => row.sha256));
- const segments = batch.map(row => {
+ ledger ??= await readBodyLedger(engine, input.sourceId, input.slug);
+ const segments = [];
+ for (const row of batch) {
const bytes = texts.get(hex(row.sha256));
if (bytes === undefined) throw new Error(`Segment text ${hex(row.sha256)} of page ${input.pageId} is missing.`);
const entryState = readEntryState(row.entryState);
if (!entryState) throw new Error(`Manifest row ${row.occurrenceId} of page ${input.pageId} has an entry state of another version; resegment the page.`);
const fenceTrust = regionTrust(input.flags, row.region);
- return { row, fenceTrust, segment: { region: row.region, bytes, byteStart: row.byteStart, entryState, fenceTrust, protectedRegions: row.protectedRegions as StoredRegion[] } };
- });
- const factsTexts = segments.flatMap(({ segment }) => segment.protectedRegions.some(region => region.kind === 'facts')
- ? segmentProjectionParts(utf8.decode(segment.bytes), segment.protectedRegions, segment.byteStart)
- .filter(part => part.kind === 'facts' && part.region?.open_start === undefined).map(part => part.text) : []);
+ const text = await overlaySegmentText(engine, ledger, { sourceId: input.sourceId, byteStart: row.byteStart, entryState }, utf8.decode(bytes), 'read');
+ segments.push({ row, fenceTrust, text, segment: { region: row.region, bytes, byteStart: row.byteStart, entryState, fenceTrust, protectedRegions: row.protectedRegions as StoredRegion[] } });
+ }
+ const factsTexts = segments.flatMap(({ text }) => text.includes('gbrain:facts:begin') ? withdrawalFenceBlocks(text).map(block => text.slice(block.start, block.end)) : []);
const overlay = factsTexts.length ? await loadFenceChunkOverlay(engine, { sourceId: input.sourceId, slug: input.slug, compiled_truth: factsTexts.join('\n') }) : undefined;
const chunks: SegmentChunkInput[] = [];
- for (const { row, fenceTrust, segment } of segments) {
- for (const chunk of await prepareSegmentChunks(segment, { fenceTrust, frontmatter: input.frontmatter, overlay, fenceBudget })) {
+ for (const { row, fenceTrust, segment, text } of segments) {
+ for (const chunk of await prepareSegmentChunks(segment, { fenceTrust, frontmatter: input.frontmatter, overlay, fenceBudget, text })) {
chunks.push({ ...chunk, occurrence_id: row.occurrenceId });
}
}
diff --git a/src/core/page-body/read-range.ts b/src/core/page-body/read-range.ts
new file mode 100644
index 0000000000..5f2d0bbbc0
--- /dev/null
+++ b/src/core/page-body/read-range.ts
@@ -0,0 +1,444 @@
+/**
+ * Segmented page storage (Wave B, spec 7.1-7.3): ranged reads of a segmented
+ * body, one segment text at a time, never the whole body as one string.
+ *
+ * Two views, chosen by space and audience:
+ *
+ * - The read projection (space 'projected', either audience; space 'stored'
+ * for a remote caller): the text projectPageText gives the joined body
+ * (page-window/document.ts), the one text Wave A windows, outlines, chunks
+ * and evidence are cut from, the same for local and remote callers.
+ * Projected offsets are its UTF-8 bytes: truth segments, the low-tier block
+ * after the truth, TIMELINE_SEPARATOR and the timeline segments when the
+ * timeline shows any text. Each segment is projected whole from its stored
+ * regions (segment-projection.ts) after the withdrawal overlay, then cut.
+ * - The trusted body (space 'stored', audience 'trusted'): the stored stream
+ * after the withdrawal overlay, what readPageSnapshot gives a trusted reader
+ * of an inline page (export, derived passes, a local full read). It has no
+ * coordinates of its own: `projectedStart` repeats `storedStart`.
+ *
+ * Offsets are located from manifest sums: a page's rows are one light query,
+ * static projection sizes add up, and only segments with facts slots are read
+ * to add their rendered facts tables and to load the page's fence overlay
+ * (`projectedLayout`, cached on the handle). A stored-space range selects the
+ * rows it overlaps; a token, a rendered facts table or a block the overlay
+ * rewrote is emitted whole or not at all.
+ *
+ * Offsets can drift without a revision change (a hold or a tier change moves
+ * the projection, and a withdrawal block outside a facts region changes a
+ * segment's length the sums do not see): a read can then repeat or skip text,
+ * never show text the projection hides.
+ */
+import { createHash } from 'node:crypto';
+import type { BrainEngine } from '../engine.ts';
+import { TIMELINE_SEPARATOR } from '../page-window/document.ts';
+import { sanitizeRemoteBody } from '../remote-body.ts';
+import { credentialSafeProjection } from '../credential-projection.ts';
+import { loadFenceChunkOverlay, markFenceChunk, renderFenceLowTier, type FenceChunkOverlay, type FenceLowTierRow } from '../eligibility/fence-overlay.ts';
+import { withdrawalFenceBlocks } from '../facts/withdrawal-overlay.ts';
+import { regionTrust } from './ingest.ts';
+import { readBodyLedger, overlaySegmentText, type BodyLedger } from './segment-ledger.ts';
+import { SEGMENTER_VERSION, type FactsSlot, type OutlineHeading, type StoredRegion } from './segmenter.ts';
+import { overlaidPieces, projectionStaleError, projectSegment, type ProjectedPiece, type SegmentProjection } from './segment-projection.ts';
+import type { BodyRegion, JsonObject } from './types.ts';
+
+export type BodySpace = 'stored' | 'projected';
+export type BodyAudience = 'trusted' | 'remote';
+
+export type { BodyLedger } from './segment-ledger.ts';
+
+/** One manifest row of the read generation, without its JSON metadata. */
+export interface BodyRow {
+ seq: number;
+ occurrenceId: number;
+ region: BodyRegion;
+ sha256: Uint8Array;
+ byteStart: number;
+ byteLen: number;
+ lineStart: number;
+ staticProjBytes: number;
+ staticProjLines: number;
+ outlineCount: number;
+ hasFacts: boolean;
+ hasDate: boolean;
+}
+
+/** A segmented body opened for reading: the page, the generation's rows and the ledger. Reuse it across reads of one request. */
+export interface SegmentedBody {
+ pageId: number;
+ sourceId: string;
+ slug: string;
+ generation: number;
+ bodyBytes: number;
+ truthBytes: number;
+ flags: JsonObject;
+ rows: BodyRow[];
+ ledger: BodyLedger;
+ /** The page was segmented by another segmenter version: every segment's regions are recomputed. */
+ stale: boolean;
+ layout?: ProjectedLayout;
+}
+
+/** Where every row of the read projection sits (`projectedLayout`). */
+export interface ProjectedLayout {
+ /** Document byte of each row's projection, its bytes and its newlines; -1 for timeline rows when the timeline shows nothing. */
+ rowStart: number[];
+ rowBytes: number[];
+ rowNewlines: number[];
+ /** Rendered facts table bytes per slot, for rows with facts slots. */
+ rowFacts: Array<number[] | null>;
+ /** The low-tier block after the truth ('' when none) and where it starts. */
+ lowTier: string;
+ lowTierStart: number;
+ /** Where the timeline text starts after TIMELINE_SEPARATOR; -1 when the page shows no timeline. */
+ timelineByte: number;
+ totalBytes: number;
+ newlines: number;
+ overlay: FenceChunkOverlay | undefined;
+}
+
+export interface BodyRangeRequest {
+ pageId: number;
+ /** Default: the live generation. */
+ generation?: number;
+ space: BodySpace;
+ /** Bytes in that space, [start, end); `end` may be Infinity. */
+ start: number;
+ end: number;
+ audience: BodyAudience;
+ /** Rows of one region only (the low-tier block counts as truth; TIMELINE_SEPARATOR as neither). */
+ region?: BodyRegion;
+ /** An opened body (openSegmentedBody), reused across reads. */
+ body?: SegmentedBody;
+ /** The page's ledger when the caller read a snapshot; else loaded. */
+ ledger?: BodyLedger;
+}
+
+export interface BodyRangePiece {
+ bytes: Buffer;
+ /** Stored-stream byte the piece stands at (for a token or a facts table, its region's start). */
+ storedStart: number;
+ /** Byte of the piece in the read projection (the trusted body: equal to storedStart). */
+ projectedStart: number;
+}
+
+const utf8 = new TextDecoder('utf-8', { fatal: true });
+const HEAVY_BATCH = 64;
+const toJson = (v: unknown) => typeof v === 'string' ? JSON.parse(v) as unknown : v;
+const bytesOf = (v: unknown): Uint8Array => { const b = v as Uint8Array; return new Uint8Array(b.buffer, b.byteOffset, b.byteLength); };
+const newlines = (s: string) => { let n = 0; for (let i = s.indexOf('\n'); i !== -1; i = s.indexOf('\n', i + 1)) n++; return n; };
+
+export async function openSegmentedBody(engine: BrainEngine, opts: { pageId: number; generation?: number; ledger?: BodyLedger }): Promise<SegmentedBody> {
+ const [page] = await engine.executeRaw<Record<string, unknown>>(`SELECT id, source_id, slug, body_storage, body_generation, body_bytes, truth_bytes,
+ body_flags, segmenter_version FROM pages WHERE id=$1`, [opts.pageId]);
+ if (!page || page.body_storage !== 'segmented') throw new Error(`Page ${opts.pageId} is not a segmented page.`);
+ const generation = opts.generation ?? Number(page.body_generation);
+ const rows = await engine.executeRaw<Record<string, unknown>>(`SELECT m.seq, m.occurrence_id, m.region, m.sha256, m.byte_start, m.byte_len,
+ m.line_start, m.static_proj_bytes, m.static_proj_lines, jsonb_array_length(m.outline) AS outline_count,
+ jsonb_array_length(m.facts_slots) > 0 AS has_facts, m.date_min IS NOT NULL AS has_date
+ FROM page_body_manifest m
+ WHERE m.page_id=$1 AND m.staging_id IS NULL AND m.gen_from<=$2 AND (m.gen_to IS NULL OR m.gen_to>$2) ORDER BY m.seq`, [opts.pageId, generation]);
+ const slug = String(page.slug);
+ const sourceId = String(page.source_id);
+ const ledger = opts.ledger ?? await readBodyLedger(engine, sourceId, slug);
+ return {
+ pageId: opts.pageId, sourceId, slug, generation, bodyBytes: Number(page.body_bytes ?? 0), truthBytes: Number(page.truth_bytes ?? 0),
+ flags: (toJson(page.body_flags) ?? {}) as JsonObject, ledger, stale: Number(page.segmenter_version) !== SEGMENTER_VERSION,
+ rows: rows.map(r => ({
+ seq: Number(r.seq), occurrenceId: Number(r.occurrence_id), region: r.region as BodyRegion, sha256: bytesOf(r.sha256),
+ byteStart: Number(r.byte_start), byteLen: Number(r.byte_len), lineStart: Number(r.line_start), staticProjBytes: Number(r.static_proj_bytes),
+ staticProjLines: Number(r.static_proj_lines), outlineCount: Number(r.outline_count), hasFacts: r.has_facts === true, hasDate: r.has_date === true,
+ })),
+ };
+}
+
+interface LoadedSegment {
+ row: BodyRow;
+ bytes: Uint8Array;
+ entryState: unknown;
+ protectedRegions: StoredRegion[];
+ /** The text's sha256 is not the row's. */
+ mismatch: boolean;
+}
+
+/** The rows' texts and JSON metadata, one text at a time (metadata in batches). */
+async function* loadSegments(engine: BrainEngine, body: SegmentedBody, rows: readonly BodyRow[]): AsyncIterable<LoadedSegment> {
+ for (let at = 0; at < rows.length; at += HEAVY_BATCH) {
+ const batch = rows.slice(at, at + HEAVY_BATCH);
+ const meta = new Map((await engine.executeRaw<Record<string, unknown>>(`SELECT occurrence_id, entry_state, protected_regions
+ FROM page_body_manifest WHERE page_id=$1 AND occurrence_id=ANY($2::bigint[]) AND staging_id IS NULL AND gen_from<=$3 AND (gen_to IS NULL OR gen_to>$3)`,
+ [body.pageId, batch.map(r => r.occurrenceId), body.generation])).map(m => [Number(m.occurrence_id), m]));
+ for (const row of batch) {
+ const m = meta.get(row.occurrenceId);
+ const bytes = (await engine.readSegmentTexts(body.sourceId, [row.sha256])).get(Buffer.from(row.sha256).toString('hex'));
+ if (!m || bytes === undefined) throw projectionStaleError(row.byteStart, 'its manifest row or text is missing');
+ yield {
+ row, bytes, entryState: toJson(m.entry_state), protectedRegions: (toJson(m.protected_regions) ?? []) as StoredRegion[],
+ mismatch: !createHash('sha256').update(bytes).digest().equals(Buffer.from(row.sha256)),
+ };
+ }
+ }
+}
+
+function overlaidText(engine: BrainEngine, body: SegmentedBody, seg: LoadedSegment, raw: string, view: 'read' | 'trusted'): Promise<string> {
+ return overlaySegmentText(engine, body.ledger, { sourceId: body.sourceId, byteStart: seg.row.byteStart, entryState: seg.entryState }, raw, view);
+}
+
+/** The fence overlay for a segment: the page's (layout), plus the rows of fence blocks outside its facts slots. */
+async function segmentOverlay(engine: BrainEngine, body: SegmentedBody, seg: LoadedSegment, text: string, base: FenceChunkOverlay | undefined) {
+ if (seg.row.hasFacts || !text.includes('gbrain:facts:begin')) return base;
+ const extra = await loadFenceChunkOverlay(engine, { sourceId: body.sourceId, slug: body.slug, compiled_truth: fenceBlockText(text) });
+ if (!extra) return base;
+ if (!base) return extra;
+ return { omit: new Set([...base.omit, ...extra.omit]), demote: new Map([...base.demote, ...extra.demote]),
+ unconfirmed: new Set([...(base.unconfirmed ?? []), ...(extra.unconfirmed ?? [])]) };
+}
+
+function fenceBlockText(text: string): string {
+ return withdrawalFenceBlocks(text).map(b => text.slice(b.start, b.end)).join('\n');
+}
+
+async function projectLoaded(engine: BrainEngine, body: SegmentedBody, seg: LoadedSegment, overlay: FenceChunkOverlay | undefined): Promise<SegmentProjection> {
+ const raw = utf8.decode(seg.bytes);
+ const text = await overlaidText(engine, body, seg, raw, 'read');
+ return projectSegment({ region: seg.row.region, bytes: seg.bytes, byteStart: seg.row.byteStart, lineStart: seg.row.lineStart, entryState: seg.entryState,
+ protectedRegions: seg.protectedRegions, fenceTrust: regionTrust(body.flags, seg.row.region) },
+ { text, fenceOverlay: await segmentOverlay(engine, body, seg, text, overlay), stale: body.stale || seg.mismatch });
+}
+
+interface RowSummary { bytes: number; newlines: number; facts: number[]; lowTier: FenceLowTierRow[]; blank: boolean }
+
+function summarize(p: SegmentProjection): RowSummary {
+ let bytes = 0, lines = 0, blank = true;
+ for (const piece of p.pieces) {
+ bytes += Buffer.byteLength(piece.text, 'utf8');
+ lines += newlines(piece.text);
+ if (blank && piece.text.trim()) blank = false;
+ }
+ return { bytes, newlines: lines, facts: p.factsBytes, lowTier: p.lowTier, blank };
+}
+
+/**
+ * Where each row sits in the read projection. Reads only the segments with facts slots (twice when the page's fence
+ * overlay is not empty: its world rows decide the overlay), plus, when no stored sum says so, timeline segments until
+ * one shows text.
+ */
+export async function projectedLayout(engine: BrainEngine, body: SegmentedBody): Promise<ProjectedLayout> {
+ if (body.layout) return body.layout;
+ const factsRows = body.rows.filter(r => r.hasFacts);
+ const summaries = new Map<number, RowSummary>();
+ const blocks: string[] = [];
+ for await (const seg of loadSegments(engine, body, factsRows)) {
+ const text = await overlaidText(engine, body, seg, utf8.decode(seg.bytes), 'read');
+ blocks.push(fenceBlockText(text));
+ summaries.set(seg.row.seq, summarize(await projectLoaded(engine, body, seg, undefined)));
+ }
+ const overlay = blocks.length ? await loadFenceChunkOverlay(engine, { sourceId: body.sourceId, slug: body.slug, compiled_truth: blocks.join('\n') }) : undefined;
+ if (overlay) for await (const seg of loadSegments(engine, body, factsRows)) summaries.set(seg.row.seq, summarize(await projectLoaded(engine, body, seg, overlay)));
+
+ const n = body.rows.length;
+ const layout: ProjectedLayout = { rowStart: new Array(n).fill(-1), rowBytes: new Array(n).fill(0), rowNewlines: new Array(n).fill(0),
+ rowFacts: new Array(n).fill(null), lowTier: '', lowTierStart: 0, timelineByte: -1, totalBytes: 0, newlines: 0, overlay };
+ let pos = 0, lines = 0;
+ const place = (i: number) => {
+ const row = body.rows[i]!;
+ const s = summaries.get(row.seq);
+ layout.rowStart[i] = pos;
+ layout.rowBytes[i] = s?.bytes ?? row.staticProjBytes;
+ layout.rowNewlines[i] = s?.newlines ?? row.staticProjLines;
+ layout.rowFacts[i] = s?.facts ?? null;
+ pos += layout.rowBytes[i]!;
+ lines += layout.rowNewlines[i]!;
+ };
+ body.rows.forEach((row, i) => { if (row.region === 'truth') place(i); });
+ const low = (region: BodyRegion) => body.rows.filter(r => r.region === region).flatMap(r => summaries.get(r.seq)?.lowTier ?? []);
+ layout.lowTier = [...renderFenceLowTier(low('truth')), ...renderFenceLowTier(low('timeline'))]
+ .map(({ tier, unconfirmed, body: text }) => '\n\n' + markFenceChunk(tier, credentialSafeProjection(sanitizeRemoteBody(text)), unconfirmed)).join('');
+ layout.lowTierStart = pos;
+ pos += Buffer.byteLength(layout.lowTier, 'utf8');
+ lines += newlines(layout.lowTier);
+ if (await timelineVisible(engine, body, summaries)) {
+ pos += Buffer.byteLength(TIMELINE_SEPARATOR, 'utf8');
+ lines += newlines(TIMELINE_SEPARATOR);
+ layout.timelineByte = pos;
+ body.rows.forEach((row, i) => { if (row.region === 'timeline') place(i); });
+ }
+ layout.totalBytes = pos;
+ layout.newlines = lines;
+ body.layout = layout;
+ return layout;
+}
+
+/** projectPageText shows the timeline only when its projection holds non-whitespace text. */
+async function timelineVisible(engine: BrainEngine, body: SegmentedBody, summaries: Map<number, RowSummary>): Promise<boolean> {
+ for (const row of body.rows) {
+ if (row.region !== 'timeline') continue;
+ const known = summaries.get(row.seq);
+ if (known) { if (!known.blank) return true; continue; }
+ if (row.staticProjBytes === 0) continue;
+ if (row.hasDate || row.outlineCount > 0) return true;
+ for await (const seg of loadSegments(engine, body, [row])) if (!summarize(await projectLoaded(engine, body, seg, undefined)).blank) return true;
+ }
+ return false;
+}
+
+/** Projected totals for `body: 'none'` and window metadata: bytes, lines (as window.ts totalLines counts them), timeline start. */
+export async function projectedTotals(engine: BrainEngine, body: SegmentedBody): Promise<{ total_bytes: number; total_lines: number; timeline_byte_start: number }> {
+ const layout = await projectedLayout(engine, body);
+ let last = '';
+ if (layout.totalBytes > 0) {
+ for await (const piece of readBodyRange(engine, { pageId: body.pageId, space: 'projected', start: layout.totalBytes - 1, end: layout.totalBytes, audience: 'remote', body })) last = piece.bytes.toString('latin1');
+ }
+ const lines = layout.totalBytes === 0 ? 0 : layout.newlines + (last.endsWith('\n') ? 0 : 1);
+ return { total_bytes: layout.totalBytes, total_lines: lines, timeline_byte_start: layout.timelineByte };
+}
+
+type Unit = { kind: 'row'; index: number; start: number } | { kind: 'text'; text: string; start: number; storedStart: number; region: BodyRegion | null };
+
+/** The read projection's parts in document order: truth rows, the low-tier block, the separator, timeline rows. */
+function units(body: SegmentedBody, layout: ProjectedLayout): Unit[] {
+ const out: Unit[] = [];
+ body.rows.forEach((row, i) => { if (row.region === 'truth') out.push({ kind: 'row', index: i, start: layout.rowStart[i]! }); });
+ if (layout.lowTier) out.push({ kind: 'text', text: layout.lowTier, start: layout.lowTierStart, storedStart: body.truthBytes, region: 'truth' });
+ if (layout.timelineByte >= 0) {
+ out.push({ kind: 'text', text: TIMELINE_SEPARATOR, start: layout.timelineByte - Buffer.byteLength(TIMELINE_SEPARATOR, 'utf8'), storedStart: body.truthBytes, region: null });
+ body.rows.forEach((row, i) => { if (row.region === 'timeline') out.push({ kind: 'row', index: i, start: layout.rowStart[i]! }); });
+ }
+ return out;
+}
+
+const unitBytes = (u: Unit, layout: ProjectedLayout) => u.kind === 'row' ? layout.rowBytes[u.index]! : Buffer.byteLength(u.text, 'utf8');
+
+export async function* readBodyRange(engine: BrainEngine, req: BodyRangeRequest): AsyncIterable<BodyRangePiece> {
+ if (!(req.start >= 0) || !(req.end >= req.start) || !Number.isInteger(req.start) || (!Number.isInteger(req.end) && req.end !== Infinity)) {
+ throw new Error(`readBodyRange: [${req.start}, ${req.end}) is not a byte range.`);
+ }
+ if (req.end === req.start) return;
+ const body = req.body ?? await openSegmentedBody(engine, req);
+ if (req.space === 'projected') return yield* projectedRange(engine, body, req);
+ const rows = body.rows.filter(r => (!req.region || r.region === req.region) && r.byteStart < req.end && r.byteStart + r.byteLen > req.start);
+ if (req.audience === 'trusted') {
+ for await (const seg of loadSegments(engine, body, rows)) {
+ const raw = utf8.decode(seg.bytes);
+ for (const piece of overlaidPieces(raw, await overlaidText(engine, body, seg, raw, 'trusted'))) {
+ const cut = cutStored(piece, seg.row.byteStart, req.start, req.end);
+ if (cut) yield { bytes: cut.bytes, storedStart: cut.storedStart, projectedStart: cut.storedStart };
+ }
+ }
+ return;
+ }
+ const layout = await projectedLayout(engine, body);
+ for await (const seg of loadSegments(engine, body, rows)) {
+ let doc = layout.rowStart[body.rows.indexOf(seg.row)]!;
+ if (doc < 0) continue;
+ for (const piece of (await projectLoaded(engine, body, seg, layout.overlay)).pieces) {
+ const cut = cutStored(piece, seg.row.byteStart, req.start, req.end);
+ if (cut) yield { bytes: cut.bytes, storedStart: cut.storedStart, projectedStart: doc + cut.offset };
+ doc += Buffer.byteLength(piece.text, 'utf8');
+ }
+ }
+}
+
+/** The part of a piece inside stored range [start, end): linear text byte for byte, anything else whole. */
+function cutStored(piece: ProjectedPiece, base: number, start: number, end: number): { bytes: Buffer; storedStart: number; offset: number } | null {
+ const s = base + piece.rawStart;
+ const e = base + piece.rawEnd;
+ if (!(e > start && s < end) && !(s === e && s >= start && s < end)) return null;
+ const bytes = Buffer.from(piece.text, 'utf8');
+ if (!piece.linear) return { bytes, storedStart: s, offset: 0 };
+ const from = Math.max(start, s) - s;
+ return { bytes: bytes.subarray(from, Math.min(end, e) - s), storedStart: s + from, offset: from };
+}
+
+async function* projectedRange(engine: BrainEngine, body: SegmentedBody, req: BodyRangeRequest): AsyncIterable<BodyRangePiece> {
+ const layout = await projectedLayout(engine, body);
+ const wanted = units(body, layout).filter(u => {
+ const region = u.kind === 'row' ? body.rows[u.index]!.region : u.region;
+ return (!req.region || region === req.region) && u.start < req.end && u.start + unitBytes(u, layout) > req.start;
+ });
+ const rows = wanted.flatMap(u => u.kind === 'row' ? [body.rows[u.index]!] : []);
+ const segments = loadSegments(engine, body, rows)[Symbol.asyncIterator]();
+ for (const u of wanted) {
+ if (u.kind === 'text') {
+ const bytes = Buffer.from(u.text, 'utf8');
+ const from = Math.max(req.start, u.start) - u.start;
+ yield { bytes: bytes.subarray(from, Math.min(req.end, u.start + bytes.length) - u.start), storedStart: u.storedStart, projectedStart: u.start + from };
+ continue;
+ }
+ const next = await segments.next();
+ if (next.done) return;
+ let doc = u.start;
+ for (const piece of (await projectLoaded(engine, body, next.value, layout.overlay)).pieces) {
+ const bytes = Buffer.from(piece.text, 'utf8');
+ const from = Math.max(req.start, doc) - doc;
+ const to = Math.min(req.end, doc + bytes.length) - doc;
+ if (to > from) {
+ const storedStart = next.value.row.byteStart + piece.rawStart + (piece.linear ? from : 0);
+ yield { bytes: bytes.subarray(from, to), storedStart, projectedStart: doc + from };
+ }
+ doc += bytes.length;
+ if (doc >= req.end) break;
+ }
+ }
+}
+
+/** The projected byte where 1-based line `line` starts (totalBytes past the last line); reads at most one segment. */
+export async function projectedLineStart(engine: BrainEngine, body: SegmentedBody, line: number): Promise<number> {
+ const layout = await projectedLayout(engine, body);
+ let want = line - 1;
+ if (want <= 0) return 0;
+ for (const u of units(body, layout)) {
+ const count = u.kind === 'row' ? layout.rowNewlines[u.index]! : newlines(u.text);
+ if (want > count) { want -= count; continue; }
+ let text = '';
+ if (u.kind === 'text') text = u.text;
+ else for await (const piece of readBodyRange(engine, { pageId: body.pageId, space: 'projected', start: u.start, end: u.start + layout.rowBytes[u.index]!, audience: 'remote', body })) text += piece.bytes.toString('utf8');
+ let at = -1;
+ for (let k = 0; k < want; k++) { at = text.indexOf('\n', at + 1); if (at === -1) return u.start + Buffer.byteLength(text, 'utf8'); }
+ return u.start + Buffer.byteLength(text.slice(0, at + 1), 'utf8');
+ }
+ return layout.totalBytes;
+}
+
+export interface BodyOutlineEntry { heading: string; level: number; byte_start: number; region: BodyRegion }
+
+/**
+ * The stored outline (headings of each segment's static projection outside code fences and protected regions, at
+ * most OUTLINE_MAX_HEADINGS per segment), paged by entry index: reads the metadata of the rows the page covers, no
+ * segment text. Offsets are read-projection bytes; line numbers are not stored.
+ */
+export async function projectedOutline(engine: BrainEngine, body: SegmentedBody, from: number, limit: number):
+ Promise<{ entries: BodyOutlineEntry[]; total_entries: number; from_index: number; next_from_index?: number }> {
+ const layout = await projectedLayout(engine, body);
+ const visible = body.rows.map((row, i) => ({ row, i })).filter(({ i }) => layout.rowStart[i]! >= 0)
+ .sort((a, b) => layout.rowStart[a.i]! - layout.rowStart[b.i]!);
+ const total = visible.reduce((n, v) => n + v.row.outlineCount, 0);
+ const entries: BodyOutlineEntry[] = [];
+ const needed: typeof visible = [];
+ let index = 0;
+ for (const v of visible) {
+ if (index + v.row.outlineCount > from && index < from + limit) needed.push(v);
+ index += v.row.outlineCount;
+ }
+ const meta = needed.length ? new Map((await engine.executeRaw<Record<string, unknown>>(`SELECT occurrence_id, facts_slots, outline FROM page_body_manifest
+ WHERE page_id=$1 AND occurrence_id=ANY($2::bigint[]) AND staging_id IS NULL AND gen_from<=$3 AND (gen_to IS NULL OR gen_to>$3)`,
+ [body.pageId, needed.map(v => v.row.occurrenceId), body.generation])).map(m => [Number(m.occurrence_id), m])) : new Map();
+ index = 0;
+ let next = 0;
+ for (const v of visible) {
+ const m = needed.includes(v) ? meta.get(v.row.occurrenceId) : undefined;
+ if (!m) { index += v.row.outlineCount; continue; }
+ const slots = (toJson(m.facts_slots) ?? []) as FactsSlot[];
+ const facts = layout.rowFacts[v.i] ?? [];
+ for (const h of (toJson(m.outline) ?? []) as OutlineHeading[]) {
+ if (index >= from && entries.length < limit) {
+ let byte = layout.rowStart[v.i]! + h.proj_byte;
+ slots.forEach((slot, k) => { if (slot.proj_byte <= h.proj_byte) byte += facts[k] ?? 0; });
+ entries.push({ heading: h.text, level: h.level, byte_start: byte, region: v.row.region });
+ next = index + 1;
+ }
+ index++;
+ }
+ }
+ return { entries, total_entries: total, from_index: from, ...(next < total && entries.length ? { next_from_index: next } : {}) };
+}
diff --git a/src/core/page-body/segment-chunks.ts b/src/core/page-body/segment-chunks.ts
index c4a2dc9f0a..7d5e79380b 100644
--- a/src/core/page-body/segment-chunks.ts
+++ b/src/core/page-body/segment-chunks.ts
@@ -8,27 +8,35 @@
* the segment's bounds and carry no overlap from the previous segment, so a
* segment's chunks depend only on its bytes, entry state and stored regions.
*
- * The projection is built from the stored regions the segmenter computed
- * under the page's fence trust: takes, truncated tail and materialized
- * markers out, private keys as the projection token, and each facts region
- * rendered (world rows through the fence overlay) where its slot sits. A
- * facts region that crosses the segment's bounds is omitted, fail closed.
+ * The projection is the segment's read projection (segment-projection.ts),
+ * the same text a window of the page shows: takes, truncated tail and
+ * materialized markers out, private keys as the projection token, each facts
+ * region rendered (world rows through the fence overlay, credential-projected)
+ * where its slot sits, a facts region that crosses the segment's bounds
+ * omitted, all after the page's withdrawal overlay (`text`). That is the
+ * safe-fence contract of the inline chunker (chunkText over
+ * credentialSafeProjection(sanitizeRemoteBody()) of the overlaid body), so a
+ * sealed segmented page carries the markdown chunker's version and remote
+ * reads serve its chunks.
* Inline pages keep prepareMarkdownChunks; this is a separate chunker identity.
*/
-import { chunkProjectedText, chunkText } from '../chunkers/recursive.ts';
+import { chunkProjectedText, chunkText, MARKDOWN_CHUNKER_VERSION } from '../chunkers/recursive.ts';
import { estimateEmbedTokens } from '../chunkers/token-estimate.ts';
import { resolveMaxChunkTokens } from '../embedding-input-limit.ts';
import { fencedCodeChunks, newFenceChunkBudget, type FenceChunkBudget } from '../markdown-chunks.ts';
-import { fenceTrustMarker, markFenceChunk, splitFenceOverlay, type FenceChunkOverlay } from '../eligibility/fence-overlay.ts';
+import { fenceTrustMarker, markFenceChunk, renderFenceLowTier, type FenceChunkOverlay } from '../eligibility/fence-overlay.ts';
import { isQuarantined } from '../quarantine.ts';
-import { renderFactsRegion } from '../remote-body.ts';
-import { credentialSafeProjection } from '../credential-projection.ts';
import type { EntryState } from './entry-state.ts';
import type { SegmentChunkInput, BodyRegion } from './types.ts';
-import { segmentProjectionParts, type StoredRegion } from './segmenter.ts';
+import type { StoredRegion } from './segmenter.ts';
+import { projectSegment } from './segment-projection.ts';
-/** Bump when the per-segment projection or chunk layout changes (stamped with the segmenter version). */
-export const SEGMENTED_CHUNKER_VERSION = 1;
+/**
+ * `pages.chunker_version` of a sealed segmented page: segments are chunked by the markdown pipeline
+ * (chunkProjectedText, fencedCodeChunks) under the same safe-fence contract, so they share its version, at or above
+ * SAFE_FENCE_CHUNKER_VERSION. A change to the cuts or the stored per-segment metadata bumps SEGMENTER_VERSION.
+ */
+export const SEGMENTED_CHUNKER_VERSION = MARKDOWN_CHUNKER_VERSION;
export type SegmentChunk = Omit<SegmentChunkInput, 'occurrence_id'>;
@@ -48,6 +56,8 @@ export interface SegmentChunkOptions {
frontmatter?: Record<string, unknown> | null;
maxChunkTokens?: number;
overlay?: FenceChunkOverlay;
+ /** The segment text after the page's withdrawal overlay; defaults to the stored text. */
+ text?: string;
/** One budget per page, shared by every segment's call, so the fence caps stay per page. */
fenceBudget?: FenceChunkBudget;
}
@@ -60,26 +70,16 @@ export async function prepareSegmentChunks(segment: ChunkableSegment, opts: Segm
throw new Error(`segment_regions_stale: regions at byte ${segment.byteStart} were computed under fence trust ${segment.fenceTrust}, the page is ${opts.fenceTrust}; rescan before chunking`);
}
const maxTokens = opts.maxChunkTokens ?? resolveMaxChunkTokens();
- const raw = Buffer.from(segment.bytes).toString('utf8');
const segEnd = segment.byteStart + segment.bytes.length;
- const pieces: string[] = [];
+ const projected = projectSegment({ ...segment, lineStart: 0 }, { text: opts.text, fenceOverlay: opts.overlay });
const map: MappedPart[] = [];
- const factsTexts: string[] = [];
let projBytes = 0;
- for (const part of segmentProjectionParts(raw, segment.protectedRegions, segment.byteStart)) {
- let text = '';
- if (part.kind === 'text' || part.kind === 'pem') text = part.text;
- else if (part.kind === 'facts' && part.region!.open_start === undefined) {
- factsTexts.push(part.text);
- text = credentialSafeProjection(renderFactsRegion(splitFenceOverlay(part.text, opts.overlay).main));
- }
- if (!text) continue;
- const bytes = Buffer.byteLength(text, 'utf8');
- map.push({ projStart: projBytes, projEnd: projBytes + bytes, rawStart: part.start, rawEnd: part.end, linear: part.kind === 'text' });
- pieces.push(text);
+ for (const piece of projected.pieces) {
+ const bytes = Buffer.byteLength(piece.text, 'utf8');
+ map.push({ projStart: projBytes, projEnd: projBytes + bytes, rawStart: piece.rawStart, rawEnd: piece.rawEnd, linear: piece.linear });
projBytes += bytes;
}
- const projection = pieces.join('');
+ const projection = projected.pieces.map(piece => piece.text).join('');
const source = segment.region === 'truth' ? 'compiled_truth' : 'timeline';
const chunks: SegmentChunk[] = [];
const push = (c: Omit<SegmentChunk, 'local_ordinal'>) => chunks.push({ ...c, local_ordinal: chunks.length });
@@ -110,12 +110,10 @@ export async function prepareSegmentChunks(segment: ChunkableSegment, opts: Segm
}
}
- if (factsTexts.length) {
- for (const { tier, unconfirmed, body } of splitFenceOverlay(factsTexts.join('\n'), opts.overlay).lowTier) {
- const room = Math.max(1, maxTokens - estimateEmbedTokens(fenceTrustMarker(tier, unconfirmed)) - 1);
- for (const c of chunkText(body, { maxTokens: room })) {
- push({ chunk_text: markFenceChunk(tier, c.text, unconfirmed), chunk_source: source, ...wholeSegment });
- }
+ for (const { tier, unconfirmed, body } of renderFenceLowTier(projected.lowTier)) {
+ const room = Math.max(1, maxTokens - estimateEmbedTokens(fenceTrustMarker(tier, unconfirmed)) - 1);
+ for (const c of chunkText(body, { maxTokens: room })) {
+ push({ chunk_text: markFenceChunk(tier, c.text, unconfirmed), chunk_source: source, ...wholeSegment });
}
}
return chunks;
diff --git a/src/core/page-body/segment-ledger.ts b/src/core/page-body/segment-ledger.ts
new file mode 100644
index 0000000000..76c3625bf5
--- /dev/null
+++ b/src/core/page-body/segment-ledger.ts
@@ -0,0 +1,48 @@
+/**
+ * Segmented page storage (Wave B, spec 7.3 item 5): the withdrawal overlay of
+ * one segment. readPageSnapshot overlays an inline body whole; a segmented
+ * body is overlaid segment by segment, with the same ledger (the page's
+ * withdrawals, subject '*' included, and its '*' purge marker) and the same
+ * DB normalization (overlayCanonicalBodies), so the 16,384-marker
+ * capacity applies per segment. Used by every reader of segment text that
+ * must not show withdrawn rows: the segment reader and the segment chunker.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { partialFenceRuns } from '../facts/withdrawal-overlay.ts';
+import { overlayCanonicalBodies } from '../page-state/snapshot.ts';
+import type { GlobalPurgeMarker, PageWithdrawal } from '../page-state/types.ts';
+import { readEntryState } from './entry-state.ts';
+import { projectionStaleError } from './segment-projection.ts';
+
+/** The withdrawal ledger of a page (readPageSnapshot's `withdrawals` and `globalPurges`). */
+export interface BodyLedger { withdrawals: PageWithdrawal[]; globalPurges?: GlobalPurgeMarker }
+
+export async function readBodyLedger(engine: Pick<BrainEngine, 'readPageSnapshot'>, sourceId: string, slug: string): Promise<BodyLedger> {
+ const snapshot = await engine.readPageSnapshot(slug, { sourceId, includeDeleted: true });
+ return { withdrawals: snapshot?.withdrawals ?? [], ...(snapshot?.globalPurges ? { globalPurges: snapshot.globalPurges } : {}) };
+}
+
+export function ledgerApplies(ledger: BodyLedger): boolean {
+ return ledger.withdrawals.length > 0 || (ledger.globalPurges?.count ?? 0) > 0;
+}
+
+/**
+ * The segment's text after the page's withdrawal overlay. A fence block a
+ * forced cut splits cannot be overlaid from one segment: with a ledger that
+ * applies, the read view omits its runs here (`view: 'read'`, fail closed) and
+ * a trusted body read refuses with `page_projection_stale`.
+ */
+export async function overlaySegmentText(engine: Pick<BrainEngine, 'executeRaw'>, ledger: BodyLedger,
+ segment: { sourceId: string; byteStart: number; entryState: unknown }, raw: string, view: 'read' | 'trusted'): Promise<string> {
+ if (!ledgerApplies(ledger)) return raw;
+ const query = <T>(sql: string, params?: unknown[]) => engine.executeRaw<T>(sql, params);
+ const text = raw.includes('gbrain:facts:begin')
+ ? (await overlayCanonicalBodies(query, raw, '', ledger.withdrawals, { sourceId: segment.sourceId, marker: ledger.globalPurges })).compiled_truth
+ : raw;
+ const entryOpen = readEntryState(segment.entryState)?.withdrawal.open === true;
+ if (!entryOpen && !text.includes('gbrain:facts:')) return text;
+ const { head, tail } = partialFenceRuns(text, entryOpen);
+ if (head === 0 && tail === text.length) return text;
+ if (view === 'trusted') throw projectionStaleError(segment.byteStart, 'a facts fence block crosses a forced cut and the source has withdrawals');
+ return text.slice(head, Math.max(head, tail));
+}
diff --git a/src/core/page-body/segment-projection.ts b/src/core/page-body/segment-projection.ts
new file mode 100644
index 0000000000..a9df817f37
--- /dev/null
+++ b/src/core/page-body/segment-projection.ts
@@ -0,0 +1,162 @@
+/**
+ * Segmented page storage (Wave B, spec 7.3): one segment's read projection,
+ * the text whole-body sanitization (page-window/document.ts projectPageText)
+ * gives for that stretch of the body, computed from the segment alone.
+ *
+ * Whole segments are projected, never a bare slice: the stored protected
+ * regions remove takes runs, a truncated tail, materialized markers and the
+ * pem guard, replace each private key with the projection token plus its
+ * newlines, and leave each facts region as a slot rendered here (world rows
+ * only, minus rows the text marks forgotten, through renderFactsRegion; a
+ * region crossing the segment's bounds is omitted). The caller hands in the
+ * segment text after the withdrawal overlay; this applies the fence overlay
+ * (held and purged rows out, rows below the page tier moved to the low-tier
+ * block). When either changed the text, or the stored metadata is stale, the
+ * regions are recomputed by segmenting the text from the segment's carried
+ * entry state; with no usable entry state the read refuses with
+ * `page_projection_stale`, never raw text.
+ *
+ * Each piece maps back to the stored bytes it stands for, so a stored-space
+ * range selects pieces: text is cut byte for byte where the mapping is
+ * linear; a token, a rendered facts table or text a transform rewrote is
+ * emitted whole or not at all.
+ */
+import { opError } from '../ops/contract.ts';
+import { renderFactsRegion } from '../remote-body.ts';
+import { credentialSafeProjection } from '../credential-projection.ts';
+import { fenceLowTierRows, splitFenceOverlay, type FenceChunkOverlay, type FenceLowTierRow } from '../eligibility/fence-overlay.ts';
+import { readEntryState } from './entry-state.ts';
+import { utf8Len } from './region-scan.ts';
+import { segmentProjectionParts, segmentString, type StoredRegion } from './segmenter.ts';
+import type { BodyRegion } from './types.ts';
+
+const utf8 = new TextDecoder('utf-8', { fatal: true });
+
+/** The stored parts of one segment the projection reads (a manifest row and its text). */
+export interface ProjectableSegment {
+ region: BodyRegion;
+ bytes: Uint8Array;
+ /** Stored-stream offset and 0-based raw line of the segment's first byte. */
+ byteStart: number;
+ lineStart: number;
+ /** The stored entry state (JSON); only read when the regions are recomputed. */
+ entryState: unknown;
+ protectedRegions: readonly StoredRegion[];
+ /** The region's fence trust (body_flags), the trust stored regions were computed under. */
+ fenceTrust: 'trusted' | 'void';
+}
+
+export interface SegmentProjectionInput {
+ /** The segment text after the withdrawal overlay; defaults to the stored text. */
+ text?: string;
+ fenceOverlay?: FenceChunkOverlay;
+ /** The stored regions cannot be trusted (segmenter version or sha mismatch): recompute from the entry state. */
+ stale?: boolean;
+}
+
+/** A run of the projection: `text`, standing for stored bytes [rawStart, rawEnd) of the segment (segment-relative). */
+export interface ProjectedPiece {
+ text: string;
+ rawStart: number;
+ rawEnd: number;
+ /** Projected text equals the stored bytes, so a stored range may cut it; otherwise it is emitted whole or not at all. */
+ linear: boolean;
+}
+
+export interface SegmentProjection {
+ pieces: ProjectedPiece[];
+ /** Rendered facts regions in slot order (bytes), for the outline's static-to-projected offsets. */
+ factsBytes: number[];
+ /** Rows the fence overlay moved to the page's low-tier block. */
+ lowTier: FenceLowTierRow[];
+ /** The regions were recomputed (a transform changed the text, or the metadata was stale). */
+ recomputed: boolean;
+}
+
+/** `page_projection_stale`: the segment's stored projection metadata is unusable and cannot be recomputed. */
+export function projectionStaleError(byteStart: number, why: string) {
+ return opError('page_projection_stale',
+ `The segment at stored byte ${byteStart} cannot be projected: ${why}. Nothing was returned for it.`,
+ 'Rewrite the page body (import or sync its file again) so it is segmented by this gbrain version, then read it again.');
+}
+
+export function projectSegment(segment: ProjectableSegment, input: SegmentProjectionInput = {}): SegmentProjection {
+ const raw = utf8.decode(segment.bytes);
+ const overlaid = input.text ?? raw;
+ const split = splitFenceOverlay(overlaid, input.fenceOverlay);
+ const lowTier = fenceLowTierRows(overlaid, input.fenceOverlay);
+ const text = split.main;
+ const recompute = input.stale === true || text !== raw;
+ const parts = recompute ? recomputedParts(segment, text) : segmentProjectionParts(raw, segment.protectedRegions, segment.byteStart);
+ const map = recompute ? diffMap(raw, text) : null;
+ const pieces: ProjectedPiece[] = [];
+ const factsBytes: number[] = [];
+ for (const part of parts) {
+ let out = '';
+ if (part.kind === 'text' || part.kind === 'pem') out = part.text;
+ else if (part.kind === 'facts') {
+ out = part.region!.open_start === undefined ? credentialSafeProjection(renderFactsRegion(part.text)) : '';
+ factsBytes.push(utf8Len(out));
+ }
+ if (!out) continue;
+ const at = map ? map(part.start, part.end) : { start: part.start, end: part.end, linear: true };
+ pieces.push({ text: out, rawStart: at.start, rawEnd: at.end, linear: part.kind === 'text' && at.linear });
+ }
+ return { pieces, factsBytes, lowTier, recomputed: recompute };
+}
+
+/**
+ * The trusted body view of a segment (its stored text after the withdrawal overlay) as pieces: one linear piece when
+ * the overlay changed nothing, else the unchanged prefix and suffix linear and the rewritten middle whole.
+ */
+export function overlaidPieces(raw: string, text: string): ProjectedPiece[] {
+ if (text === raw) return raw ? [{ text: raw, rawStart: 0, rawEnd: utf8Len(raw), linear: true }] : [];
+ const map = diffMap(raw, text);
+ const bytes = Buffer.from(text, 'utf8');
+ const cuts = [...new Set([0, map.head, map.textTail, bytes.length])].filter(b => b >= 0 && b <= bytes.length).sort((a, b) => a - b);
+ const pieces: ProjectedPiece[] = [];
+ for (let i = 0; i + 1 < cuts.length; i++) {
+ const at = map(cuts[i]!, cuts[i + 1]!);
+ pieces.push({ text: bytes.subarray(cuts[i]!, cuts[i + 1]!).toString('utf8'), rawStart: at.start, rawEnd: at.end, linear: at.linear });
+ }
+ return pieces;
+}
+
+/** The projection parts of `text` (the segment's text after a transform), segmented from the stored entry state. */
+function recomputedParts(segment: ProjectableSegment, text: string) {
+ const entry = readEntryState(segment.entryState);
+ if (!entry || entry.region !== segment.region) throw projectionStaleError(segment.byteStart, 'its entry state is missing or of another version');
+ const segments = segmentString(text, entry, { byteStart: segment.byteStart, lineStart: segment.lineStart, fenceTrust: segment.fenceTrust, end: 'eof' });
+ return segments.flatMap(out => {
+ const shift = out.byteStart - segment.byteStart;
+ return segmentProjectionParts(utf8.decode(out.bytes), out.protectedRegions, out.byteStart)
+ .map(part => ({ ...part, start: part.start + shift, end: part.end + shift }));
+ });
+}
+
+/**
+ * Stored bytes of a transformed text's byte range: the common prefix and suffix of the stored and transformed texts map
+ * exactly, the rewritten middle maps to its whole stored extent.
+ */
+interface DiffMap {
+ (start: number, end: number): { start: number; end: number; linear: boolean };
+ /** Transformed-text bytes of the common prefix, and where the common suffix starts. */
+ head: number;
+ textTail: number;
+}
+
+function diffMap(raw: string, text: string): DiffMap {
+ const high = (c: number) => c >= 0xd800 && c <= 0xdbff;
+ let p = 0;
+ while (p < raw.length && p < text.length && raw.charCodeAt(p) === text.charCodeAt(p)) p++;
+ if (p > 0 && high(raw.charCodeAt(p - 1))) p--;
+ let q = 0;
+ while (q < raw.length - p && q < text.length - p && raw.charCodeAt(raw.length - 1 - q) === text.charCodeAt(text.length - 1 - q)) q++;
+ if (q > 0 && high(raw.charCodeAt(raw.length - 1 - q))) q--;
+ const head = utf8Len(raw, 0, p);
+ const rawTail = utf8Len(raw) - utf8Len(raw, raw.length - q);
+ const textTail = utf8Len(text) - utf8Len(text, text.length - q);
+ const at = (b: number, end: boolean) => b <= head ? b : b >= textTail ? b - textTail + rawTail : end ? rawTail : head;
+ return Object.assign((start: number, end: number) => ({ start: at(start, false), end: at(end, true), linear: end <= head || start >= textTail }),
+ { head, textTail });
+}
diff --git a/src/core/persistence/segmented-apply.ts b/src/core/persistence/segmented-apply.ts
index b0d5d7f5b0..275d08d986 100644
--- a/src/core/persistence/segmented-apply.ts
+++ b/src/core/persistence/segmented-apply.ts
@@ -30,6 +30,7 @@ import { SEGMENTED_CHUNKER_VERSION } from '../page-body/segment-chunks.ts';
import { PAGE_MAX_BYTES } from '../page-size-policy.ts';
import { pageSearchVectorSql } from '../fts-language.ts';
import { sanitizeRemoteBody } from '../remote-body.ts';
+import { overlayCanonicalBodies, readPageSnapshot } from '../page-state/snapshot.ts';
import { faultPoint } from './fault-points.ts';
import { stableJson } from './digest.ts';
@@ -117,11 +118,19 @@ export interface SegmentedApplyInput {
/** `complete`: every occurrence has chunks and the flip retired the old rows, so the caller seals as its last step (`sealSegmentedPage`). */
export interface SegmentedApplied { pageId: number; complete: boolean; retireDeferred: boolean }
-/** Seal a segmented page's text projection at its current revision (chunks visible, title + timeline lead searchable). */
+/**
+ * Seal a segmented page's text projection at its current revision (chunks visible, title + timeline lead searchable).
+ * The lead is indexed as the inline seal indexes a snapshot's timeline: after the page's withdrawal overlay, sanitized.
+ */
export async function sealSegmentedPage(tx: Pick<BrainEngine, 'executeRaw'>, pageId: number, timelineLead?: string): Promise<void> {
- const lead = timelineLead ?? (await tx.executeRaw<{ timeline_lead: string | null }>('SELECT timeline_lead FROM pages WHERE id=$1', [pageId]))[0]?.timeline_lead ?? '';
+ const [page] = await tx.executeRaw<{ slug: string; source_id: string; timeline_lead: string | null }>('SELECT slug, source_id, timeline_lead FROM pages WHERE id=$1', [pageId]);
+ if (!page) return;
+ const query = <T>(sql: string, params?: unknown[]) => tx.executeRaw<T>(sql, params);
+ const ledger = await readPageSnapshot(query, page.slug, { sourceId: page.source_id, includeDeleted: true });
+ const { timeline } = await overlayCanonicalBodies(query, '', timelineLead ?? page.timeline_lead ?? '', ledger?.withdrawals ?? [],
+ { sourceId: page.source_id, marker: ledger?.globalPurges });
await tx.executeRaw(`UPDATE pages SET text_projection_revision=knowledge_revision, chunker_version=$3,
- search_vector=${pageSearchVectorSql('title', '$2')} WHERE id=$1`, [pageId, sanitizeRemoteBody(lead), SEGMENTED_CHUNKER_VERSION]);
+ search_vector=${pageSearchVectorSql('title', '$2')} WHERE id=$1`, [pageId, sanitizeRemoteBody(timeline), SEGMENTED_CHUNKER_VERSION]);
}
/** The segmented branch of a page write's apply, inside the publication transaction. */
diff --git a/test/helpers/segmented-chunks-fixture.ts b/test/helpers/segmented-chunks-fixture.ts
index a25fc1e914..9ab992f709 100644
--- a/test/helpers/segmented-chunks-fixture.ts
+++ b/test/helpers/segmented-chunks-fixture.ts
@@ -10,6 +10,7 @@ import { createHash } from 'node:crypto';
import type { BrainEngine } from '../../src/core/engine.ts';
import { resolveActiveEmbeddingColumnFromEngine } from '../../src/core/search/embedding-column.ts';
import { installFixtureChunks } from './page-projection.ts';
+import { SEGMENTED_CHUNKER_VERSION } from '../../src/core/page-body/segment-chunks.ts';
export interface FixtureChunk {
text: string;
@@ -84,7 +85,8 @@ export async function segmentPage(engine: BrainEngine, slug: string, opts: {
chunkIds.set(chunk.text, Number(row!.id));
}
}
- // Clearing the body and replacing the rows unseals the projection; the fixture's rows are the projection.
- await engine.executeRaw('UPDATE pages SET text_projection_revision = knowledge_revision WHERE id = $1', [pageId]);
+ // Clearing the body and replacing the rows unseals the projection; the fixture's rows are the projection, sealed at
+ // the chunker version sealSegmentedPage stamps.
+ await engine.executeRaw('UPDATE pages SET text_projection_revision = knowledge_revision, chunker_version = $2 WHERE id = $1', [pageId, SEGMENTED_CHUNKER_VERSION]);
return { pageId, chunkIds };
}
diff --git a/test/helpers/segmented-privacy-fixture.ts b/test/helpers/segmented-privacy-fixture.ts
new file mode 100644
index 0000000000..5ad70aa42d
--- /dev/null
+++ b/test/helpers/segmented-privacy-fixture.ts
@@ -0,0 +1,153 @@
+/**
+ * Wave B PR 2: segmented pages seeded with private text in every place the
+ * read projection must hide it (takes, private and withdrawn facts rows,
+ * held rows, purged rows, private keys, a truncated tail, a facts fence
+ * longer than a segment), plus the inline reference projection of the same
+ * stored body. Shared by the segment reader's parity and privacy tests and by
+ * the get_page / evidence lanes that extend them to their surfaces.
+ */
+import { expect } from 'bun:test';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { importFromContent } from '../../src/core/import-file.ts';
+import { renderFactsTable, type ParsedFact } from '../../src/core/facts-fence.ts';
+import { holdFingerprint } from '../../src/core/write-gate-store.ts';
+import { fenceRowHoldTexts } from '../../src/core/eligibility/fence-overlay.ts';
+import { materializeSegmentedBody } from '../../src/core/page-body/ingest.ts';
+import { overlayCanonicalBodies } from '../../src/core/page-state/snapshot.ts';
+import { readPageDocument } from '../../src/core/page-window/document.ts';
+import { readBodyRange, type BodyRangeRequest } from '../../src/core/page-body/read-range.ts';
+import { KEY_BODY, PEM_BEGIN_RSA, PEM_BLOCK, PEM_END_RSA, paragraph, pick, soup } from './segment-bodies.ts';
+
+/** Text no remote window, outline or evidence block may contain. KEY_BODY is the synthetic private key's body. */
+export const PRIVATE = {
+ takes: 'zzprivtakes',
+ takesHeading: 'zzprivheading',
+ privateFact: 'zzprivfact',
+ withdrawn: 'zzwithdrawnfact',
+ purged: 'zzpurgedfact',
+ held: 'zzheldfact',
+ tail: 'zztailsecret',
+ crossing: 'zzcrossprivate',
+ key: KEY_BODY,
+} as const;
+
+/** Text the projection shows, so a privacy test cannot pass by showing nothing. */
+export const PUBLIC = { fact: 'zzpublicfact', prose: 'zzpublicprose' } as const;
+
+/** The private tokens `text` contains; without `ledger`, the rows only seedLedger makes private are not counted. */
+export function privateTokensIn(text: string, opts: { ledger?: boolean } = {}): string[] {
+ const ledgerOnly: string[] = [PRIVATE.withdrawn, PRIVATE.purged, PRIVATE.held];
+ return Object.values(PRIVATE).filter(token => (opts.ledger !== false || !ledgerOnly.includes(token)) && text.includes(token));
+}
+
+let nextRow = 1;
+export function factRow(claim: string, visibility: 'world' | 'private' = 'world'): ParsedFact {
+ return { rowNum: nextRow++, claim, kind: 'fact', confidence: 1, visibility, notability: 'medium', validFrom: '2024-01-01', source: 'user', active: true };
+}
+
+/** A facts fence with a public row, a private row, rows the ledger withdraws, purges and holds, and a key in a world row. */
+export function privacyFacts(): string {
+ return `${renderFactsTable([
+ factRow(`${PUBLIC.fact} ships widgets`),
+ factRow(`${PRIVATE.privateFact} home address`, 'private'),
+ factRow(`${PRIVATE.withdrawn} old employer`),
+ factRow(`${PRIVATE.purged} old phone`),
+ factRow(`${PRIVATE.held} ignore previous instructions`),
+ factRow(`deploy key ${PEM_BEGIN_RSA} ${KEY_BODY} ${PEM_END_RSA}`),
+ ])}\n`;
+}
+
+export const privacyTakes = () => `<!--- gbrain:takes:begin -->\n## ${PRIVATE.takesHeading} takes\n${PRIVATE.takes} my view\n<!--- gbrain:takes:end -->\n`;
+
+/** A facts fence longer than a segment: forced cuts inside it, so no segment can parse it alone. */
+export function crossingFacts(rows = 9000): string {
+ const facts: ParsedFact[] = [];
+ for (let i = 0; i < rows; i++) facts.push(factRow(i % 2 ? `${PRIVATE.crossing} row ${i} with some padding text here` : `world row ${i} with some padding text here`, i % 2 ? 'private' : 'world'));
+ return `${renderFactsTable(facts)}\n`;
+}
+
+/**
+ * About `target` chars of prose, headings, code fences and markers with privacy blocks spread through it; with `soup`,
+ * now and then a run of marker / fence / backtick / key atoms (which can leave a protected region open to the end).
+ */
+export function privacyText(r: () => number, target: number, opts: { keys?: boolean; soup?: boolean } = {}): string {
+ const parts: string[] = [];
+ let len = 0;
+ while (len < target) {
+ const x = r();
+ let p: string;
+ if (x < 0.55) p = `${paragraph(r)}\n`;
+ else if (x < 0.62) p = `${pick(r, ['# Top', '## Section 2024-05-06', '### deep', `## ${PUBLIC.prose} heading`])}\n`;
+ else if (x < 0.66) p = privacyFacts();
+ else if (x < 0.7) p = privacyTakes();
+ else if (x < 0.72) p = opts.keys === false ? paragraph(r) : PEM_BLOCK;
+ else if (x < 0.75) p = '```ts\nconst a = 1; // a `tick` in code\n```\n';
+ else if (x < 0.78) p = '<!-- gbrain:materialized v1 0123456789ab -->\n- **2024-01-02** | src — did a thing\n detail line\n';
+ else if (x < 0.8) p = `inline \`code\` and ${PUBLIC.prose} \`\`more\`\` text\n`;
+ else if (x < 0.803 && opts.soup) p = `${soup(r)}\n`;
+ else p = `${paragraph(r)}\n`;
+ parts.push(p);
+ len += p.length;
+ }
+ return parts.join('');
+}
+
+export function pageContent(truth: string, timeline = ''): string {
+ return `---\ntitle: Privacy probe\ntype: note\n---\n${truth}${timeline ? `\n\n<!-- timeline -->\n\n${timeline}` : ''}`;
+}
+
+/** Import `content` with segmented storage on and return the page id; the page must come out segmented. */
+export async function importSegmented(engine: BrainEngine, slug: string, content: string): Promise<number> {
+ await engine.setConfig('pages.segmented_storage', 'on');
+ await importFromContent(engine, slug, content, { sourceId: 'default', noEmbed: true });
+ const [page] = await engine.executeRaw<{ id: number; body_storage: string }>('SELECT id, body_storage FROM pages WHERE source_id=$1 AND slug=$2', ['default', slug]);
+ expect(page?.body_storage).toBe('segmented');
+ return Number(page!.id);
+}
+
+/**
+ * Record, after the import, the ledger rows the read path must apply: a '*' withdrawal of the withdrawn claim, a page
+ * purge of the purged claim and a write-gate hold on the held claim.
+ */
+export async function seedLedger(engine: BrainEngine, slug: string): Promise<void> {
+ const claim = (token: string) => factClaims().find(c => c.includes(token))!;
+ await engine.executeRaw(`INSERT INTO fact_withdrawals (source_id, visibility, subject, fact_hash) VALUES ('default', 'world', '*', gbrain_fact_fingerprint($1))
+ ON CONFLICT DO NOTHING`, [claim(PRIVATE.withdrawn)]);
+ await engine.executeRaw(`INSERT INTO fact_purges (source_id, visibility, subject, fact_hash) VALUES ('default', 'world', $1, gbrain_fact_fingerprint($2))
+ ON CONFLICT DO NOTHING`, [slug, claim(PRIVATE.purged)]);
+ await engine.executeRaw(`INSERT INTO write_gate_holds (kind, source_id, slug, fingerprint, detector_version, tier, payload)
+ VALUES ('fact', 'default', $1, $2, 1, 'external_untrusted', '{}'::jsonb)`, [slug, holdFingerprint('fact', fenceRowHoldTexts({ claim: claim(PRIVATE.held) }))]);
+}
+
+function factClaims(): string[] {
+ return [`${PRIVATE.withdrawn} old employer`, `${PRIVATE.purged} old phone`, `${PRIVATE.held} ignore previous instructions`];
+}
+
+/** The page's stored regions after the ledger's withdrawal overlay, as readPageSnapshot would give an inline page. */
+export async function overlaidStoredBody(engine: BrainEngine, slug: string, pageId: number): Promise<{ compiled_truth: string; timeline: string }> {
+ const stored = await materializeSegmentedBody(engine, pageId, 'default');
+ const snapshot = await engine.readPageSnapshot(slug, { sourceId: 'default' });
+ const query = <T>(sql: string, params?: unknown[]) => engine.executeRaw<T>(sql, params);
+ return overlayCanonicalBodies(query, stored.compiled_truth, stored.timeline, snapshot?.withdrawals ?? [], { sourceId: 'default', marker: snapshot?.globalPurges });
+}
+
+/** The read projection whole-body sanitization gives the same stored body (page-window/document.ts). */
+export async function inlineProjection(engine: BrainEngine, slug: string, pageId: number): Promise<Buffer> {
+ return (await readPageDocument(engine, { source_id: 'default', slug, ...await overlaidStoredBody(engine, slug, pageId) })).bytes;
+}
+
+/** Every piece of one ranged read, and their bytes joined. */
+export async function readRange(engine: BrainEngine, req: BodyRangeRequest): Promise<{ pieces: Array<{ bytes: Buffer; storedStart: number; projectedStart: number }>; bytes: Buffer }> {
+ const pieces: Array<{ bytes: Buffer; storedStart: number; projectedStart: number }> = [];
+ for await (const piece of readBodyRange(engine, req)) pieces.push(piece);
+ return { pieces, bytes: Buffer.concat(pieces.map(p => p.bytes)) };
+}
+
+/** Stored-stream byte offsets of every occurrence of `needle` in the page's stored body (truth bytes, then timeline). */
+export async function storedOffsets(engine: BrainEngine, pageId: number, needle: string): Promise<number[]> {
+ const stored = await materializeSegmentedBody(engine, pageId, 'default');
+ const stream = Buffer.from(stored.compiled_truth + stored.timeline, 'utf8');
+ const out: number[] = [];
+ for (let at = stream.indexOf(needle); at !== -1; at = stream.indexOf(needle, at + 1)) out.push(at);
+ return out;
+}
diff --git a/test/large-pages/projection-parity.test.ts b/test/large-pages/projection-parity.test.ts
new file mode 100644
index 0000000000..8e063f3ca7
--- /dev/null
+++ b/test/large-pages/projection-parity.test.ts
@@ -0,0 +1,189 @@
+/**
+ * Wave B PR 2 (spec 7.3 item 8): the segment reader's read projection equals
+ * whole-body sanitization of the same stored body, byte for byte.
+ *
+ * 1. Protects: readBodyRange over a segmented page, in projected space (any
+ * window) and stored space (remote: pieces sit at their projected
+ * offsets; trusted: the overlaid stored stream), equals projectPageText
+ * over the joined body (readPageDocument), across marker, fence, backtick,
+ * key, facts and takes soup, a ledger (withdrawn, purged and held rows),
+ * low-tier rows, a timeline, stale metadata; plus totals, line starts and
+ * the outline. A case that cannot match byte for byte (a facts fence
+ * longer than a segment) never shows more.
+ * 2. Fails when: a segment is projected without its stored regions, the
+ * withdrawal or fence overlay is skipped, the low-tier block or the
+ * timeline separator moves, an offset sum drifts, or stale metadata serves
+ * the stored text.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { testBackends } from '../helpers/test-backends.ts';
+import { maintenanceTransaction } from '../../src/core/persistence/attribution.ts';
+import { withTrustBackfill } from '../../src/core/persistence/context.ts';
+import { lineOffset, pageOutline, totalLines } from '../../src/core/page-window/window.ts';
+import {
+ openSegmentedBody, projectedLayout, projectedLineStart, projectedOutline, projectedTotals,
+} from '../../src/core/page-body/read-range.ts';
+import { mulberry32 } from '../helpers/seeded-random.ts';
+import {
+ PRIVATE, PUBLIC, crossingFacts, factRow, importSegmented, inlineProjection, overlaidStoredBody, pageContent, privacyText, privateTokensIn,
+ readRange, seedLedger,
+} from '../helpers/segmented-privacy-fixture.ts';
+import { renderFactsTable } from '../../src/core/facts-fence.ts';
+import { KEY_BODY } from '../helpers/segment-bodies.ts';
+
+let engine: BrainEngine;
+
+const KEYS = (s: string) => s.split(KEY_BODY).length - 1;
+
+/** Every way of reading the page agrees with the inline projection `want`. */
+async function expectParity(pageId: number, want: Buffer, r: () => number, stored: { compiled_truth: string; timeline: string }) {
+ const body = await openSegmentedBody(engine, { pageId });
+ const whole = await readRange(engine, { pageId, space: 'projected', start: 0, end: Infinity, audience: 'remote', body });
+ expect(whole.bytes.equals(want)).toBe(true);
+ const trusted = await readRange(engine, { pageId, space: 'projected', start: 0, end: Infinity, audience: 'trusted', body });
+ expect(trusted.bytes.equals(want)).toBe(true);
+ for (let i = 0; i < 12; i++) {
+ const start = Math.floor(r() * want.length);
+ const end = Math.min(want.length, start + 1 + Math.floor(r() * 300_000));
+ const win = await readRange(engine, { pageId, space: 'projected', start, end, audience: 'remote', body });
+ expect(win.bytes.equals(want.subarray(start, end))).toBe(true);
+ for (const piece of win.pieces) expect(piece.bytes.equals(want.subarray(piece.projectedStart, piece.projectedStart + piece.bytes.length))).toBe(true);
+ }
+ const remoteStored = await readRange(engine, { pageId, space: 'stored', start: 0, end: Infinity, audience: 'remote', body });
+ for (const piece of remoteStored.pieces) expect(piece.bytes.equals(want.subarray(piece.projectedStart, piece.projectedStart + piece.bytes.length))).toBe(true);
+ const trustedStored = await readRange(engine, { pageId, space: 'stored', start: 0, end: Infinity, audience: 'trusted', body });
+ expect(trustedStored.bytes.toString('utf8')).toBe(stored.compiled_truth + stored.timeline);
+ const totals = await projectedTotals(engine, body);
+ expect(totals.total_bytes).toBe(want.length);
+ expect(totals.total_lines).toBe(totalLines(want));
+ for (let i = 0; i < 6; i++) {
+ const line = 1 + Math.floor(r() * (totals.total_lines + 2));
+ expect(await projectedLineStart(engine, body, line)).toBe(lineOffset(want, line));
+ }
+ return body;
+}
+
+for (const kind of testBackends()) {
+ describe(`read projection parity (${kind})`, () => {
+ let close: () => Promise<void>;
+
+ beforeAll(async () => {
+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ close = () => engine.disconnect();
+ }
+ }, 120_000);
+
+ afterAll(async () => { await close(); });
+
+ beforeEach(async () => {
+ for (const table of ['pages', 'fact_withdrawals', 'fact_purges', 'write_gate_holds', 'facts']) await engine.executeRaw(`DELETE FROM ${table}`);
+ });
+
+ test('soup pages, no ledger: every window, both audiences, both spaces equal the inline projection', async () => {
+ const r = mulberry32(17);
+ for (let t = 0; t < 3; t++) {
+ const slug = `notes/parity-${t}`;
+ const timeline = t === 2 ? '' : privacyText(r, 200_000 + Math.floor(r() * 400_000));
+ const pageId = await importSegmented(engine, slug, pageContent(privacyText(r, 1_200_000 + Math.floor(r() * 900_000), { soup: t === 1 }), timeline));
+ const want = await inlineProjection(engine, slug, pageId);
+ const stored = await overlaidStoredBody(engine, slug, pageId);
+ const body = await expectParity(pageId, want, r, stored);
+ expect(body.rows.length).toBeGreaterThan(3);
+ expect(body.layout!.timelineByte >= 0).toBe(t !== 2);
+ }
+ }, 240_000);
+
+ test('with a ledger: withdrawn, purged and held rows leave every view exactly as readPageSnapshot overlays them', async () => {
+ const r = mulberry32(29);
+ for (let t = 0; t < 2; t++) {
+ const slug = `notes/ledger-${t}`;
+ const pageId = await importSegmented(engine, slug, pageContent(privacyText(r, 1_400_000), privacyText(r, 300_000)));
+ await seedLedger(engine, slug);
+ const want = await inlineProjection(engine, slug, pageId);
+ const text = want.toString('utf8');
+ expect(text).toContain(PUBLIC.fact);
+ expect(privateTokensIn(text)).toEqual([]);
+ const stored = await overlaidStoredBody(engine, slug, pageId);
+ expect(stored.compiled_truth).not.toContain(PRIVATE.purged);
+ await expectParity(pageId, want, r, stored);
+ }
+ }, 240_000);
+
+ test('rows below the page tier move to the low-tier block after the truth, truth rows before timeline rows', async () => {
+ const r = mulberry32(41);
+ const truthRow = factRow('zzagentrow truth claim');
+ const timelineRow = factRow('zzagentrow timeline claim');
+ const slug = 'notes/low-tier';
+ const truth = privacyText(r, 1_200_000, { keys: false }) + renderFactsTable([factRow('zzownerrow claim'), truthRow]) + '\n' + privacyText(r, 300_000, { keys: false });
+ const pageId = await importSegmented(engine, slug, pageContent(truth, `${renderFactsTable([timelineRow])}\n${privacyText(r, 100_000)}`));
+ await engine.transaction(tx => withTrustBackfill(tx, () => tx.executeRaw("UPDATE pages SET trust_tier='operator_curated' WHERE id=$1", [pageId])));
+ for (const row of [truthRow, timelineRow]) {
+ await maintenanceTransaction(engine, tx => tx.insertFacts([{ fact: row.claim, kind: 'fact', entity_slug: slug, visibility: 'world', source: 'test',
+ valid_from: new Date('2024-01-01'), row_num: row.rowNum, source_markdown_slug: slug }], { source_id: 'default' }), { tier: 'agent_written', origin: { channel: 'test:fence' } });
+ }
+ const want = await inlineProjection(engine, slug, pageId);
+ const body = await expectParity(pageId, want, r, await overlaidStoredBody(engine, slug, pageId));
+ const layout = await projectedLayout(engine, body);
+ expect(layout.lowTier).toContain('zzagentrow truth claim');
+ expect(layout.lowTier.indexOf('zzagentrow truth claim')).toBeLessThan(layout.lowTier.indexOf('zzagentrow timeline claim'));
+ }, 240_000);
+
+ test('the outline names every heading at its projected byte', async () => {
+ const r = mulberry32(53);
+ const slug = 'notes/outline';
+ const pageId = await importSegmented(engine, slug, pageContent(privacyText(r, 1_500_000), privacyText(r, 200_000)));
+ const want = await inlineProjection(engine, slug, pageId);
+ const body = await openSegmentedBody(engine, { pageId });
+ const all = await projectedOutline(engine, body, 0, 100_000);
+ const inline = pageOutline(want, 0, 100_000).entries.filter(e => e.heading);
+ expect(all.entries.map(e => `${e.heading}@${e.byte_start}`)).toEqual(inline.map(e => `${e.heading}@${e.byte_start}`));
+ const page = await projectedOutline(engine, body, 5, 7);
+ expect(page.entries).toEqual(all.entries.slice(5, 12));
+ expect(page.next_from_index).toBe(12);
+ }, 240_000);
+
+ test('stale metadata recomputes from the entry state; an unusable entry state refuses, never raw text', async () => {
+ const r = mulberry32(67);
+ const slug = 'notes/stale';
+ const pageId = await importSegmented(engine, slug, pageContent(privacyText(r, 1_300_000)));
+ const want = await inlineProjection(engine, slug, pageId);
+ await engine.executeRaw("UPDATE page_body_manifest SET protected_regions='[]'::jsonb WHERE page_id=$1", [pageId]);
+ await engine.executeRaw('UPDATE pages SET segmenter_version=0 WHERE id=$1', [pageId]);
+ const recomputed = await readRange(engine, { pageId, space: 'projected', start: 0, end: Infinity, audience: 'remote' });
+ expect(recomputed.bytes.equals(want)).toBe(true);
+ await engine.executeRaw("UPDATE page_body_manifest SET entry_state='{}'::jsonb WHERE page_id=$1", [pageId]);
+ const err = await readRange(engine, { pageId, space: 'stored', start: 0, end: 1000, audience: 'remote' }).catch(e => e);
+ expect(err?.code).toBe('page_projection_stale');
+ }, 240_000);
+
+ test('a facts fence longer than a segment cannot match byte for byte and never shows more', async () => {
+ const r = mulberry32(79);
+ const slug = 'notes/crossing';
+ const pageId = await importSegmented(engine, slug, pageContent(privacyText(r, 300_000) + crossingFacts() + privacyText(r, 400_000)));
+ const want = (await inlineProjection(engine, slug, pageId)).toString('utf8');
+ const got = (await readRange(engine, { pageId, space: 'projected', start: 0, end: Infinity, audience: 'remote' })).bytes.toString('utf8');
+ expect(got.length).toBeLessThan(want.length);
+ expect(privateTokensIn(got, { ledger: false })).toEqual([]);
+ expect(KEYS(got)).toBeLessThanOrEqual(KEYS(want));
+ expect(isSubsequence(got, want)).toBe(true);
+ }, 240_000);
+ });
+}
+
+/** `a`'s lines appear in `b` in order (per-segment projection only drops lines whole-body sanitization keeps). */
+function isSubsequence(a: string, b: string): boolean {
+ let at = 0;
+ for (const line of a.split('\n')) {
+ const found = b.indexOf(line, at);
+ if (found === -1) return false;
+ at = found + line.length;
+ }
+ return true;
+}
diff --git a/test/large-pages/remote-window-privacy.test.ts b/test/large-pages/remote-window-privacy.test.ts
new file mode 100644
index 0000000000..ad16de9873
--- /dev/null
+++ b/test/large-pages/remote-window-privacy.test.ts
@@ -0,0 +1,108 @@
+/**
+ * Wave B PR 2 (spec 7.3 item 9): no remote window of a segmented page shows
+ * text the whole-body read projection hides.
+ *
+ * 1. Protects: remote readBodyRange windows (stored and projected space) and
+ * the projected outline over pages seeded with takes, private facts rows,
+ * withdrawn / purged / held rows, private keys, a truncated tail and a
+ * facts fence longer than a segment; windows start inside each private
+ * block, on either side of every forced cut, and at random bytes.
+ * Without a ledger the withdrawn / purged / held rows are ordinary world
+ * rows, so only the ledger test counts them.
+ * 2. Fails when: a window projects only its slice (a block whose opener sits
+ * before the window start leaks), the truncated-tail rule is dropped, the
+ * ledger is not applied per segment, or a fence split by a forced cut is
+ * rendered from its half. PUBLIC tokens must still appear.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { testBackends } from '../helpers/test-backends.ts';
+import { openSegmentedBody, projectedOutline } from '../../src/core/page-body/read-range.ts';
+import { mulberry32 } from '../helpers/seeded-random.ts';
+import {
+ PRIVATE, PUBLIC, crossingFacts, importSegmented, pageContent, privacyText, privateTokensIn, readRange, seedLedger, storedOffsets,
+} from '../helpers/segmented-privacy-fixture.ts';
+
+let engine: BrainEngine;
+
+/** Remote windows at every interesting start: none may contain a private token; all of them together show the public ones. */
+async function expectNoLeak(pageId: number, r: () => number, needles: string[], ledger = false) {
+ const body = await openSegmentedBody(engine, { pageId });
+ const starts = new Set<number>();
+ for (const needle of needles) for (const at of (await storedOffsets(engine, pageId, needle)).slice(0, 8)) for (const d of [0, 1, 40, 400]) starts.add(Math.max(0, at - d));
+ for (const row of body.rows) for (const d of [-64, -1, 0, 1]) starts.add(Math.max(0, row.byteStart + d));
+ for (let i = 0; i < 20; i++) starts.add(Math.floor(r() * body.bodyBytes));
+ const seen = { public: new Set<string>() };
+ for (const start of starts) {
+ for (const space of ['stored', 'projected'] as const) {
+ const win = await readRange(engine, { pageId, space, start, end: start + 2_000 + Math.floor(r() * 60_000), audience: 'remote', body });
+ const text = win.bytes.toString('utf8');
+ expect({ start, space, leaked: privateTokensIn(text, { ledger }) }).toEqual({ start, space, leaked: [] });
+ for (const token of Object.values(PUBLIC)) if (text.includes(token)) seen.public.add(token);
+ }
+ }
+ const whole = (await readRange(engine, { pageId, space: 'projected', start: 0, end: Infinity, audience: 'remote', body })).bytes.toString('utf8');
+ expect(privateTokensIn(whole, { ledger })).toEqual([]);
+ for (const token of Object.values(PUBLIC)) expect(whole).toContain(token);
+ expect([...seen.public].sort()).toEqual(Object.values(PUBLIC).sort());
+ const outline = await projectedOutline(engine, body, 0, 100_000);
+ expect(privateTokensIn(JSON.stringify(outline.entries), { ledger })).toEqual([]);
+ expect(outline.entries.some(e => e.heading?.includes(PUBLIC.prose))).toBe(true);
+ return body;
+}
+
+for (const kind of testBackends()) {
+ describe(`remote windows of a segmented page (${kind})`, () => {
+ let close: () => Promise<void>;
+
+ beforeAll(async () => {
+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ close = () => engine.disconnect();
+ }
+ }, 120_000);
+
+ afterAll(async () => { await close(); });
+
+ beforeEach(async () => {
+ for (const table of ['pages', 'fact_withdrawals', 'fact_purges', 'write_gate_holds']) await engine.executeRaw(`DELETE FROM ${table}`);
+ });
+
+ test('windows starting inside takes, facts and key blocks, at cuts and at random bytes show nothing private', async () => {
+ const r = mulberry32(101);
+ const pageId = await importSegmented(engine, 'notes/windows', pageContent(privacyText(r, 1_600_000), privacyText(r, 300_000)));
+ const body = await expectNoLeak(pageId, r, [PRIVATE.takes, PRIVATE.takesHeading, PRIVATE.privateFact, PRIVATE.key]);
+ expect(body.rows.length).toBeGreaterThan(3);
+ }, 300_000);
+
+ test('withdrawn, purged and held rows stay hidden in every window once the ledger records them', async () => {
+ const r = mulberry32(103);
+ const slug = 'notes/ledger-windows';
+ const pageId = await importSegmented(engine, slug, pageContent(privacyText(r, 1_400_000), privacyText(r, 200_000)));
+ const before = (await readRange(engine, { pageId, space: 'projected', start: 0, end: Infinity, audience: 'remote' })).bytes.toString('utf8');
+ expect(before).toContain(PRIVATE.withdrawn);
+ await seedLedger(engine, slug);
+ await expectNoLeak(pageId, r, [PRIVATE.withdrawn, PRIVATE.purged, PRIVATE.held], true);
+ }, 300_000);
+
+ test('a takes block left open to the end of the body hides the rest of the page in every later segment', async () => {
+ const r = mulberry32(107);
+ const tail = `<!--- gbrain:takes:begin -->\n${privacyText(r, 1_200_000, { keys: false }).replaceAll('zzpublic', `${PRIVATE.tail} `)}\n${PRIVATE.tail} last words\n`;
+ const pageId = await importSegmented(engine, 'notes/tail', pageContent(privacyText(r, 1_200_000) + tail));
+ const body = await expectNoLeak(pageId, r, [PRIVATE.tail]);
+ const tailAt = await storedOffsets(engine, pageId, PRIVATE.tail);
+ expect(body.rows.filter(row => row.byteStart > tailAt[0]!).length).toBeGreaterThan(1);
+ }, 300_000);
+
+ test('a facts fence cut by forced cuts shows no private row in any window', async () => {
+ const r = mulberry32(109);
+ const pageId = await importSegmented(engine, 'notes/crossing-windows', pageContent(privacyText(r, 500_000, { keys: false }) + crossingFacts() + privacyText(r, 600_000)));
+ await expectNoLeak(pageId, r, [PRIVATE.crossing]);
+ }, 300_000);
+ });
+}
diff --git a/test/large-pages/sealed-segmented-search.test.ts b/test/large-pages/sealed-segmented-search.test.ts
new file mode 100644
index 0000000000..d30884d8bc
--- /dev/null
+++ b/test/large-pages/sealed-segmented-search.test.ts
@@ -0,0 +1,95 @@
+/**
+ * Wave B PR 2: what a sealed segmented page (imported for real, sealed by
+ * sealSegmentedPage) gives search.
+ *
+ * 1. Protects: the seal stamps a chunker_version at or above
+ * SAFE_FENCE_CHUNKER_VERSION (its chunks are built under the same
+ * safe-fence contract), so chunk windows and remote (requireSafeChunks)
+ * keyword search serve the page; and the seal indexes the timeline lead
+ * after the page's withdrawal overlay, so a row withdrawn for every
+ * subject ('*') after the import is not findable once the projection is
+ * rebuilt (withdrawal.ts bumps the revision and deletes the chunk rows;
+ * the rebuild rechunks from the overlaid text and reseals).
+ * 2. Fails when: SEGMENTED_CHUNKER_VERSION drops below the safe-fence
+ * version (remote search and chunk windows withhold the page), or the
+ * seal indexes the raw lead (the withdrawn token is findable).
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { testBackends } from '../helpers/test-backends.ts';
+import { SAFE_FENCE_CHUNKER_VERSION } from '../../src/core/search/safe-chunks.ts';
+import { MARKDOWN_CHUNKER_VERSION } from '../../src/core/chunkers/recursive.ts';
+import { SEGMENTED_CHUNKER_VERSION } from '../../src/core/page-body/segment-chunks.ts';
+import { renderFactsTable } from '../../src/core/facts-fence.ts';
+import { buildSegmentedProjection } from '../../src/core/page-body/projection.ts';
+import { mulberry32 } from '../helpers/seeded-random.ts';
+import { factRow, importSegmented, pageContent, privacyText } from '../helpers/segmented-privacy-fixture.ts';
+
+let engine: BrainEngine;
+
+const pageRow = async (pageId: number) => (await engine.executeRaw<{ chunker_version: number; sealed: boolean }>(
+ 'SELECT chunker_version, text_projection_revision = knowledge_revision AS sealed FROM pages WHERE id=$1', [pageId]))[0]!;
+
+for (const kind of testBackends()) {
+ describe(`a sealed segmented page (${kind})`, () => {
+ let close: () => Promise<void>;
+
+ beforeAll(async () => {
+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ close = () => engine.disconnect();
+ }
+ }, 120_000);
+
+ afterAll(async () => { await close(); });
+
+ beforeEach(async () => {
+ for (const table of ['pages', 'fact_withdrawals']) await engine.executeRaw(`DELETE FROM ${table}`);
+ });
+
+ test('carries the safe-fence chunker version, so chunk windows and remote keyword search serve it', async () => {
+ const r = mulberry32(211);
+ const truth = `${privacyText(r, 600_000)}\nzzsealedneedle appears once in the truth\n${privacyText(r, 900_000)}`;
+ const pageId = await importSegmented(engine, 'notes/sealed', pageContent(truth));
+ const page = await pageRow(pageId);
+ const [win] = await engine.getChunkWindows([{ page_id: pageId, from_index: 0, to_index: 10, priority: 0 }], { chunkSources: ['compiled_truth'], maxRows: 50 });
+ expect(win!.chunks.length).toBeGreaterThan(0);
+ const remote = await engine.searchKeyword('zzsealedneedle', { requireSafeChunks: true });
+ expect(remote.map(h => h.slug)).toContain('notes/sealed');
+ expect(remote.find(h => h.slug === 'notes/sealed')!.chunk_text).toContain('zzsealedneedle');
+ expect(page).toEqual({ chunker_version: SEGMENTED_CHUNKER_VERSION, sealed: true });
+ expect(SEGMENTED_CHUNKER_VERSION).toBe(MARKDOWN_CHUNKER_VERSION);
+ expect(SEGMENTED_CHUNKER_VERSION).toBeGreaterThanOrEqual(SAFE_FENCE_CHUNKER_VERSION);
+ }, 240_000);
+
+ test("a reseal indexes the timeline lead after the withdrawal overlay: a row withdrawn for '*' after the import is not findable", async () => {
+ const r = mulberry32(223);
+ const withdrawn = factRow('zzleadwithdrawn former role');
+ const kept = factRow('zzleadkept current role');
+ const timeline = `${renderFactsTable([withdrawn, kept])}\n${privacyText(r, 200_000)}`;
+ const pageId = await importSegmented(engine, 'notes/lead', pageContent(privacyText(r, 1_400_000), timeline));
+ const vectorHas = async (word: string) => (await engine.executeRaw<{ hit: boolean }>(
+ "SELECT search_vector @@ plainto_tsquery('english', $2) AS hit FROM pages WHERE id=$1", [pageId, word]))[0]!.hit;
+ expect(await vectorHas('zzleadwithdrawn')).toBe(true);
+ await engine.executeRaw(`INSERT INTO fact_withdrawals (source_id, visibility, subject, fact_hash)
+ VALUES ('default', 'world', '*', gbrain_fact_fingerprint($1))`, [withdrawn.claim]);
+ await engine.executeRaw('UPDATE pages SET knowledge_revision=gen_random_uuid(), text_projection_revision=NULL WHERE id=$1', [pageId]);
+ await engine.executeRaw('DELETE FROM content_chunks WHERE page_id=$1', [pageId]);
+ expect((await buildSegmentedProjection(engine, { sourceId: 'default', slug: 'notes/lead' })).sealed).toBe(true);
+ const [lead] = await engine.executeRaw<{ timeline_lead: string }>('SELECT timeline_lead FROM pages WHERE id=$1', [pageId]);
+ expect(lead!.timeline_lead).toContain('zzleadwithdrawn');
+ expect((await pageRow(pageId)).sealed).toBe(true);
+ expect(await vectorHas('zzleadkept')).toBe(true);
+ expect(await vectorHas('zzleadwithdrawn')).toBe(false);
+ for (const requireSafeChunks of [true, false]) {
+ expect((await engine.searchKeyword('zzleadkept', { requireSafeChunks })).map(h => h.slug)).toContain('notes/lead');
+ expect((await engine.searchKeyword('zzleadwithdrawn', { requireSafeChunks })).map(h => h.slug)).not.toContain('notes/lead');
+ }
+ }, 240_000);
+ });
+}
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 163998e07a..a80539f95c 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -66,6 +66,9 @@ test/lane-apply-pipelining.test.ts
test/large-pages/chunk-visibility.test.ts
test/large-pages/managed-streamed-import.test.ts
test/large-pages/managed-sync-segmented-rename.test.ts
+test/large-pages/projection-parity.test.ts
+test/large-pages/remote-window-privacy.test.ts
+test/large-pages/sealed-segmented-search.test.ts
test/large-pages/segment-vector-reuse.test.ts
test/large-pages/segmented-body-unreachable.test.ts
test/large-pages/segmented-derived-work.test.ts