Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Wave B PR 2 lane F: pin segmented reads to the authorized snapshot; purge_fact and GC respect in-flight stagings
garrytan0f53286933af
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex a91b0dd280..9b7746a1fe 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -2154,6 +2154,16 @@ Reasons: `host_mismatch`, `transfer_in_progress`, `clone_in_progress`, `binding_More: [docs/guides/troubleshooting.md#owner-unavailable](../../docs/guides/troubleshooting.md#owner-unavailable)+### page_body_rows_unreadable++<a id="page_body_rows_unreadable"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| This large page's segment rows readable on this connection do not cover its body, so the read returned nothing rather than a short or empty body. | A segmented page keeps its body in manifest rows that must tile the stored body from its first byte to body_bytes; a role that sees the page row but not its manifest rows (a row-level security policy or grant that covers pages only), or rows missing from the database, would otherwise read as an empty or truncated page with nothing to say so. | Give the role that reads the brain the same access to page_body_manifest and page_segment_texts it has to pages (the brain host's operator), then read again; run gbrain doctor --json to check the segment tables. | host_admin | `gbrain doctor --json` | 1 | no |++More: [docs/guides/windowed-reads.md#page_body_rows_unreadable](../../docs/guides/windowed-reads.md#page_body_rows_unreadable)+### page_body_segmented<a id="page_body_segmented"></a>diff --git a/docs/guides/windowed-reads.md b/docs/guides/windowed-reads.mdindex d63e409f64..53722d01ec 100644--- a/docs/guides/windowed-reads.md+++ b/docs/guides/windowed-reads.md@@ -144,6 +144,17 @@ it refuses with this code (wire `error: invalid_params`, not retryable) and afix that saves the claim without an entity (`infer_entity: false`), whetherthe entity was named or inferred from the fact.+## page_body_rows_unreadable++A read of a segmented page found manifest rows that do not cover the page's+stored body: they must run from byte 0 to the page's `body_bytes` without a+gap. The usual cause is a database role that can read the page row but not+its segment rows (a row-level security policy or grant on `pages` only); a+damaged database is the other. gbrain returns nothing rather than an empty or+truncated page. The brain host's operator gives the reading role the same+access to `page_body_manifest` and `page_segment_texts` it has to `pages`;+`gbrain doctor --json` checks the segment tables.+## page_projection_staleA read of a segmented page reached a segment whose stored projection metadatadiff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 6f6bbcac8e..4cce825884 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -40,7 +40,7 @@ src/core/config.ts 1981 ratchet +2 W5: search.page_rank_cut / page_rank_cut_factsrc/core/persistence/sync-run.ts 1704 ratchet new row: crossed the 1500 unlisted cap in #6643 (knock-on re-freeze, checkpoint revival, root cause and the truthful --retry-failed wait all drive the private cursor/gate machinery: holdUnderGate, freezeEntry, saveCursor); classification lives in sync-knock-on.ts, the checkpoint clause in checkpoint-validation.ts; peel the settle path (settleFailedRequest and its recoveries) into a sibling module next; +3 #6722: committed pages' size_state tallied into the cursor and the sync receipt size_states (logic in page-embedding-budget.ts addSizeState); merge v0.60.240.0: large pages and master growth compose at 1687; +2 #6694: the slug-mode checkpoint revival import and its doc line (predicate lives in persistence/sync-slug-mode.ts); +14 Wave B PR 2: freezeEntry freezes a Markdown file over the read bound by reference (body_ref) and holdFailedFenceRequest holds a streamed refusal; both set freezeEntry/holdFailedFenceRequest locals (blob, oversize, rawHash) so they stay here, the hashing and preparation live in persistence/sync-streamed.ts and the hold in sync-screen.ts streamedRefusalHoldsrc/core/bootstrap/harness.ts 2615 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts); +5 D8 Codex slice: the Codex SessionEnd capture hook obeys the recorded consent (wireCodexCapture: hooks on, capture accepted, never registrar mode) and is disclosed in the consent blocksrc/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option-src/core/ops/pages.ts 711 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +21 large pages (Wave A): get_page body-mode dispatch, fetch window branch, put_page large-page admission and allow_shrink param, description text (logic in ops/get-page-body.ts and persistence/large-page-guard.ts); +1 D8 funnel: committed put_page records a save when the opt-in funnel is on; +1 #6609: restore_page detach param (logic in persistence/detached-pages.ts); +1 Wave B gem A: post-batch auto-link reads a segmented page materialized (helpers in persistence/segmented-apply.ts); merge v0.60.249.0: composes at 707; +4 Wave B PR 2: get_page refuses a segmented page whole and fetch windows one (logic in ops/get-page-body.ts and page-window/segmented.ts)+src/core/ops/pages.ts 713 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +21 large pages (Wave A): get_page body-mode dispatch, fetch window branch, put_page large-page admission and allow_shrink param, description text (logic in ops/get-page-body.ts and persistence/large-page-guard.ts); +1 D8 funnel: committed put_page records a save when the opt-in funnel is on; +1 #6609: restore_page detach param (logic in persistence/detached-pages.ts); +1 Wave B gem A: post-batch auto-link reads a segmented page materialized (helpers in persistence/segmented-apply.ts); merge v0.60.249.0: composes at 707; +4 Wave B PR 2: get_page refuses a segmented page whole and fetch windows one (logic in ops/get-page-body.ts and page-window/segmented.ts); +2 Wave B PR 2 lane F: get_page and fetch pin segmented reads to the authorized snapshot (pin logic in ops/get-page-body.ts authorizedReadPin)src/core/search/mode.ts 1669 ratchet +53 W3 confidence-gated reranking: reranker_gate / reranker_gate_min_gap bundle fields, overrides, config parse and KNOB_CONFIG_KEY rows, knobsHash v=31 rrg=/rrgg=/ecf= parts (parse contracts in crag.ts); +10 System One v1: decide.* snapshot subset in loadSearchModeConfig, append-only dec= knobsHash part; +5 #3617 follow-up: v27 same-knobs behavioral-change note (relaxed-row fusion demotion rides the bump); new row: crossed the 1500 unlisted cap in the 2026-08 eval fix wave — KNOBS_HASH v=27 adaptive-return fold (ar/arem/arom/armk/ari parts + KnobsHashContext.adaptiveReturn field + contamination rationale comments) | merged v0.48.1.0 (+#4787) true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: four knobs (expansion_variant_budget, relational_rerank_pin, keyword_arm_confidence_floor, metadata_boost_gate) + v29 hash parts + doc receipts (+218); #4781 loadSearchModeConfig reads the config table once via loadConfigSnapshot (+6); +4 #4359: update loadSearchModeConfig docstring — the cached path now reads config once (threaded snapshot), not twice; retired provider integration removed; +12 fw3-search: search.source_boosts + search.alias_token_hop read in the mode snapshot; +10 #5691: KnobsHashContext.queryPrefix and its append-only qp= part; P7 relational_planner / relational_orient_onehop knobs (interface docs, bundles, overrides, config parse, hash parts); +18 P7 relational_chain_slots knob (interface doc, bundles, override, config parse, rcs= hash part); +22 GBRA-60 S1 diverse_pool_depth knob (interface doc, bundles, overrides, pick, config parse, append-only dpd= hash part)src/commands/eval-longmemeval.ts 1544 ratchet new row: crossed the 1500 unlisted cap in fw3-search (#5092 benchmark-brain recycling: configureBrain split + recycler wiring + test seams; the recycler itself lives in src/eval/longmemeval/harness.ts); +1 P6: tokenmax synopsis-tier wiring (logic in eval/longmemeval/synopsis-tier.ts); +13 GBRA-81 lane A: --via-operation query|search (flags, per-call expansion pin, the run's expectExpansion, the op branch in runOneQuestion, row field, via_operation_summary and its FAIL line; logic in eval/longmemeval/via-operation.ts); +12 --call-plan FILE / --call-plan-gate CMD: two LME_FLAGS entries (CLI help lines), two ParsedArgs fields, the parseArgs pairing check and the header invariant (planner lives in eval/longmemeval/call-plan.ts; runEvalLongMemEval is one line shorter)src/commands/doctor/checks/extraction-sync.ts 1523 ratchet +1 undeclared_db_only_pages computes the source Git scope once per source (logic in core/markdown.ts sourceGitScope); new row: crossed the 1500 unlisted cap at the fix wave 9 merge: +7 lane W #5028 (extract_atoms freshness judged by the phase itself) and +3 lane F #5863 (extract_health dates a high halt rate by its last halt), each under the cap alone; +7 #5019: content_hash_duplicates fix pins the pairs' source (GBRAIN_SOURCE) and names a delete that runs; +1 fix wave 10 lane L1 #5556: links_extraction_lag denominator excludes quarantined pages (quarantineFilterFragment import); +11 fix wave 15 P2.8 (#5495): extract_health reads the 7-day halt reasons per kind (halt_reasons, top_halt_reason in details and the top reason in the warn line); the read, the unknown bucket and the ranking live in core/extract/rollup-writer.tsdiff --git a/src/cli/page-render.ts b/src/cli/page-render.tsindex 34aa4b74db..917594ca05 100644--- a/src/cli/page-render.ts+++ b/src/cli/page-render.ts@@ -168,7 +168,8 @@ export async function streamSegmentedGet(engine: BrainEngine, params: Record<strconst { page, tags } = snapshot;const json = params.json === true;if (json && Number(page.body_bytes) > PAGE_MAX_BYTES) throw jsonTooLargeError(page.slug, page.source_id, Number(page.body_bytes));- const body = await openSegmentedBody(engine, { pageId: page.id, ledger: { withdrawals: snapshot.withdrawals, ...(snapshot.globalPurges ? { globalPurges: snapshot.globalPurges } : {}) } });+ const body = await openSegmentedBody(engine, { pageId: page.id, ledger: { withdrawals: snapshot.withdrawals, ...(snapshot.globalPurges ? { globalPurges: snapshot.globalPurges } : {}) },+ pin: { revision: snapshot.revision, generation: snapshot.bodyGeneration } });const doc = await segmentedMarkdownDocument(engine, body, markdownHead(page, tags), 'trusted');const parts: string[] = [];for await (const bytes of doc.stream()) {diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 77b39ff41b..044e932ba9 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -667,6 +667,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: 'TBD', text: 'The pre-push secret scan (`gbrain sources push` and the automatic pushes) now scans a staged file over 25 MiB in bounded 8 Mi-character windows streamed from git, instead of refusing the push as `blocked_unscannable`: a clean large file pushes, and one holding a secret is refused as `blocked_secrets` naming its file and line. A staged file over 512 MiB still refuses as `blocked_unscannable`.' },{ since: 'TBD', text: 'On Postgres, title search, the source-scoped vector scan, the chunk windows search reads around its hits and `get_page` now read the new `page_body_manifest` table for every page, inline ones included, whether or not `pages.segmented_storage` is on. A database role that neither owns the tables nor bypasses row level security needs `SELECT` on it, or those reads fail with `permission_denied` (42501). Row level security is on for the new segment tables (`page_segment_texts`, `page_body_manifest`, `page_body_stagings`, `page_body_staging_parts`, `page_view_digests`) and is re-enabled on every schema replay, as for `pages`, so a role without a policy reads none of their rows. Grant the table together with the source-scoped policies in docs/ENGINES.md ("Segmented page tables"), never with an open policy, or the role reads every source\'s segment text. A runtime role that owns the tables or bypasses row level security, the default setup, needs nothing.' },{ since: 'TBD', text: 'MCP `get_page` of a page stored in segments no longer reports `size.body_bytes` or `size.body_lines` (the stored body) to a remote caller, and its `page_body_segmented` refusal names the size of the body that caller may read, as for an inline page; the difference told how much text privacy fences and withdrawals hide. A local `gbrain get` still reports both.' },+ { since: 'TBD', text: 'Reads of a page stored in segments that follow an authorization (MCP `get_page` windows, outlines, sizes and its whole-body refusal, `fetch`, evidence windows and the `entity` card excerpt) now read the revision they authorized: a page edited, made private or dropped below the caller\'s `min_trust` mid-read refuses with `revision_changed` (or `page_not_found`) instead of returning the newer body, and evidence falls back to the hit chunk. A segmented page whose segment rows the reader cannot see, or that has a gap, refuses with the new `page_body_rows_unreadable` instead of reading as empty. `purge_fact` now aborts a write in flight that staged a text holding the purged claim (its publish refuses `body_staging_expired`), segment maintenance keeps every text a live write staged, a page purge of an inline page no longer reports other pages\' segments as incomplete, and MCP `get_versions` reports a segmented version\'s readable size as `total_bytes` instead of its stored `body_bytes`.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/engine-sql/page-body.ts b/src/core/engine-sql/page-body.tsindex f7d09d087d..b8bff59765 100644--- a/src/core/engine-sql/page-body.ts+++ b/src/core/engine-sql/page-body.ts@@ -34,8 +34,9 @@ import { jsonbParam, type SqlExecutor } from './executor.ts';import type { LegacyUnscopedRead } from './brands.ts';import { joinFragments, sqlFragment, trustedSql, type SqlFragment } from './fragment.ts';import { compileRowNormalizer } from './normalize.ts';+import { stagingNeedsTextSql } from '../page-body/schema.ts';-const LIVE_STAGING_STATES = ['open', 'sealed', 'prepared'];+export const LIVE_STAGING_STATES = ['open', 'sealed', 'prepared'];const TERMINAL_STAGING_STATES = ['committed', 'aborted', 'expired'];const NON_TERMINAL_REQUEST_STATES = ['queued', 'running', 'recovering'];@@ -303,11 +304,7 @@ export async function flipBodyGeneration(exec: SqlExecutor, input: BodyFlipInputmcp: { tool: 'get_page', arguments: { slug: page.slug, source_id: page.source_id, body: 'none' } } }) });}const { rows: stagings } = await tx.run<{ state: string }>(sqlFragment`SELECT state FROM page_body_stagings WHERE id = ${input.stagingId}::uuid FOR UPDATE`);- if (!LIVE_STAGING_STATES.includes(stagings[0]?.state ?? '')) {- throw opError('body_staging_expired', `The staged body of this write to ${page.slug} is ${stagings[0]?.state ?? 'gone'}, so nothing was published.`,- 'The write waited past its staging deadline and its staged segments were collected. Send the write again.',- { detail: JSON.stringify({ staging_id: input.stagingId, state: stagings[0]?.state ?? null }) });- }+ if (!LIVE_STAGING_STATES.includes(stagings[0]?.state ?? '')) throw bodyStagingGoneError(page.slug, input.stagingId, stagings[0]?.state ?? null);const newLive = sqlFragment`(SELECT s.occurrence_id FROM page_body_manifest s WHERE s.page_id = ${input.pageId}AND (s.staging_id = ${input.stagingId}::uuidOR (s.staging_id IS NULL AND s.gen_to IS NULL AND NOT (s.occurrence_id = ANY(${[...input.closeOccurrences]}::bigint[])))))`;@@ -345,6 +342,15 @@ export async function flipBodyGeneration(exec: SqlExecutor, input: BodyFlipInput});}+/** A write's staging is no longer live, so the write publishes nothing: expired and collected, or aborted (a fact purge removed text it staged). */+export function bodyStagingGoneError(slug: string, stagingId: string, state: string | null) {+ return opError('body_staging_expired', `The staged body of this write to ${slug} is ${state ?? 'gone'}, so nothing was published.`,+ state === 'aborted'+ ? 'The staging was aborted (a fact purge removed text it staged, or its preparation failed). Send the write again; purged content is refused.'+ : 'The write waited past its staging deadline and its staged segments were collected. Send the write again.',+ { detail: JSON.stringify({ staging_id: stagingId, state }) });+}+export async function openBodyStaging(exec: SqlExecutor, input: BodyStagingInput): Promise<void> {await exec.run(sqlFragment`INSERT INTO page_body_stagings (id, kind, principal_kind, principal_id, client_request_id, source_id,source_incarnation, slug, page_id, mode, base_revision, base_generation, declared_bytes, declared_sha256, reserved_bytes,@@ -370,8 +376,10 @@ export async function setBodyStagingState(exec: SqlExecutor, id: string, state:* stagings (`liveStagingIds`). Deletes staged chunk rows (above the page's* generation) no live staging owns, manifest rows outside every root, and* unreferenced texts older than the grace window and older than every live- * staging of their source (a text a concurrent writer is referencing is- * row-locked by its FK check or its refresh and skipped). A page-scoped sweep+ * staging of their source, that no live staging recorded+ * (page_body_staging_texts: a create that deduped onto an older text holds it+ * until it publishes); a text a concurrent writer is referencing is row-locked+ * by its FK check or its refresh and skipped. A page-scoped sweep* (`pageId`) considers only the texts its own manifest deletes released, so* its cost is the page's, not the source's; the source-wide sweep collects the* rest. Rows of retired occurrences are deleted by the flip or, deferred, by@@ -439,6 +447,7 @@ export async function sweepSegments(exec: SqlExecutor, opts: SegmentSweepOptionsAND NOT EXISTS (SELECT 1 FROM page_body_manifest m WHERE m.source_id = t.source_id AND m.sha256 = t.sha256)AND NOT EXISTS (SELECT 1 FROM page_body_stagings s WHERE s.source_id = t.source_id AND s.created_at <= t.created_atAND s.id::text IN ${liveStagingIds})+ AND NOT ${trustedSql(stagingNeedsTextSql('t'))}FOR UPDATE SKIP LOCKED)`)).affectedRows;return { retiredChunksDeleted: retiredChunksDeleted + orphanedChunksDeleted, manifestRowsDeleted: stagedRowsDeleted + closedRowsDeleted, textsDeleted, stagingsExpired };}diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex bcffe2d4ab..83de6fd13f 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_body_rows_unreadable: { class: 'server', summary: "This large page's segment rows readable on this connection do not cover its body, so the read returned nothing rather than a short or empty body.", why: "A segmented page keeps its body in manifest rows that must tile the stored body from its first byte to body_bytes; a role that sees the page row but not its manifest rows (a row-level security policy or grant that covers pages only), or rows missing from the database, would otherwise read as an empty or truncated page with nothing to say so.", docs: 'docs/guides/windowed-reads.md#page_body_rows_unreadable', suggestion: "Give the role that reads the brain the same access to page_body_manifest and page_segment_texts it has to pages (the brain host's operator), then read again; run gbrain doctor --json to check the segment tables." },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: "Retrying refuses the same way. Read the page in pieces: get_page body: 'auto' returns its outline and first window, and body: 'window' reads any lines or bytes.", fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--body', 'auto', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}', body: 'auto' } }, consent: [], actor: 'agent', why: "Returns the page's outline and its first window, with next_cursor to read on.", 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 } },diff --git a/src/core/facts/purge-verify.ts b/src/core/facts/purge-verify.tsindex 5e991f9d85..3693c0d5da 100644--- a/src/core/facts/purge-verify.ts+++ b/src/core/facts/purge-verify.ts@@ -389,6 +389,9 @@ export async function verifyPagePurge(engine: BrainEngine, input: { sourceId: stawait keyed('files', 'SELECT 1 FROM files WHERE page_slug=$2 AND (source_id=$1 OR source_id IS NULL)', [src, slug]);await keyed('write_gate_holds', 'SELECT 1 FROM write_gate_holds WHERE source_id=$1 AND slug=$2', [src, slug]);await keyed('query_cache', 'SELECT 1 FROM query_cache WHERE $1::text IS NOT NULL', [src]);+ // The page's own segment texts only: a text of another page holding the same words is that page's body, never a+ // residue of this purge (an inline page referenced none, so the inventory sweep below must not probe the table).+ if (context && !context.segmentShas.length) stores.push({ store: 'page_segment_texts', status: 'not_present', removed: removed.page_segment_texts ?? 0 });if (context?.segmentShas.length) await keyed('page_segment_texts', `SELECT 1 FROM page_segment_texts t WHERE t.source_id=$1AND t.sha256=ANY(SELECT decode(h,'hex') FROM unnest($2::text[]) AS h)AND NOT EXISTS (SELECT 1 FROM page_body_manifest m WHERE m.source_id=t.source_id AND m.sha256=t.sha256) AND NOT ${stagingNeedsTextSql('t')}`, [src, context.segmentShas]);diff --git a/src/core/facts/purge.ts b/src/core/facts/purge.tsindex 74edba930d..d88196fee0 100644--- a/src/core/facts/purge.ts+++ b/src/core/facts/purge.ts@@ -44,6 +44,8 @@ import { cancelRequestsHoldingStagings, findRequestsCarrying, findRequestsHoldinimport { withPageTierKept } from '../trust/fence-append.ts';import { rebuildPendingPageProjections } from '../page-state/projections.ts';import { buildSegmentedProjection } from '../page-body/projection.ts';+import { liveStagingSql } from '../page-body/schema.ts';+import { escapeFenceCell } from '../fence-shared.ts';import { carriesClaimSql, claimNeedles, purgeCompletion, verifyFactPurge, type PurgeReceipt, type StoreCount } from './purge-verify.ts';export const PURGE_OPERATION = 'purge_fact';@@ -153,11 +155,16 @@ export async function planFactPurge(engine: BrainEngine, target: PurgeTarget, alconst [versions] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM page_versions v JOIN pages p ON p.id=v.page_idWHERE p.source_id=$1 AND (${carriesClaimSql('v', 2)}OR (v.body_storage='segmented' AND ${SEGMENTED_VERSION_CARRIES}))`, [target.source_id, ...claimNeedles(target.fact)]);+ // A live staging that recorded a text holding the claim, plain or as a fence cell (page_body_staging_texts: a create+ // holds its manifest rows in memory until it publishes), is aborted with the rest: the purge deletes that text and the+ // create refuses cleanly (body_staging_expired) instead of failing on the manifest's text foreign key.const stagings = [...new Set([...(await engine.executeRaw<{ id: string }>(`SELECT s.id::text AS id FROM page_body_stagings s- WHERE s.source_id=$1 AND s.state IN ('open','sealed','prepared') AND (EXISTS (SELECT 1 FROM page_body_manifest m+ WHERE s.source_id=$1 AND ((s.state IN ('open','sealed','prepared') AND (EXISTS (SELECT 1 FROM page_body_manifest mJOIN page_segment_texts t ON t.source_id=m.source_id AND t.sha256=m.sha256 WHERE m.staging_id=s.id AND strpos(lower(convert_from(t.body,'UTF8')),$2)>0)- OR EXISTS (SELECT 1 FROM page_body_staging_parts pt WHERE pt.staging_id=s.id AND position(convert_to($3::text,'UTF8') in pt.body)>0))- ORDER BY s.id`, [target.source_id, target.fact.toLowerCase(), target.fact])).map(row => row.id),+ OR EXISTS (SELECT 1 FROM page_body_staging_parts pt WHERE pt.staging_id=s.id AND position(convert_to($3::text,'UTF8') in pt.body)>0)))+ OR (${liveStagingSql('s')} AND EXISTS (SELECT 1 FROM page_body_staging_texts r JOIN page_segment_texts t ON t.source_id=r.source_id AND t.sha256=r.sha256+ WHERE r.staging_id=s.id AND (strpos(lower(convert_from(t.body,'UTF8')),$2)>0 OR strpos(lower(convert_from(t.body,'UTF8')),$4)>0))))+ ORDER BY s.id`, [target.source_id, target.fact.toLowerCase(), target.fact, escapeFenceCell(target.fact).toLowerCase()])).map(row => row.id),...await stagingsWithClaimAcrossParts(engine, target.source_id, target.fact)])].sort();const held = await findRequestsHoldingStagings(engine, target.source_id, stagings);// #6511 [R5]: a statement timeout of this unindexable substring search is deterministic on a large journal, not contention: the typed code, not a retry.@@ -297,7 +304,8 @@ async function redactPageVersions(tx: BrainEngine, sourceId: string, claim: stri* Wave B (spec 11), after the body and version rewrites: stagings holding the claim are aborted (their upload parts* deleted, requests that reference them cancelled with purged_content), closed manifest rows outside every GC root* go, and every segment text the rewrites replaced, or that still holds the claim, is deleted once nothing- * references it, in this transaction (purge never waits for GC).+ * references it, in this transaction (purge never waits for GC). A live staging that recorded such a text was aborted+ * by the plan (planFactPurge), so no write in flight still needs it.*/async function purgeSegmentStorage(tx: BrainEngine, sourceId: string, claim: string, plan: PurgePlan, pageIds: number[], replaced: Uint8Array[], ownRequest: string):Promise<{ texts: number; stagings: number; parts: number; cancelled: number }> {@@ -306,7 +314,7 @@ async function purgeSegmentStorage(tx: BrainEngine, sourceId: string, claim: strconst staged: number[] = [];if (plan.stagings.length) {staged.push(...(await tx.executeRaw<{ page_id: number | null }>(`UPDATE page_body_stagings SET state='aborted',updated_at=now()- WHERE id=ANY($1::uuid[]) RETURNING page_id`, [plan.stagings])).flatMap(row => row.page_id === null ? [] : [Number(row.page_id)]));+ WHERE id=ANY($1::uuid[]) AND state<>'committed' RETURNING page_id`, [plan.stagings])).flatMap(row => row.page_id === null ? [] : [Number(row.page_id)]));parts = (await tx.executeRaw('DELETE FROM page_body_staging_parts WHERE staging_id=ANY($1::uuid[]) RETURNING 1', [plan.stagings])).length;}for (const pageId of new Set([...pageIds, ...staged])) await tx.sweepSegments({ pageId });diff --git a/src/core/ops/admin.ts b/src/core/ops/admin.tsindex 12d14357a3..0da6a41aa4 100644--- a/src/core/ops/admin.ts+++ b/src/core/ops/admin.ts@@ -20,6 +20,8 @@ import { resolveActiveEmbeddingColumnFromEngine } from '../search/embedding-coluimport { memoizedHealth } from '../health-memo.ts';import { LARGE_PAGES_CAPABILITY } from './get-page-body.ts';import { isSegmentedPage, pageBodyBytes } from '../page-body/page-shape.ts';+import { openSegmentedBody } from '../page-body/read-range.ts';+import { segmentedReadDocument } from '../page-window/segmented.ts';// --- Admin ---@@ -220,26 +222,44 @@ const get_versions: Operation = {// An adapter that ignores includeBody never leaks an unsanitized body through the metadata default.const metadata = page(await ctx.engine.getVersions(p.slug as string, { ...opts, includeBody: false })).map(v => { const { compiled_truth: _b, timeline: _t, ...rest } = v as typeof v & { compiled_truth?: unknown; timeline?: unknown }; return rest; });- return canReadWriteAttribution(ctx) ? attributeVersions(ctx.engine, metadata) : metadata;+ const sized = [];+ for (const v of metadata) sized.push(await remoteVersionSize(ctx, v));+ return canReadWriteAttribution(ctx) ? attributeVersions(ctx.engine, sized) : sized;}const plain = page(await ctx.engine.getVersions(p.slug as string, opts));const versions = canReadWriteAttribution(ctx) ? await attributeVersions(ctx.engine, plain) : plain;// Wave B: a segmented version's body is never returned whole; body_ref names its size and the windowed read.- return versions.map(v => {+ const out = [];+ for (const v of versions) {if (isSegmentedPage(v)) {- const { compiled_truth: _b, timeline: _t, ...rest } = v;- return { ...rest, body_ref: { version_id: v.id, total_bytes: pageBodyBytes(v),- read: { tool: 'get_page', arguments: { slug: p.slug, version_id: v.id, body: 'window' } } } };+ const sized = await remoteVersionSize(ctx, v);+ const { compiled_truth: _b, timeline: _t, ...rest } = sized;+ out.push({ ...rest, body_ref: { version_id: v.id, total_bytes: 'total_bytes' in sized ? sized.total_bytes : pageBodyBytes(v),+ read: { tool: 'get_page', arguments: { slug: p.slug, version_id: v.id, body: 'window' } } } });+ continue;}- if (ctx.remote === false) return v;- return { ...v, compiled_truth: sanitizeRemoteBody(v.compiled_truth),- ...(typeof v.timeline === 'string' ? { timeline: sanitizeRemoteBody(v.timeline) } : {}) };- });+ if (ctx.remote === false) { out.push(v); continue; }+ out.push({ ...v, compiled_truth: sanitizeRemoteBody(v.compiled_truth),+ ...(typeof v.timeline === 'string' ? { timeline: sanitizeRemoteBody(v.timeline) } : {}) });+ }+ return out;},scope: 'read',cliHints: { name: 'history', positional: ['slug'] },};+/**+ * A segmented version as a remote caller sees it: the size of its read projection (`total_bytes`, what get_page reports+ * for a segmented page), never the stored body_bytes, whose difference would say how much text the projection hides.+ */+async function remoteVersionSize<V extends { page_id: number; body_storage?: string; body_generation?: number; body_bytes?: number }>(ctx: OperationContext, v: V):+ Promise<V | Omit<V, 'body_bytes'> & { total_bytes: number }> {+ if (ctx.remote === false || v.body_storage !== 'segmented') return v;+ const { body_bytes: _stored, ...rest } = v;+ const body = await openSegmentedBody(ctx.engine, { pageId: v.page_id, generation: v.body_generation });+ return { ...rest, total_bytes: (await segmentedReadDocument(ctx.engine, body)).total };+}+const revert_version: Operation = {name: 'revert_version',idempotent: true,diff --git a/src/core/ops/get-page-body.ts b/src/core/ops/get-page-body.tsindex 1eadfb7770..0f0fd87aa9 100644--- a/src/core/ops/get-page-body.ts+++ b/src/core/ops/get-page-body.ts@@ -45,9 +45,9 @@ import {import {markdownDigest, markdownHead, readViewLines, segmentedMarkdownDocument, segmentedOutline, segmentedReadDocument, tailDigest, type SegmentedDocument,} from '../page-window/segmented.ts';-import { openSegmentedBody } from '../page-body/read-range.ts';+import { confirmBodyPin, openSegmentedBody, type BodyPin } from '../page-body/read-range.ts';import { renderTrustedText, type TrustFields } from '../eligibility/labels.ts';-import type { QuarantinedView } from './get-page-projection.ts';+import { pageTrustForRead, type QuarantinedView } from './get-page-projection.ts';import { chunkGenerationProbe } from '../search/safe-chunks.ts';export const BODY_MODES = ['auto', 'full', 'none', 'outline', 'window'] as const;@@ -220,9 +220,13 @@ export async function assertFullReadFits(ctx: OperationContext, page: Pick<Page,* read projection (as an inline page reports its privacy-stripped body), never the stored body_bytes, whose difference* would say how much text the projection hides.*/-export async function segmentedFullReadError(ctx: OperationContext, page: Page, req: BodyRequest): Promise<OperationError> {- const total = ctx.remote === false ? pageBodyBytes(page)- : (await segmentedReadDocument(ctx.engine, await openSegmentedBody(ctx.engine, { pageId: page.id }))).total;+export async function segmentedFullReadError(ctx: OperationContext, page: Page, req: BodyRequest, pin: BodyPin): Promise<OperationError> {+ let total = pageBodyBytes(page);+ if (ctx.remote !== false) {+ const body = await openSegmentedBody(ctx.engine, { pageId: page.id, pin });+ total = (await segmentedReadDocument(ctx.engine, body)).total;+ await confirmBodyPin(ctx.engine, body);+ }const windows = "Read it in pieces: get_page body: 'auto' returns the outline and the first window, then body: 'window' with lines, bytes, around_chunk_id or next_cursor reads on.";const fix = segmentedReadFix(page.slug, page.source_id);if (ctx.remote === false) {@@ -267,6 +271,13 @@ export interface PartialReadInput {quarantined: QuarantinedView | null;trust?: TrustFields;extras: Record<string, unknown>;+ /** A segmented page's reads are pinned to `revision`, this body generation (from the same snapshot) and `admit` (openSegmentedBody). */+ pin?: Omit<BodyPin, 'revision'>;+}++/** The pin of a segmented read after get_page's or fetch's authorization: the snapshot's generation, with the trust floor re-checked when the read confirms. */+export function authorizedReadPin(ctx: OperationContext, page: Page, generation: number | undefined, minTrust: unknown, refuse: () => Error): Omit<BodyPin, 'revision'> {+ return { generation, admit: async () => { if (!await pageTrustForRead(ctx, page, minTrust)) throw refuse(); } };}function envelopeText(text: string, quarantined: QuarantinedView | null, trust?: TrustFields): string {@@ -346,7 +357,7 @@ function inlineDocument(doc: PageDocument): WindowDocument {*/async function segmentedWindows(ctx: OperationContext, input: PartialReadInput, req: BodyRequest, mode: BodyMode): Promise<{ doc: WindowDocument; size: Record<string, unknown> }> {const { page, revision, tags } = input;- const body = await openSegmentedBody(ctx.engine, { pageId: page.id });+ const body = await openSegmentedBody(ctx.engine, { pageId: page.id, pin: { ...input.pin, revision } });const audience = ctx.remote === false ? 'trusted' : 'remote';const stored = audience === 'trusted' ? { body_bytes: body.bodyBytes, body_lines: body.bodyLines } : {};let seg: SegmentedDocument;@@ -419,8 +430,13 @@ export async function readPartialBody(ctx: OperationContext, input: PartialReadIdoc = inlineDocument(whole);}const out: Record<string, unknown> = { ...base, body: mode, view: req.view, ...(doc.segmented ? { body_storage: 'segmented' } : {}), size };+ // A segmented read is returned only while the page is still at the revision its caller was authorized for.+ const confirmed = async (result: Record<string, unknown>) => {+ if (doc.segments) await confirmBodyPin(ctx.engine, doc.segments.body);+ return result;+ };- if (mode === 'none') return noneResult(ctx, page, out, doc.total > 0);+ if (mode === 'none') return confirmed(await noneResult(ctx, page, out, doc.total > 0));if (mode === 'outline') {const limit = Math.min(MAX_OUTLINE_LIMIT, DEFAULT_OUTLINE_LIMIT);@@ -431,9 +447,9 @@ export async function readPartialBody(ctx: OperationContext, input: PartialReadIout.truncated = true;if (first.byte_end < doc.total) setNext(out, page, encodeCursor({ page_id: page.id, revision, view: 'read', offset: first.byte_end, max_bytes: req.maxBytes ?? DEFAULT_WINDOW_BYTES }), false);out.auto_reason = 'over_inline_bytes';- return out;+ return confirmed(out);}- return { ...out, truncated: true };+ return confirmed({ ...out, truncated: true });}// window: chosen, then measured as the final encoded frame; text that escapes heavily shrinks the window until it fits.@@ -473,14 +489,14 @@ export async function readPartialBody(ctx: OperationContext, input: PartialReadIlet maxBytes = await windowBudget(ctx, req.maxBytes ?? (sel?.kind === 'cursor' ? decodeCursor(sel.raw)?.max_bytes : undefined), DEFAULT_WINDOW_BYTES);for (let attempt = 0; ; attempt++) {const win = await select(maxBytes);- if (!win) return { ...out, truncated: true };+ if (!win) return confirmed({ ...out, truncated: true });out.window = { ...win, text: envelopeText(win.text, quarantined, trust) };out.truncated = win.byte_start > 0 || win.byte_end < doc.total;if (win.byte_end < doc.total) setNext(out, page, encodeCursor({ page_id: page.id, revision, view: req.view, offset: win.byte_end, max_bytes: cursorMax }), markdown);else { delete out.next_cursor; delete out.next; }- if (!Number.isFinite(cap) || attempt >= 6) return out;+ if (!Number.isFinite(cap) || attempt >= 6) return confirmed(out);const frame = encodedFrameBytes({ content: [{ type: 'text', text: JSON.stringify(out) }] }) + ENVELOPE_RESERVE_BYTES - FRAME_RESERVE_BYTES;- if (frame <= cap || win.byte_end - win.byte_start <= 1) return out;+ if (frame <= cap || win.byte_end - win.byte_start <= 1) return confirmed(out);maxBytes = Math.max(1, Math.floor((win.byte_end - win.byte_start) * (cap / frame) * 0.9));}}diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.tsindex d26eb55edb..e61341bf6c 100644--- a/src/core/ops/pages.ts+++ b/src/core/ops/pages.ts@@ -19,7 +19,7 @@ import { PageSnapshotAmbiguousError, type PageSnapshot } from '../page-state/typimport { serializePageToMarkdown } from '../markdown.ts';import { pageTrustForRead, projectFetchText, projectGetPage, readQuarantined } from './get-page-projection.ts';import { assertLargePageAdmission } from '../persistence/large-page-guard.ts';-import { assertFullReadFits, bodyBytes, fetchWindowResult, GET_PAGE_BODY_PARAMS, inlineBodyBytes, parseBodyRequest, readPartialBody, segmentedFullReadError } from './get-page-body.ts';+import { assertFullReadFits, bodyBytes, fetchWindowResult, GET_PAGE_BODY_PARAMS, inlineBodyBytes, parseBodyRequest, readPartialBody, segmentedFullReadError, authorizedReadPin } from './get-page-body.ts';import { isSegmentedPage } from '../page-body/page-shape.ts';import { MIN_TRUST_PARAM } from '../eligibility/policy.ts';import { stampRowTrust } from '../eligibility/stamp.ts';@@ -222,15 +222,16 @@ const get_page: Operation = {const quarantined = readQuarantined(ctx, page, p.include_quarantined === true); // #6259const fileHeld = held ? { file_held: fileHeldField(held, isUntrustedReader) } : {};const segmented = isSegmentedPage(page);+ const pin = authorizedReadPin(ctx, page, snapshot!.bodyGeneration, p.min_trust, () => pageNotFoundError(ctx, slug, { includeDeleted, sourceIdParam }));const whole = bodyRequest.mode === 'full'|| (bodyRequest.mode === 'auto' && !segmented && bodyBytes(visibleBody) <= await inlineBodyBytes(ctx));if (!whole) {- const partial = await readPartialBody(ctx, { page, visibleBody, revision: snapshot!.revision, tags, quarantined, trust: readable.trust,+ const partial = await readPartialBody(ctx, { page, visibleBody, revision: snapshot!.revision, tags, quarantined, trust: readable.trust, pin,extras: { ...(quarantined ? { quarantined } : {}), ...(timelineEntries ? { timeline_entries: timelineEntries } : {}), ...fileHeld,...(resolved_slug ? { resolved_slug } : {}), ...(content_flag ? { content_flag } : {}) } }, bodyRequest);return lineGrammar ? { ...partial, line_grammar: lineGrammar } : partial;}- if (segmented) throw await segmentedFullReadError(ctx, page, bodyRequest);+ if (segmented) throw await segmentedFullReadError(ctx, page, bodyRequest, { ...pin, revision: snapshot!.revision });const projected = projectGetPage(visibleBody, {revision: snapshot!.revision, tags, includeContent, contentOnly, resolved_slug, content_flag, quarantined, trust: readable.trust,...(timelineEntries ? { timeline_entries: timelineEntries } : {}),@@ -299,7 +300,8 @@ const fetch_page: Operation = {const visibleBody = ctx.remote === false || segmented ? page : stripPrivacyFencesForRemoteReader(page);const quarantined = readQuarantined(ctx, page, p.include_quarantined === true);if (!quarantined?.body_omitted && (segmented || (ctx.remote !== false && bodyBytes(visibleBody) > await inlineBodyBytes(ctx)))) {- return fetchWindowResult(ctx, { page, visibleBody: visibleBody as Page, revision: snapshot!.revision, tags, quarantined, trust: readable.trust, extras: {} }, id, identity ? decodeDeepResearchAnchor(id) : null);+ const pin = authorizedReadPin(ctx, page, snapshot!.bodyGeneration, p.min_trust, missing);+ return fetchWindowResult(ctx, { page, visibleBody: visibleBody as Page, revision: snapshot!.revision, tags, quarantined, trust: readable.trust, extras: {}, pin }, id, identity ? decodeDeepResearchAnchor(id) : null);}return {id: identity ? id : page.slug,diff --git a/src/core/page-body/read-range.ts b/src/core/page-body/read-range.tsindex ea4dbd099e..63d2f0884d 100644--- a/src/core/page-body/read-range.ts+++ b/src/core/page-body/read-range.ts@@ -41,6 +41,8 @@ import { readBodyLedger, overlaySegmentText, type BodyLedger } from './segment-limport { 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';+import { opError } from '../ops/contract.ts';+import { REVISION_BACKFILL_PENDING } from '../page-state/types.ts';export type BodySpace = 'stored' | 'projected';export type BodyAudience = 'trusted' | 'remote';@@ -64,6 +66,18 @@ export interface BodyRow {hasDate: boolean;}+/**+ * What a caller authorized before it reads a segmented body: the page's knowledge revision and, when its snapshot says,+ * the body generation. Every visibility, deletion, metadata or body change advances the revision, so a pinned read+ * refuses (revision_changed) rather than read a body or a page state nobody authorized; `admit` re-runs the parts of+ * the authorization the revision does not cover (a trust floor, a re-derivation hold) and throws to refuse.+ */+export interface BodyPin {+ revision: string;+ generation?: number;+ admit?: () => Promise<void>;+}+/** 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;@@ -79,6 +93,8 @@ export interface SegmentedBody {/** The page was segmented by another segmenter version: every segment's regions are recomputed. */stale: boolean;layout?: ProjectedLayout;+ /** Set when the read follows an authorization: confirmBodyPin checks it again before the text is returned. */+ pin?: BodyPin;}/** Where every row of the read projection sits (`projectedLayout`). */@@ -114,6 +130,8 @@ export interface BodyRangeRequest {body?: SegmentedBody;/** The page's ledger when the caller read a snapshot; else loaded. */ledger?: BodyLedger;+ /** The authorization this read follows (openSegmentedBody). */+ pin?: BodyPin;}export interface BodyRangePiece {@@ -137,11 +155,28 @@ const toJson = (v: unknown) => typeof v === 'string' ? JSON.parse(v) as unknownconst 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> {+/** The page row a pin was taken at: same revision and, when pinned, the same body generation. */+async function checkPin(pin: BodyPin, page: Record<string, unknown> | undefined, pageId: number): Promise<void> {+ const revision = page?.revision == null ? REVISION_BACKFILL_PENDING : String(page.revision);+ if (!page || revision !== pin.revision || (pin.generation !== undefined && Number(page.body_generation) !== pin.generation)) {+ const slug = page?.slug == null ? String(pageId) : String(page.slug);+ throw opError('revision_changed', `Page ${slug} changed after this read was authorized; nothing from the read was returned.`,+ "Read the page again: get_page body: 'none' returns its current revision, then read the window or outline you wanted.",+ { legacy_error: 'invalid_params', detail: JSON.stringify({ page_id: pageId }) });+ }+ await pin.admit?.();+}++/**+ * Open a segmented body. With `pin` the read is the authorized one: the page must still be at the pinned revision (and+ * generation), the caller's admission is re-run, and the rows read are that generation's.+ */+export async function openSegmentedBody(engine: BrainEngine, opts: { pageId: number; generation?: number; ledger?: BodyLedger; pin?: BodyPin }): Promise<SegmentedBody> {const [page] = await engine.executeRaw<Record<string, unknown>>(`SELECT id, source_id, slug, body_storage, body_generation, body_bytes, body_lines, truth_bytes,- body_flags, segmenter_version FROM pages WHERE id=$1`, [opts.pageId]);+ body_flags, segmenter_version, knowledge_revision::text AS revision FROM pages WHERE id=$1`, [opts.pageId]);+ if (opts.pin) await checkPin(opts.pin, page, 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 generation = opts.pin?.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.line_count, 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@@ -149,10 +184,11 @@ export async function openSegmentedBody(engine: BrainEngine, opts: { pageId: numWHERE 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);+ assertRowsTile(rows, slug, sourceId, generation === Number(page.body_generation) ? Number(page.body_bytes ?? 0) : null);const ledger = opts.ledger ?? await readBodyLedger(engine, sourceId, slug);return {pageId: opts.pageId, sourceId, slug, generation, bodyBytes: Number(page.body_bytes ?? 0), bodyLines: Number(page.body_lines ?? 0), truthBytes: Number(page.truth_bytes ?? 0),- flags: (toJson(page.body_flags) ?? {}) as JsonObject, ledger, stale: Number(page.segmenter_version) !== SEGMENTER_VERSION,+ flags: (toJson(page.body_flags) ?? {}) as JsonObject, ledger, stale: Number(page.segmenter_version) !== SEGMENTER_VERSION, ...(opts.pin ? { pin: opts.pin } : {}),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), lineCount: Number(r.line_count), staticProjBytes: Number(r.static_proj_bytes),@@ -161,6 +197,29 @@ export async function openSegmentedBody(engine: BrainEngine, opts: { pageId: num};}+/**+ * The generation's rows must run from byte 0 without a gap, to body_bytes when it is the live generation (`total`): a+ * role that sees the page row but not its manifest rows, or rows missing, would otherwise read as a short or empty body.+ */+function assertRowsTile(rows: Array<Record<string, unknown>>, slug: string, sourceId: string, total: number | null): void {+ let end = 0;+ for (const row of rows) {+ if (Number(row.byte_start) !== end) { end = -1; break; }+ end += Number(row.byte_len);+ }+ if (end >= 0 && (total === null ? rows.length > 0 : end === total)) return;+ throw opError('page_body_rows_unreadable', `Page ${slug} (source ${sourceId}): the segment rows readable here do not cover its ${total ?? 'stored'}-byte body, so nothing was read.`,+ "Give the role that reads the brain the same access to page_body_manifest and page_segment_texts it has to pages, then read again.",+ { detail: JSON.stringify({ rows: rows.length, covered_bytes: end >= 0 ? end : null, body_bytes: total }) });+}++/** After a pinned read, before its text is returned: the page is still at the pin and still admits the caller. */+export async function confirmBodyPin(engine: BrainEngine, body: SegmentedBody): Promise<void> {+ if (!body.pin) return;+ const [page] = await engine.executeRaw<Record<string, unknown>>('SELECT slug, body_generation, knowledge_revision::text AS revision FROM pages WHERE id=$1', [body.pageId]);+ await checkPin(body.pin, page, body.pageId);+}+interface LoadedSegment {row: BodyRow;bytes: Uint8Array;diff --git a/src/core/page-body/schema.ts b/src/core/page-body/schema.tsindex 4df12149e0..695e85c1a6 100644--- a/src/core/page-body/schema.ts+++ b/src/core/page-body/schema.ts@@ -68,10 +68,14 @@ CREATE INDEX IF NOT EXISTS page_body_staging_texts_text ON page_body_staging_tex*/export function stagingNeedsTextSql(t: string): string {return `EXISTS (SELECT 1 FROM page_body_staging_texts r JOIN page_body_stagings rs ON rs.id = r.staging_id- WHERE r.source_id = ${t}.source_id AND r.sha256 = ${t}.sha256- AND (rs.state IN ('open','sealed','prepared')+ WHERE r.source_id = ${t}.source_id AND r.sha256 = ${t}.sha256 AND ${liveStagingSql('rs')})`;+}++/** The staging `s` (an alias of page_body_stagings) is live in stagingNeedsTextSql's sense: a write that may still publish it. */+export function liveStagingSql(s: string): string {+ return `(${s}.state IN ('open','sealed','prepared')OR EXISTS (SELECT 1 FROM persistence_requests rq WHERE rq.state IN ('queued','running','recovering')- AND rq.intent->'body_ref'->>'staging_id' = rs.id::text)))`;+ AND rq.intent->'body_ref'->>'staging_id' = ${s}.id::text))`;}/**diff --git a/src/core/page-body/segment-blocks.ts b/src/core/page-body/segment-blocks.tsindex 9c2e922bf9..ce7680a0f5 100644--- a/src/core/page-body/segment-blocks.ts+++ b/src/core/page-body/segment-blocks.ts@@ -22,7 +22,7 @@import type { BrainEngine } from '../engine.ts';import { opError } from '../ops/contract.ts';import { SEGMENT_MAX_BYTES } from './limits.ts';-import { bodyRowWork, openSegmentedBody, readBodyRange, trustedSegments, type TrustedSegment } from './read-range.ts';+import { bodyRowWork, confirmBodyPin, openSegmentedBody, readBodyRange, trustedSegments, type BodyPin, type TrustedSegment } from './read-range.ts';import { cutBlocked } from './segmenter.ts';import { readEntryState } from './entry-state.ts';import type { BodyRegion } from './types.ts';@@ -164,10 +164,15 @@ export async function* bodyBlocks(engine: BrainEngine, page: { id: number; slug:}}-/** The first `chars` UTF-16 units of a segmented page's trusted compiled truth, reading at most 4 x `chars` + 4 bytes. */-export async function truthLead(engine: BrainEngine, pageId: number, chars: number): Promise<string> {+/**+ * The first `chars` UTF-16 units of a segmented page's trusted compiled truth, reading at most 4 x `chars` + 4 bytes;+ * with `pin`, at the revision a caller authorized (openSegmentedBody) or not at all.+ */+export async function truthLead(engine: BrainEngine, pageId: number, chars: number, pin?: BodyPin): Promise<string> {const parts: Buffer[] = [];- for await (const piece of readBodyRange(engine, { pageId, space: 'stored', start: 0, end: 4 * chars + 4, audience: 'trusted', region: 'truth' })) parts.push(piece.bytes);+ const body = await openSegmentedBody(engine, { pageId, ...(pin ? { pin } : {}) });+ for await (const piece of readBodyRange(engine, { pageId, space: 'stored', start: 0, end: 4 * chars + 4, audience: 'trusted', region: 'truth', body })) parts.push(piece.bytes);+ await confirmBodyPin(engine, body);return new TextDecoder('utf-8', { ignoreBOM: true }).decode(Buffer.concat(parts)).slice(0, chars);}diff --git a/src/core/page-body/segment-rewrite.ts b/src/core/page-body/segment-rewrite.tsindex d9beb2a6a4..3b2e4caa7c 100644--- a/src/core/page-body/segment-rewrite.ts+++ b/src/core/page-body/segment-rewrite.ts@@ -178,16 +178,24 @@ const MANIFEST_COLUMNS = `page_id,occurrence_id,seq,region,source_id,sha256,byte* their other generations, and the rebuilt rows (new occurrences, every* coordinate and hash midstate recomputed) cover exactly this one. Each* version row of the generation gets the rebuilt content_hash and size.- * Returns the replaced segment shas, or null when no fence changed.+ * Returns the replaced segment shas, or null when no fence changed. A change+ * to the page's live generation is refused (the page row is locked, so the+ * generation cannot become live under the rebuild).*/export async function rewriteSegmentedGeneration(tx: BrainEngine, pageId: number, generation: number, transform: FenceTransform,version: { title: string; type: string; frontmatter: JsonObject; tags: readonly string[] }): Promise<Uint8Array[] | null> {- const [page] = await tx.executeRaw<{ slug: string; source_id: string; body_flags: JsonObject | null }>('SELECT slug,source_id,body_flags FROM pages WHERE id=$1', [pageId]);+ const [page] = await tx.executeRaw<{ slug: string; source_id: string; body_flags: JsonObject | null; body_storage: string; body_generation: number | string }>(+ 'SELECT slug,source_id,body_flags,body_storage,body_generation FROM pages WHERE id=$1 FOR UPDATE', [pageId]);if (!page) return null;const sourceId = page.source_id;const rows = await tx.readManifest(pageId, { generation });const units = await changedUnits(tx, sourceId, rows, transform);if (!units.length) return null;+ // Rebuilding rows in place is for retained generations only: the live one changes by a flip (rewriteLiveSegmentedFences),+ // which moves the revision and the chunks with it.+ if (page.body_storage === 'segmented' && Number(page.body_generation) === generation) {+ throw new Error(`rewriteSegmentedGeneration: generation ${generation} is the live body of page ${page.slug}; rewrite it with rewriteLiveSegmentedFences.`);+ }const prepared = await prepareSegmentedBody(tx, { sourceId, slug: page.slug, live: null, ...version,truth: rewrittenRegion(tx, sourceId, rows, units, 'truth'), timeline: rewrittenRegion(tx, sourceId, rows, units, 'timeline'),hasTimeline: rows.some(row => row.region === 'timeline'), flags: page.body_flags ?? {}, declaredBytes: bodyBytesOf(rows, units),diff --git a/src/core/page-snapshot-batch.ts b/src/core/page-snapshot-batch.tsindex f8c4300ead..20d315c38e 100644--- a/src/core/page-snapshot-batch.ts+++ b/src/core/page-snapshot-batch.ts@@ -94,7 +94,8 @@ export async function readPageSnapshotsBatch(page.timeline = overlayWithdrawalBody(page.timeline, String(row.fingerprint_timeline ?? ''), withdrawals);}snapshots.set(key, { page, tags: row.snapshot_tags as string[], revision: row.knowledge_revision == null ? REVISION_BACKFILL_PENDING : String(row.knowledge_revision),- sourceIncarnation: String(row.source_incarnation), withdrawals, ...(globalPurges.count > 0 ? { globalPurges } : {}) });+ sourceIncarnation: String(row.source_incarnation), withdrawals, ...(globalPurges.count > 0 ? { globalPurges } : {}),+ ...(isSegmentedPage(page) ? { bodyGeneration: Number(row.body_generation) } : {}) });}return { snapshots, covered: rows.length };}diff --git a/src/core/page-state/snapshot.ts b/src/core/page-state/snapshot.tsindex b1a07f75df..2f6ce8aa1c 100644--- a/src/core/page-state/snapshot.ts+++ b/src/core/page-state/snapshot.ts@@ -132,5 +132,6 @@ async function readSnapshotStatement(query: ReadQuery, slug: string, opts?: Pagepage.timeline = overlayWithdrawalBody(page.timeline, String(row.fingerprint_timeline ?? ''), withdrawals);}return { page, tags: row.snapshot_tags as string[], revision: row.knowledge_revision == null ? REVISION_BACKFILL_PENDING : String(row.knowledge_revision),- sourceIncarnation: String(row.source_incarnation), withdrawals, ...(globalPurges.count > 0 ? { globalPurges } : {}) };+ sourceIncarnation: String(row.source_incarnation), withdrawals, ...(globalPurges.count > 0 ? { globalPurges } : {}),+ ...(isSegmentedPage(page) ? { bodyGeneration: Number(row.body_generation) } : {}) };}diff --git a/src/core/page-state/types.ts b/src/core/page-state/types.tsindex aac927cf29..5020a17fad 100644--- a/src/core/page-state/types.ts+++ b/src/core/page-state/types.ts@@ -74,6 +74,8 @@ export interface PageSnapshot {withdrawals: PageWithdrawal[];/** Subject-'*' purges, listed in `withdrawals` only when the stored text names them. Absent when the source has none under the read's filter. */globalPurges?: GlobalPurgeMarker;+ /** A segmented page's body generation at `revision` (readPageSnapshot): what a read that follows this snapshot pins. */+ bodyGeneration?: number;}/**diff --git a/src/core/persistence/segmented-apply.ts b/src/core/persistence/segmented-apply.tsindex eabaf6fd4b..17cd46c7df 100644--- a/src/core/persistence/segmented-apply.ts+++ b/src/core/persistence/segmented-apply.ts@@ -34,6 +34,7 @@ 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 { bodyStagingGoneError, LIVE_STAGING_STATES } from '../engine-sql/page-body.ts';import { segmentedPageSearchable } from './searchable.ts';import { stableJson } from './digest.ts';@@ -141,6 +142,10 @@ export async function applySegmentedBody(tx: BrainEngine, input: SegmentedApplyIconst { prepared } = input;let pageId = input.pageId;if (prepared.createRows) {+ // A create inserts its manifest rows before the flip checks its staging: a staging a fact purge aborted (and whose+ // claim-bearing texts it deleted) refuses here, not on the manifest's text foreign key.+ const [staging] = await tx.executeRaw<{ state: string }>('SELECT state FROM page_body_stagings WHERE id=$1::uuid FOR UPDATE', [prepared.stagingId]);+ if (!LIVE_STAGING_STATES.includes(staging?.state ?? '')) throw bodyStagingGoneError(input.slug, prepared.stagingId, staging?.state ?? null);pageId = (await tx.createSegmentedPageShell(input.slug, input.meta, { sourceId: input.sourceId })).id;await tx.stageManifestRows(prepared.createRows.map(row => ({ ...row, pageId: pageId! })));}diff --git a/src/core/search/segmented-evidence.ts b/src/core/search/segmented-evidence.tsindex 628ff2357b..3cbf130908 100644--- a/src/core/search/segmented-evidence.ts+++ b/src/core/search/segmented-evidence.ts@@ -20,11 +20,16 @@* drift when a hold or a tier change moves the projection); a hit whose chunk* has no stored span (a fenced-code or low-tier chunk) is placed by a unique* exact match inside its own segment, never by a search of the page.+ *+ * The windows are read at the revision getChunkWindows authorized the page at+ * (`page.revision`): a page that changed since (a visibility flip, a new+ * body, a delete) refuses the read, and the assembler falls back to the hit's+ * chunk.*/import type { BrainEngine } from '../engine.ts';import type { ChunkWindowPage } from './chunk-windows.ts';import { DEFAULT_INLINE_BODY_BYTES, TIMELINE_SEPARATOR } from '../page-window/document.ts';-import { openSegmentedBody, projectedLayout, readBodyRange, type SegmentedBody } from '../page-body/read-range.ts';+import { confirmBodyPin, openSegmentedBody, projectedLayout, readBodyRange, type SegmentedBody } from '../page-body/read-range.ts';/** Bytes read past a window's ends so it can start and end on whole lines. */const LINE_PAD_BYTES = 4096;@@ -47,7 +52,7 @@ interface Located extends EvidenceSpan { row: number; text: string }export async function readSegmentedWindows(engine: BrainEngine, page: ChunkWindowPage,hits: ReadonlyArray<{ chunk_id: number; chunk_index: number; text: string }>,opts: { unit: 'window' | 'section' | 'page'; radius: number; includeTimeline: boolean }): Promise<SegmentedWindows> {- const body = await openSegmentedBody(engine, { pageId: page.page_id });+ const body = await openSegmentedBody(engine, { pageId: page.page_id, pin: { revision: page.revision } });const layout = await projectedLayout(engine, body);const region = opts.includeTimeline ? undefined : 'truth' as const;const bytes = region && layout.timelineByte >= 0 ? layout.timelineByte - Buffer.byteLength(TIMELINE_SEPARATOR, 'utf8') : layout.totalBytes;@@ -116,6 +121,7 @@ export async function readSegmentedWindows(engine: BrainEngine, page: ChunkWindofor (const [id, span] of placedBytes) if (inside(span)) placed.set(id, { run: runs.length, start: charAt(span.start), end: charAt(span.end) });runs.push({ text, spans });}+ await confirmBodyPin(engine, body);return { bytes, overInline, runs, placed };}diff --git a/src/core/verbs/entity-card-identity.ts b/src/core/verbs/entity-card-identity.tsindex 891b66564c..1ad541ea80 100644--- a/src/core/verbs/entity-card-identity.ts+++ b/src/core/verbs/entity-card-identity.ts@@ -28,7 +28,6 @@ import { readIdentitySiblings, SIBLING_GROUP_CAP } from '../mentions/siblings.tsimport type { MentionPolicy, PackTypes } from '../mentions/policy.ts';import type { Notice } from '../agent-output.ts';import type { RecordGroupView } from './entity-references.ts';-import type { Page } from '../types.ts';import { isSegmentedPage } from '../page-body/page-shape.ts';import { truthLead } from '../page-body/segment-blocks.ts';import { boundedRawPrefix } from '../page-window/bounded-lead.ts';@@ -150,10 +149,14 @@ export async function readSiblingIdentity(engine: BrainEngine, sourceId: string,};}-/** The body an excerpt is cut from: the compiled truth, or a segmented page's lead (EXCERPT_LEAD_BYTES, cut back to a whole line when the truth goes on). */-async function excerptSource(engine: BrainEngine, page: Page): Promise<string> {+/**+ * The body an excerpt is cut from: the compiled truth, or a segmented page's lead (EXCERPT_LEAD_BYTES, cut back to a+ * whole line when the truth goes on), read at the snapshot's revision.+ */+async function excerptSource(engine: BrainEngine, snapshot: PageSnapshot): Promise<string> {+ const { page } = snapshot;if (!isSegmentedPage(page)) return page.compiled_truth ?? '';- const lead = await truthLead(engine, page.id, EXCERPT_LEAD_BYTES);+ const lead = await truthLead(engine, page.id, EXCERPT_LEAD_BYTES, { revision: snapshot.revision, generation: snapshot.bodyGeneration });const bounded = boundedRawPrefix(lead, EXCERPT_LEAD_BYTES);if (bounded.length === lead.length && lead.length < EXCERPT_LEAD_BYTES) return lead;return bounded.slice(0, Math.max(0, bounded.lastIndexOf('\n')));@@ -178,7 +181,7 @@ export async function readCardIdentity(engine: BrainEngine, sourceId: string,const bodies = new Map<string, { title: string; body: string }>();for (const slug of slugs) {const snapshot = snapshots.get(pageSnapshotKey(sourceId, slug));- if (snapshot) bodies.set(slug, { title: snapshot.page.title ?? slug, body: await excerptSource(engine, snapshot.page).catch(() => '') });+ if (snapshot) bodies.set(slug, { title: snapshot.page.title ?? slug, body: await excerptSource(engine, snapshot).catch(() => '') });}const excerpt: IdentityExcerptLine[] = [];const omitted: string[] = [];diff --git a/test/large-pages/pinned-segmented-reads.test.ts b/test/large-pages/pinned-segmented-reads.test.tsnew file mode 100644index 0000000000..f9511f1982--- /dev/null+++ b/test/large-pages/pinned-segmented-reads.test.ts@@ -0,0 +1,266 @@+/**+ * Wave B PR 2 fix lane F (F1): a segmented read that follows an authorization reads the authorized revision or+ * nothing.+ *+ * 1. Protects: remote get_page (none, outline, auto, a bytes window, the markdown view, around_chunk_id, the whole-body+ * refusal), fetch, assemble_evidence windows and the entity card's identity excerpt authorize a page snapshot and+ * then open its segmented body. A page made private (frontmatter visibility plus a new body generation holding a+ * secret) between that authorization and the segment read, a visibility-only flip while the segments are being+ * read, and a trust demotion below the caller's min_trust (no revision change) all refuse the raced read+ * (revision_changed or page_not_found; evidence falls back to the hit chunk; the card shows no excerpt), and a+ * fresh read is page_not_found. An unchanged page reads normally under the pin.+ * 2. Fails when: openSegmentedBody reads the live generation instead of the snapshot's (b9787c6a9 returned the new+ * private body's text to the raced reader), a pinned read is returned without confirming the page is still at the+ * pinned revision, or the trust floor is not re-checked after the read.+ * N5: manifest rows the reader cannot see (hidden through the engine, as a pages-only RLS policy would) or a gap in the+ * live manifest refuse with page_body_rows_unreadable instead of reading as an empty or truncated body (b9787c6a9+ * answered total_bytes 0).+ * N8: remote get_versions reports a segmented version's read-projection size (total_bytes), never its stored+ * body_bytes.+ * 3. The race is forced through a one-shot hook on the engine: before openSegmentedBody's page-row query (`open`) or+ * before the first segment-text read (`read`), the hook writes the page; no timing. Runs on PGLite, and on Postgres+ * when DATABASE_URL is set.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../../src/core/engine.ts';+import type { GBrainConfig } from '../../src/core/config.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { operations, type OperationContext } from '../../src/core/operations.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { withCoordinatedWrite, withTrustBackfill } from '../../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from '../helpers/write-attribution.ts';+import { readCardIdentity } from '../../src/core/verbs/entity-card-identity.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { testBackends } from '../helpers/test-backends.ts';+import { importSegmented } from '../helpers/segmented-privacy-fixture.ts';++const SECRET = ['zz', 'secret', 'pinned', 'token'].join('');+const NEEDLE = 'zzpinneedle';+const op = (name: string) => operations.find(o => o.name === name)!;+let engine: BrainEngine;++const ctx = (): OperationContext => ({ engine, config: {} as GBrainConfig, logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote: true,+ sourceId: 'default', emitResponseMeta: () => {}, transport: 'http', auth: { token: 'fixture', clientId: 'pin-client',+ principal: { kind: 'oauth_client', id: 'pin-client' }, scopes: ['read'], sourceId: 'default', allowedSources: ['default'] } } as unknown as OperationContext);+const call = async (name: string, params: Record<string, unknown>) => await op(name).handler(ctx(), params) as Record<string, any>;++function filler(bytes: number, tag: string): string {+ const parts: string[] = [];+ for (let i = 0, n = 0; n < bytes; i++) {+ const part = `## Section ${tag} ${i}\n\n${`Public notes on launch planning and roadmap review for week ${i}. `.repeat(30)}\n\n`;+ parts.push(part);+ n += part.length;+ }+ return parts.join('');+}+const publicBody = (tag: string) => `Nickname: Copper Pin\n\n${filler(700_000, tag)}\n${NEEDLE} marks the middle once\n\n${filler(700_000, `${tag}b`)}`;+const content = (body: string, extra = '') => `---\ntitle: Pinned probe\ntype: note\n${extra}---\n\n${body}`;++/** The authorized page becomes private with a new body generation whose lead holds SECRET. */+const privateRewrite = (slug: string) => async () => {+ await importFromContent(engine, slug, content(`Codename: ${SECRET} Alpha\n\n${SECRET} is the private body now.\n\n${filler(1_300_000, 'private')}`, 'visibility: private\n'),+ { sourceId: 'default', noEmbed: true });+};+const visibilityOnly = (slug: string) => async () => {+ await engine.executeRaw(`UPDATE pages SET frontmatter = frontmatter || '{"visibility":"private"}'::jsonb WHERE source_id='default' AND slug=$1`, [slug]);+};++type Outcome = { ok: boolean; code?: string; text: string };+const OPEN_SQL = 'SELECT id, source_id, slug, body_storage, body_generation';+/** Runs `flip` once, before openSegmentedBody's page-row query (`open`) or the first segment-text read (`read`); reports whether it fired. */+async function raced(seam: 'open' | 'read', flip: () => Promise<void>, read: () => Promise<unknown>): Promise<{ fired: boolean; outcome: Outcome }> {+ let fired = false;+ const exec = engine.executeRaw;+ const texts = engine.readSegmentTexts;+ const fire = async () => { fired = true; await flip(); };+ // A transaction's engine inherits from `engine` (Object.create on PGLite), so the hooks keep the caller's `this`.+ if (seam === 'open') {+ engine.executeRaw = (async function (this: BrainEngine, sql: string, params?: unknown[]) {+ if (!fired && sql.startsWith(OPEN_SQL)) await fire();+ return exec.call(this, sql, params);+ }) as typeof engine.executeRaw;+ } else {+ engine.readSegmentTexts = (async function (this: BrainEngine, ...args: Parameters<typeof engine.readSegmentTexts>) {+ if (!fired) await fire();+ return texts.apply(this, args);+ }) as typeof engine.readSegmentTexts;+ }+ try {+ const outcome = await read().then((r): Outcome => ({ ok: true, text: JSON.stringify(r) }),+ (e: { canonical?: string; code?: string; message?: string; detail?: string }): Outcome => ({ ok: false, code: e.canonical ?? e.code, text: `${e.message} ${e.detail ?? ''}` }));+ return { fired, outcome };+ } finally {+ engine.executeRaw = exec;+ engine.readSegmentTexts = texts;+ }+}++const refused = (outcome: Outcome) => ({ ok: outcome.ok, code: outcome.code, leaked: outcome.text.includes(SECRET) });++async function freshReadIsMissing(slug: string) {+ const fresh = await call('get_page', { slug, body: 'none' }).then(() => null, (e: { canonical?: string; code?: string }) => e.canonical ?? e.code);+ expect(fresh).toBe('page_not_found');+}++for (const kind of testBackends()) {+ describe(`segmented reads pinned to the authorized revision (${kind})`, () => {+ let close: () => Promise<void>;+ let n = 0;+ const page = async () => {+ const slug = `notes/pinned-${++n}`;+ const id = await importSegmented(engine, slug, content(publicBody(`p${n}`)));+ return { slug, id };+ };+ const needleChunk = async (pageId: number) => (await engine.executeRaw<{ id: number; chunk_text: string }>(+ 'SELECT id, chunk_text FROM content_chunks WHERE page_id=$1 AND strpos(chunk_text, $2) > 0 ORDER BY chunk_index LIMIT 1', [pageId, NEEDLE]))[0]!;++ 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 () => { await engine.executeRaw('DELETE FROM pages'); });++ const shapes: Array<[string, Record<string, unknown>]> = [+ ['none', { body: 'none' }], ['outline', { body: 'outline' }], ['auto', {}], ['bytes window', { body: 'window', bytes: { offset: 0, length: 20_000 } }],+ ['markdown view', { body: 'window', view: 'markdown', bytes: { offset: 0, length: 20_000 } }], ['whole-body refusal', { body: 'full' }],+ ];+ for (const [label, params] of shapes) {+ test(`get_page ${label}: a page made private with a new body between authorization and the read is refused`, async () => {+ const { slug } = await page();+ const { fired, outcome } = await raced('open', privateRewrite(slug), () => call('get_page', { slug, ...params }));+ expect(fired).toBe(true);+ expect(refused(outcome)).toEqual({ ok: false, code: 'revision_changed', leaked: false });+ await freshReadIsMissing(slug);+ }, 240_000);+ }++ test('get_page around_chunk_id: the raced read is refused', async () => {+ const { slug, id } = await page();+ const hit = await needleChunk(id);+ const { fired, outcome } = await raced('open', privateRewrite(slug), () => call('get_page', { slug, around_chunk_id: Number(hit.id) }));+ expect(fired).toBe(true);+ expect(refused(outcome)).toEqual({ ok: false, code: 'revision_changed', leaked: false });+ }, 240_000);++ test('get_page window: a visibility flip while the segments are read refuses the result', async () => {+ const { slug } = await page();+ const { fired, outcome } = await raced('read', visibilityOnly(slug), () => call('get_page', { slug, body: 'window', bytes: { offset: 600_000, length: 20_000 } }));+ expect(fired).toBe(true);+ expect(refused(outcome)).toEqual({ ok: false, code: 'revision_changed', leaked: false });+ await freshReadIsMissing(slug);+ }, 240_000);++ test('get_page window: a trust demotion below min_trust (no revision change) is re-checked and reads as missing', async () => {+ const { slug, id } = await page();+ await engine.transaction(tx => withTrustBackfill(tx, () => tx.executeRaw("UPDATE pages SET trust_tier='operator_curated' WHERE id=$1", [id])));+ const params = { slug, body: 'window', bytes: { offset: 0, length: 20_000 }, min_trust: 'agent_written' };+ expect((await call('get_page', params)).window.text).toContain('Copper Pin');+ const [before] = await engine.executeRaw<{ revision: string }>('SELECT knowledge_revision::text AS revision FROM pages WHERE id=$1', [id]);+ const demote = async () => { await engine.executeRaw("UPDATE pages SET trust_tier='external_untrusted' WHERE id=$1", [id]); };+ const { fired, outcome } = await raced('open', demote, () => call('get_page', params));+ expect(fired).toBe(true);+ expect((await engine.executeRaw<{ revision: string }>('SELECT knowledge_revision::text AS revision FROM pages WHERE id=$1', [id]))[0]!.revision).toBe(before!.revision);+ expect(refused(outcome)).toEqual({ ok: false, code: 'page_not_found', leaked: false });+ }, 240_000);++ test('fetch: the raced window is refused', async () => {+ const { slug } = await page();+ const { fired, outcome } = await raced('open', privateRewrite(slug), () => call('fetch', { id: slug }));+ expect(fired).toBe(true);+ expect(refused(outcome)).toEqual({ ok: false, code: 'revision_changed', leaked: false });+ }, 240_000);++ test('assemble_evidence: the raced window falls back to the authorized hit chunk', async () => {+ const { slug, id } = await page();+ const hit = await needleChunk(id);+ const { fired, outcome } = await raced('open', privateRewrite(slug),+ () => call('assemble_evidence', { hits: [{ source_id: 'default', slug, chunk_id: Number(hit.id) }], return_unit: 'window', return_window: 2, token_budget: 30_000 }));+ expect(fired).toBe(true);+ expect(outcome.ok).toBe(true);+ expect(outcome.text.includes(SECRET)).toBe(false);+ const [block] = JSON.parse(outcome.text).results as Array<{ chunk_text: string; delivered: { unit: string; fallback_reason?: string } }>;+ expect({ unit: block!.delivered.unit, reason: block!.delivered.fallback_reason }).toEqual({ unit: 'chunk', reason: 'segment_read_failed' });+ expect(block!.chunk_text).toBe(hit.chunk_text);+ }, 240_000);++ test('entity card excerpt: a raced lead read shows nothing of the new body', async () => {+ const { slug } = await page();+ const { fired, outcome } = await raced('open', privateRewrite(slug),+ () => readCardIdentity(engine, 'default', { slug, title: 'Pinned probe', compiled_truth: null }, { excludePrivate: true, aka: [] }));+ expect(fired).toBe(true);+ expect(outcome.ok).toBe(true);+ expect(outcome.text.includes(SECRET)).toBe(false);+ }, 240_000);++ // N5: a role that sees the page row but not its manifest rows (a pages-only RLS policy or grant), or rows missing.+ const ROWS_SQL = 'SELECT m.seq, m.occurrence_id';+ test('manifest rows hidden from the reader refuse the read with page_body_rows_unreadable, never an empty body', async () => {+ const { slug } = await page();+ const exec = engine.executeRaw;+ engine.executeRaw = (async function (this: BrainEngine, sql: string, params?: unknown[]) {+ return sql.startsWith(ROWS_SQL) ? [] : exec.call(this, sql, params);+ }) as typeof engine.executeRaw;+ try {+ for (const params of [{ body: 'none' }, { body: 'window', bytes: { offset: 0, length: 20_000 } }, { body: 'outline' }]) {+ const outcome = await call('get_page', { slug, ...params }).then(r => ({ code: 'ok', total: r.size?.total_bytes }), (e: { canonical?: string; code?: string }) => ({ code: e.canonical ?? e.code }));+ expect({ params, outcome }).toEqual({ params, outcome: { code: 'page_body_rows_unreadable' } });+ }+ } finally {+ engine.executeRaw = exec;+ }+ }, 240_000);++ test('a gap in the live manifest refuses the read with page_body_rows_unreadable', async () => {+ const { slug, id } = await page();+ await engine.executeRaw('DELETE FROM page_body_manifest WHERE page_id=$1 AND staging_id IS NULL AND gen_to IS NULL AND seq=(SELECT max(seq) / 2 FROM page_body_manifest WHERE page_id=$1 AND gen_to IS NULL)', [id]);+ const outcome = await call('get_page', { slug, body: 'window', bytes: { offset: 0, length: 20_000 } }).then(() => 'ok', (e: { canonical?: string; code?: string }) => e.canonical ?? e.code);+ expect(outcome).toBe('page_body_rows_unreadable');+ }, 240_000);++ // N8: get_versions tells a remote caller a segmented version's projected size, never its stored body_bytes.+ test('remote get_versions reports a segmented version by its read projection size, not the stored body_bytes', async () => {+ const slug = `notes/pinned-versions-${++n}`;+ const takes = `<!--- gbrain:takes:begin -->\n${'Hidden take about pricing strategy. '.repeat(8000)}\n<!--- gbrain:takes:end -->\n`;+ const id = await importSegmented(engine, slug, content(`${publicBody(`v${n}`)}\n\n${takes}`));+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.createVersion(slug, { sourceId: 'default' }), TEST_WRITE_ATTRIBUTION));+ const projected = (await call('get_page', { slug, body: 'none' })).size.total_bytes as number;+ const [stored] = await engine.executeRaw<{ body_bytes: number }>('SELECT body_bytes FROM pages WHERE id=$1', [id]);+ expect(projected).toBeLessThan(Number(stored!.body_bytes));+ const [meta] = await call('get_versions', { slug }) as unknown as Array<Record<string, unknown>>;+ expect(meta!.body_storage).toBe('segmented');+ expect(meta!.body_bytes).toBeUndefined();+ expect(meta!.total_bytes).toBe(projected);+ const [full] = await call('get_versions', { slug, include_body: true }) as unknown as Array<Record<string, any>>;+ expect(full!.body_bytes).toBeUndefined();+ expect(full!.body_ref.total_bytes).toBe(projected);+ expect(JSON.stringify([meta, full])).not.toContain(String(stored!.body_bytes));+ }, 240_000);++ test('an unchanged page reads normally under the pin on every path', async () => {+ const { slug, id } = await page();+ const none = await call('get_page', { slug, body: 'none' });+ expect(none.body_storage).toBe('segmented');+ expect(none.size.total_bytes).toBeGreaterThan(1_300_000);+ expect((await call('get_page', { slug, body: 'outline' })).outline.entries.length).toBeGreaterThan(0);+ expect((await call('get_page', { slug })).window.text).toContain('Copper Pin');+ let r = await call('get_page', { slug, body: 'window', max_bytes: 400_000 });+ const parts = [r.window.text as string];+ while (r.next_cursor) { r = await call('get_page', { slug, cursor: r.next_cursor }); parts.push(r.window.text); }+ expect(Buffer.byteLength(parts.join(''))).toBe(none.size.total_bytes);+ expect(parts.join('')).toContain(NEEDLE);+ expect((await call('get_page', { slug, body: 'window', view: 'markdown', bytes: { offset: 0, length: 20_000 } })).window.text).toContain('Copper Pin');+ const hit = await needleChunk(id);+ expect((await call('get_page', { slug, around_chunk_id: Number(hit.id) })).window.text).toContain(NEEDLE);+ const refusal = await call('get_page', { slug, body: 'full' }).then(() => null, (e: { code?: string; detail?: string }) => e);+ expect(refusal?.code).toBe('page_body_segmented');+ expect(JSON.parse(refusal!.detail!).total_bytes).toBe(none.size.total_bytes);+ expect((await call('fetch', { id: slug })).text).toContain('Copper Pin');+ const evidence = await call('assemble_evidence', { hits: [{ source_id: 'default', slug, chunk_id: Number(hit.id) }], return_unit: 'window', return_window: 2, token_budget: 30_000 });+ expect(evidence.results[0].delivered.unit).toBe('window');+ expect(evidence.results[0].chunk_text).toContain(NEEDLE);+ const card = await readCardIdentity(engine, 'default', { slug, title: 'Pinned probe', compiled_truth: null }, { excludePrivate: true, aka: [] });+ expect(card.identity_excerpt).toContainEqual({ slug, line: 'Nickname: Copper Pin' });+ }, 300_000);+ });+}diff --git a/test/large-pages/purge-fact-inflight-staging.test.ts b/test/large-pages/purge-fact-inflight-staging.test.tsnew file mode 100644index 0000000000..fab1984c7c--- /dev/null+++ b/test/large-pages/purge-fact-inflight-staging.test.ts@@ -0,0 +1,213 @@+/**+ * Wave B PR 2 fix lane F (F2): purge_fact and segment GC with a create in flight.+ *+ * 1. Protects: a create keeps its manifest rows in memory until it publishes and records its texts in+ * page_body_staging_texts. purge_fact aborts a live staging that recorded a text holding the purged claim, deletes+ * that text in the same transaction, and the create then refuses cleanly with body_staging_expired (nothing+ * claim-bearing survives); a create in flight that shares only texts without the claim keeps its staging and publishes. The+ * segment GC keeps every text a live staging recorded, even one older than the staging (a create that deduped onto+ * an older text), and still collects the texts of an aborted staging.+ * A page purge of an inline page never probes other pages' segment texts as its own residue: a segmented page that+ * states the purged page's claim in prose leaves the receipt complete.+ * L3: rewriteSegmentedGeneration (the in-place rebuild of a version's retained generation) refuses the page's live+ * generation, which only a flip may change.+ * 2. Fails when: planFactPurge ignores page_body_staging_texts (b9787c6a9: the purge committed, deleted the text and+ * left the staging open, so the create's manifest insert died on page_body_manifest's text foreign key), or GC+ * protects a staging's texts only when the staging is older than the text, or the page purge receipt of an inline page+ * probes page_segment_texts for its claims (b9787c6a9: page_segment_texts incomplete, so the purge exits 75), or+ * rewriteSegmentedGeneration accepts the live generation (b9787c6a9: it rewrote the live body in place).+ * 3. Runs on PGLite, and on Postgres when DATABASE_URL is set.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../../src/core/engine.ts';+import type { OperationContext } from '../../src/core/ops/contract.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { parseMarkdown } from '../../src/core/markdown.ts';+import { operations } from '../../src/core/operations.ts';+import { readPageBodyPolicy } from '../../src/core/page-body/limits.ts';+import { materializeSegmentedBody } from '../../src/core/page-body/ingest.ts';+import { registerLocalWriter } from '../../src/core/persistence/identity.ts';+import { withCoordinatedWrite } from '../../src/core/persistence/context.ts';+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';+import { stageSegmentedImport } from '../../src/core/persistence/segmented-apply.ts';+import { rewriteSegmentedGeneration } from '../../src/core/page-body/segment-rewrite.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { segmentedPageRow } from '../helpers/segmented-page-checks.ts';+import { testBackends } from '../helpers/test-backends.ts';+import { TEST_WRITE_ATTRIBUTION } from '../helpers/write-attribution.ts';+import { withEnv } from '../helpers/with-env.ts';++const CLAIM = ['Gate', 'code', 'is', '7731'].join(' ');+const FENCE = `<!--- gbrain:facts:begin -->+| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |+|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|+| 1 | ${CLAIM} | fact | 1.0 | world | medium | 2026-01-01 | | chat | |+| 2 | Likes green tea | preference | 1.0 | world | medium | 2026-01-01 | | chat | |+<!--- gbrain:facts:end -->`;+const home = mkdtempSync(join(tmpdir(), 'gbrain-purge-staging-texts-'));+const env = { GBRAIN_HOME: home, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };+const ctx = (engine: BrainEngine): OperationContext => ({ engine, sourceId: 'default', remote: false, dryRun: false,+ config: { engine: engine.kind }, logger: { info() {}, warn() {}, error() {} } } as OperationContext);+const purge = operations.find(o => o.name === 'purge_fact')!;+const coordinated = <T>(engine: BrainEngine, fn: (tx: BrainEngine) => Promise<T>) =>+ engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => fn(tx), TEST_WRITE_ATTRIBUTION));++function filler(bytes: number, tag: string): string {+ const parts: string[] = [];+ for (let i = 0, n = 0; n < bytes; i++) {+ const part = `## Section ${tag} ${i}\n\n${`Notes on launch planning, pricing and roadmap review for week ${i}. `.repeat(30)}\n\n`;+ parts.push(part);+ n += part.length;+ }+ return parts.join('');+}+const page = (title: string, body: string) => `---\ntitle: ${title}\ntype: note\n---\n\n${body}`;+const withFence = (tag: string, tail: string) => `# Shared notes\n\nIntro paragraph.\n\n## Facts\n\n${FENCE}\n\n${filler(1_300_000, tag)}## Tail\n\n${tail}\n`;++afterAll(() => { rmSync(home, { recursive: true, force: true }); });++for (const kind of testBackends()) {+ describe(`purge_fact and segment GC with a create in flight (${kind})`, () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ beforeAll(async () => withEnv(env, 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(); }+ await registerLocalWriter(engine, 'cli');+ await engine.setConfig('pages.segmented_storage', 'on');+ }), 120_000);+ afterAll(async () => withEnv(env, async () => { await disposePersistenceConsumer(engine); await close?.(); }));++ /** A create whose preparation finished (texts staged and recorded, manifest rows in memory) and has not published. */+ async function inFlightCreate(slug: string, content: string) {+ const parsed = parseMarkdown(content, `${slug}.md`);+ const staged = await stageSegmentedImport(engine, { slug, sourceId: 'default', existing: null,+ page: { title: parsed.title, type: parsed.type, compiled_truth: parsed.compiled_truth, timeline: parsed.timeline, frontmatter: parsed.frontmatter, tags: parsed.tags },+ policy: await readPageBodyPolicy(engine), chunking: { quarantined: false, corpusGeneration: null, tier: 'none' }, baseRevision: null });+ return {+ parsed, stagingId: staged.prepared.stagingId,+ publish: () => engine.transaction(tx => staged.apply(tx, { type: parsed.type, title: parsed.title, frontmatter: parsed.frontmatter, page_kind: 'markdown' },+ { mode: 'none', corpusGeneration: null })),+ };+ }+ const stagingState = async (id: string) => (await engine.executeRaw<{ state: string }>('SELECT state FROM page_body_stagings WHERE id=$1::uuid', [id]))[0]?.state;+ const recorded = async (id: string) => (await engine.executeRaw<{ sha: string }>("SELECT encode(sha256,'hex') AS sha FROM page_body_staging_texts WHERE staging_id=$1::uuid", [id])).map(r => r.sha);+ const textsLeft = async (shas: readonly string[]) => Number((await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM page_segment_texts+ WHERE source_id='default' AND sha256=ANY(SELECT decode(h,'hex') FROM unnest($1::text[]) AS h)`, [shas]))[0]!.n);+ const expectPublished = async (slug: string, create: { parsed: { compiled_truth: string } }) => {+ const row = await segmentedPageRow(engine, slug);+ expect((await materializeSegmentedBody(engine, row.id, 'default')).compiled_truth).toBe(create.parsed.compiled_truth);+ };++ test('purge_fact aborts the in-flight create that recorded a claim-bearing text; an unrelated create still publishes', async () => withEnv(env, async () => {+ const tag = randomUUID().slice(0, 8);+ const purged = `notes/purged-${tag}`;+ await importFromContent(engine, purged, page('Purged', withFence(tag, 'The purged page tail.')), { sourceId: 'default', noEmbed: true });+ expect((await segmentedPageRow(engine, purged)).body_storage).toBe('segmented');+ const [fact] = await coordinated(engine, tx => tx.executeRaw<{ id: number }>(`INSERT INTO facts(source_id,fact,entity_slug,visibility,source,source_markdown_slug,row_num)+ VALUES ('default',$1,NULL,'world','test',$2,1) RETURNING id`, [CLAIM, purged]));+ const holder = await inFlightCreate(`notes/holder-${tag}`, page('Holder', withFence(tag, 'The in-flight create tail.')));+ const bystander = await inFlightCreate(`notes/bystander-${tag}`, page('Bystander', `# Other notes\n\n${filler(1_300_000, tag)}## Tail\n\nThe bystander tail.\n`));+ const claimShas = (await engine.executeRaw<{ sha: string }>(`SELECT encode(t.sha256,'hex') AS sha FROM page_body_staging_texts r JOIN page_segment_texts t+ ON t.source_id=r.source_id AND t.sha256=r.sha256 WHERE r.staging_id=$1::uuid AND position(convert_to($2::text,'UTF8') in t.body)>0`, [holder.stagingId, CLAIM])).map(r => r.sha);+ expect(claimShas.length).toBeGreaterThan(0);+ expect(await engine.executeRaw('SELECT 1 FROM page_body_manifest WHERE staging_id IN ($1::uuid,$2::uuid)', [holder.stagingId, bystander.stagingId])).toHaveLength(0);+ const bystanderShas = await recorded(bystander.stagingId);+ const [purgedRow] = await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id=$1 AND slug=$2', ['default', purged]);+ const shared = await engine.executeRaw("SELECT DISTINCT sha256 FROM page_body_manifest WHERE page_id=$1 AND encode(sha256,'hex')=ANY($2::text[])", [purgedRow!.id, bystanderShas]);+ expect(shared.length).toBeGreaterThan(0);++ const dry = await purge.handler(ctx(engine), { id: Number(fact!.id), dry_run: true }) as Record<string, any>;+ const done = await purge.handler(ctx(engine), { id: Number(fact!.id), confirm: dry.confirm_token, expected_revision: dry.expected_revision, request_id: randomUUID() }) as Record<string, any>;+ expect(done.state).toBe('committed');+ expect(await textsLeft(claimShas)).toBe(0);+ expect(await engine.executeRaw("SELECT 1 FROM page_segment_texts WHERE position(convert_to($1::text,'UTF8') in body)>0", [CLAIM])).toHaveLength(0);+ expect(done.stores.find((s: { store: string }) => s.store === 'page_segment_texts')).toMatchObject({ status: 'deleted' });+ expect(await stagingState(holder.stagingId)).toBe('aborted');+ expect(await stagingState(bystander.stagingId)).toBe('prepared');+ expect(await textsLeft(bystanderShas)).toBe(bystanderShas.length);++ const refusal = await holder.publish().then(() => null, (e: { canonical?: string; code?: string; message?: string }) => ({ code: e.canonical ?? e.code, message: e.message }));+ expect(refusal?.code).toBe('body_staging_expired');+ expect(refusal?.message).toContain('aborted');+ expect(await engine.executeRaw('SELECT 1 FROM pages WHERE source_id=$1 AND slug=$2', ['default', `notes/holder-${tag}`])).toHaveLength(0);+ await bystander.publish();+ await expectPublished(`notes/bystander-${tag}`, bystander);+ }), 300_000);++ test('segment GC keeps a text a live staging recorded even when the text is older than the staging', async () => withEnv(env, async () => {+ const tag = randomUUID().slice(0, 8);+ const live = await inFlightCreate(`notes/gc-live-${tag}`, page('Live', filler(1_300_000, `live-${tag}`)));+ const dead = await inFlightCreate(`notes/gc-dead-${tag}`, page('Dead', filler(1_300_000, `dead-${tag}`)));+ await engine.setBodyStagingState(dead.stagingId, 'aborted');+ const liveShas = await recorded(live.stagingId), deadShas = await recorded(dead.stagingId);+ expect(liveShas.length).toBeGreaterThan(0);+ // A dedup onto an older text: the texts predate the staging and are past GC's grace.+ await engine.executeRaw("UPDATE page_segment_texts SET created_at = now() - interval '30 days' WHERE source_id='default' AND sha256=ANY(SELECT decode(h,'hex') FROM unnest($1::text[]) AS h)",+ [[...liveShas, ...deadShas]]);+ await engine.sweepSegments({ sourceId: 'default' });+ expect(await textsLeft(liveShas)).toBe(liveShas.length);+ expect(await textsLeft(deadShas.filter(sha => !liveShas.includes(sha)))).toBe(0);+ await live.publish();+ await expectPublished(`notes/gc-live-${tag}`, live);+ }), 300_000);++ test('purging an inline page is complete when a segmented page states the same claim in its prose', async () => withEnv(env, async () => {+ const tag = randomUUID().slice(0, 8);+ const inline = `notes/inline-${tag}`, other = `notes/prose-${tag}`;+ const claim = `The vault code is ${tag}`;+ await importFromContent(engine, other, page('Prose', `# Prose\n\nSomeone wrote that ${claim} in passing.\n\n${filler(1_300_000, `prose-${tag}`)}`), { sourceId: 'default', noEmbed: true });+ expect((await segmentedPageRow(engine, other)).body_storage).toBe('segmented');+ await importFromContent(engine, inline, page('Inline', `# Inline\n\n${FENCE.replace(CLAIM, claim)}\n`), { sourceId: 'default', noEmbed: true });+ const snapshot = await engine.readPageSnapshot(inline, { sourceId: 'default', includeDeleted: true });+ expect(snapshot!.page.body_storage).toBeUndefined();+ await coordinated(engine, tx => tx.executeRaw(`INSERT INTO facts(source_id,fact,entity_slug,visibility,source,source_markdown_slug,row_num)+ VALUES ('default',$1,NULL,'world','test',$2,1)`, [claim, inline]));+ const result = await operations.find(o => o.name === 'delete_page')!.handler(ctx(engine),+ { slug: inline, purge: true, request_id: randomUUID(), expected_revision: snapshot!.revision }) as Record<string, any>;+ expect(result.status).toBe('purged');+ const stores = result.receipt.stores as Array<{ store: string; status: string }>;+ expect(stores.find(s => s.store === 'page_segment_texts')).toMatchObject({ status: 'not_present' });+ expect(stores.filter(s => s.status === 'incomplete')).toEqual([]);+ expect(stores.find(s => s.store === 'source_prose')).toMatchObject({ status: 'out_of_scope', reason: 'source_prose', items: [other] });+ }), 300_000);++ test('a retained-generation rebuild refuses the live generation and leaves the live body and revision as they were', async () => withEnv(env, async () => {+ const tag = randomUUID().slice(0, 8);+ const slug = `notes/live-rebuild-${tag}`;+ await importFromContent(engine, slug, page('Live rebuild', withFence(tag, 'The live tail.')), { sourceId: 'default', noEmbed: true });+ const row = await segmentedPageRow(engine, slug);+ const before = await materializeSegmentedBody(engine, row.id, 'default');+ const [revision] = await engine.executeRaw<{ r: string }>('SELECT knowledge_revision::text AS r FROM pages WHERE id=$1', [row.id]);+ const outcome = await coordinated(engine, tx => rewriteSegmentedGeneration(tx, row.id, row.body_generation, async fence => fence.replace('Likes green tea', 'Likes black tea'),+ { title: 'Live rebuild', type: 'note', frontmatter: {}, tags: [] })).then(() => 'rewrote', (e: Error) => e.message);+ expect(outcome).toContain('is the live body');+ expect((await materializeSegmentedBody(engine, row.id, 'default')).compiled_truth).toBe(before.compiled_truth);+ expect((await engine.executeRaw<{ r: string }>('SELECT knowledge_revision::text AS r FROM pages WHERE id=$1', [row.id]))[0]!.r).toBe(revision!.r);+ expect((await segmentedPageRow(engine, slug)).body_generation).toBe(row.body_generation);+ }), 300_000);++ test('purge_fact commits when a soft-deleted segmented page states the claim in prose at the generation its version references', async () => withEnv(env, async () => {+ const tag = randomUUID().slice(0, 8);+ const prose = `notes/soft-prose-${tag}`, holder = `notes/soft-holder-${tag}`;+ const claim = `The locker code is ${tag}`;+ await importFromContent(engine, prose, page('Soft prose', `# Prose\n\nSomeone said ${claim} once.\n\n${filler(1_300_000, `soft-${tag}`)}`), { sourceId: 'default', noEmbed: true });+ await importFromContent(engine, holder, page('Holder', `# Holder\n\n${FENCE.replace(CLAIM, claim)}\n`), { sourceId: 'default', noEmbed: true });+ const [fact] = await coordinated(engine, tx => tx.executeRaw<{ id: number }>(`INSERT INTO facts(source_id,fact,entity_slug,visibility,source,source_markdown_slug,row_num)+ VALUES ('default',$1,NULL,'world','test',$2,1) RETURNING id`, [claim, holder]));+ const snapshot = await engine.readPageSnapshot(prose, { sourceId: 'default' });+ await operations.find(o => o.name === 'delete_page')!.handler(ctx(engine), { slug: prose, request_id: randomUUID(), expected_revision: snapshot!.revision });+ const row = await segmentedPageRow(engine, prose);+ expect(await engine.executeRaw('SELECT 1 FROM page_versions WHERE page_id=$1 AND body_generation=$2', [row.id, row.body_generation])).toHaveLength(1);+ const dry = await purge.handler(ctx(engine), { id: Number(fact!.id), dry_run: true }) as Record<string, any>;+ const done = await purge.handler(ctx(engine), { id: Number(fact!.id), confirm: dry.confirm_token, expected_revision: dry.expected_revision, request_id: randomUUID() }) as Record<string, any>;+ expect(done.state).toBe('committed');+ expect((await segmentedPageRow(engine, prose)).body_generation).toBe(row.body_generation);+ }), 300_000);+ });+}diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex c988f9609f..2d528f6c75 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -74,8 +74,10 @@ test/large-pages/managed-sync-segmented-rename.test.tstest/large-pages/managed-sync-streamed.test.tstest/large-pages/oversized-backfill-segmented.test.tstest/large-pages/page-purge-segments.test.ts+test/large-pages/pinned-segmented-reads.test.tstest/large-pages/projection-demotion-race.test.tstest/large-pages/projection-parity.test.ts+test/large-pages/purge-fact-inflight-staging.test.tstest/large-pages/purge-inflight-create.test.tstest/large-pages/purge-segment-residue.test.tstest/large-pages/purge-segmented-versions-batch.test.ts