Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Wave B PR 2 lane H: forget, fact purge, page purge, withdrawal discovery and credential reseal on segmented pages (spec 11)

garrytana3140831d22a
diff --git a/docs/architecture/key-files/core-persistence-continued.md b/docs/architecture/key-files/core-persistence-continued.md
index 5322f4625b..afc3702c7c 100644
--- a/docs/architecture/key-files/core-persistence-continued.md
+++ b/docs/architecture/key-files/core-persistence-continued.md
@@ -23,7 +23,7 @@ Managed connector ingestion, connector item holds and the no-op kernel (checkpoi
- `src/core/persistence/{types,params,preconditions,verb-errors}.ts` — public mutation receipt states, error reasons and revision/idempotency parameter contracts. Receipt serialization explicitly selects public fields; queued content and execution credentials stay internal. `frozenVerbWriteError` uses MEMORY_VERBS v1's existing error enum with additive `write_request`/`write_error`; `committedVerbOutcome` refuses pending or failed receipts. `OperationError` and the thin MCP client preserve this metadata, including when a timeout races an already-received receipt. The registry-safe parameter/schema leaf never imports operation values. Pinned by `test/persistence-write-contracts.test.ts`, `test/mcp-client-hardening.test.ts` and a real HTTP envelope in `test/mcp-client.test.ts`.
- `src/core/persistence/{database-write,manual-links}.ts` — `coordinatedDatabaseWrite` is the managed path for rows with no canonical file; `coordinatedManualLinkWrite` (`add_link` / `remove_link`) and `ontology_propose` (one entity page key) use it. On a managed brain it checks the caller's durable write authority for the authority page (`submissionAuthority`, then `authorizeWrite` FOR SHARE inside the transaction), revalidates the source incarnation and commits inside `withCoordinatedWrite` holding the given page keys (both link endpoints). Unmanaged brains keep the engine calls. Manual edges (`link_source` `manual` or a custom tag) survive re-derivation and republication because automatic reconciliation only replaces derived provenances. Tests: `test/managed-writers-w3.test.ts`, `test/managed-ontology-propose.test.ts`.
- `src/core/persistence/{attribution,attribution-schema,context}.ts` — write attribution. `withCoordinatedWrite(engine, sourceIds, fn, attribution)` sets `gbrain.write_sources` and the transaction-local actor (`gbrain.write_request`, `gbrain.write_principal_kind`, `gbrain.write_principal_id`) in one round trip and restores them on exit; a nested scope keeps the outer actor. The argument is required: `requestAttribution(row)` for journaled publication (coordinator, forget), `maintenanceAttribution(engine)` (verified local writer, else the CLI registration, else `application`/`host:<id>`; no request) for derived facts, takes/timeline/link extraction, materialization, concept provenance, connector freshness and verify cleanup, `principalAttribution` for manual links (the caller) and source lifecycle (the topology principal). `withWriteAttribution` sets only the actor, for unmanaged legacy transactions; `maintenanceTransaction(engine, fn)` wraps it in one transaction, and every unmanaged direct writer runs its write (or one bounded batch) in it (the `system-of-record.md` "unattributed" list is empty; derivers pass their taint as `maintenanceTransaction(engine, fn, trust)`, see `trust/taint.ts`). `attribution-schema.ts` (migration `f1_write_attribution`; migration-only like the facts DDL, so columns land last on fresh and upgraded brains) adds nullable columns and BEFORE ROW triggers: `facts`/`takes`/`timeline_entries` carry `write_*` (created_by, immutable once set) and `last_write_*` + `last_written_at` (moved only when a classified content column changes; a NULL actor records an unattributed writer); `pages.revision_*` is stamped when `knowledge_revision` changes; `page_versions.write_*` copies the snapshotted revision's actor and `archived_*` names the archiving write. `write_request_id` is `persistence_requests.id` with no foreign key; all-NULL reads as unrecorded. Every column of the three tables is classified content, projection (embeddings, `takes.updated_at`) or attribution, and a new column must be classified and the function re-created; the writer guard treats attribution-only facts/takes updates as projections. Tests: `test/write-attribution.test.ts`, `test/write-attribution-legacy.test.ts` (writer inventory) and `test/write-attribution-<family>.test.ts` (each routed unmanaged writer path; `write-attribution-timeline-10k.slow.test.ts` checks bounded batches at 10k pages) on PGLite; Postgres direct and PgBouncer through `test/e2e/write-attribution-postgres.test.ts`.
-- `src/core/persistence/purge-deleted.ts` — `purgeDeletedPagesCoordinated` backs the cycle `purge` phase, the purge job, `purge_deleted_pages` and `gbrain pages purge-deleted`. Unmanaged brains keep the engine bulk delete; a managed brain purges each tombstone older than the window (skipping archived sources, which the source lifecycle purges) through `delete_page` with `purge: true` bound to its revision. Revision races are deferred to the next run; any other failure is listed in `blocked` and sets `error`, which fails the purge phase. Tests: `test/managed-writers-w3.test.ts`.
+- `src/core/persistence/purge-deleted.ts` — `purgeDeletedPagesCoordinated` backs the cycle `purge` phase, the purge job, `purge_deleted_pages` and `gbrain pages purge-deleted`. Unmanaged brains keep the engine bulk delete; a managed brain purges each tombstone older than the window (skipping archived sources, which the source lifecycle purges) through `delete_page` with `purge: true` bound to its revision. Revision races are deferred to the next run; any other failure is listed in `blocked` and sets `error`, which fails the purge phase. Tests: `test/managed-writers-w3.test.ts`. The engine bulk delete (`engine-sql/pages.ts` `purgeDeletedPages`) also deletes, in its transaction, the purged pages' stagings (by source and slug) and the segment texts only their manifests referenced.
- `src/core/persistence/loop-fact-retirement.ts` — #5869 commitment-fact retirement for closed loops, one coordinator mutation on every brain (operation `loops_close`, intent `retire_loop_fact`, dispatched from `service.ts`): expires the fact and strikes its `## Facts` fence row (context `loop closed: <status>`) through the entity page publication in one transaction; no withdrawal tombstone. The shared rule (also `loopFactDrift`, used by doctor `loop_facts_drift` and `gbrain repair loop-facts`): only a fact in the loop's source that no other open loop references, re-checked under row locks at publication (`shared_with_open_loop`, `source_mismatch` otherwise). `retireLoopFact(ctx, loopId)` submits with the caller's grant and maps a refusal or pending write to `fact_expired: false, retryable: true, reason`. Tests: `test/loops-close-fact.serial.test.ts` (+ Postgres twin).
- `src/core/persistence/connector-authority.ts` -- classifies each Google/GitHub source as `connector_database` (managed, unbound), `bound` or `unmanaged` from `persistence_brain.enabled` and the source binding row. File-lane audits (doctor `undeclared_db_only_pages`, backup coverage) read it so a leftover cache directory at `local_path` is never taken for canonical files. Tests: `test/doctor-silent-death-checks.test.ts`, `test/backup-coverage.serial.test.ts`.
- `src/core/persistence/connector-sync.ts` — managed Google/GitHub API ingestion through source-scoped journaled `connector_v2_import`/`_delete`/`_checkpoint`/`_google_receipts` intents and `managed-connector` checkpoint CAS, not Git cursors. The checkpoint key, admission `configHash`, mid-sweep change check and publication `source_changed` check all use the parsed-config identity from `connector-identity.ts`, so cycle stamps in `sources.config` never rotate them. Unbound connectors use reviewed `connector_database` SQL-only authority; bound connectors retain canonical file publication with guarded root/hash/revision/epoch. Every managed run checks the credential's resolved account against the pin in the connector state row before reading its checkpoint (`assertAccount`), then applies a requested `--reset-checkpoint` (pending writes resolved first, pin kept). Each import or delete is first screened by running `prepareConnectorMutation` on an unadmitted request through the no-op kernel; unchanged items take no admission. An unchanged checkpoint save is skipped and, when it would have stamped freshness, `last_sync_at` is stamped directly inside a lease-asserted coordinated write. Accepted-pending writes are progress: a 30-second total wait budget (writes committing within one second are free), at most one in-flight write per page, outstanding writes kept under the principal's outstanding and intent-byte limits, and `ConnectorWaitBudgetStop` (a `write_pending` error) when the budget is spent. The checkpoint never advances past a pending page; the run records its pending set in the state row, and the next run resolves it first (committed dropped, failed retried automatically through the retry-pointer path without `--retry-failed`, unreached failures after a complete sweep dropped and counted). Retired `managed_connector_*` intents route to `prepareOutdatedConnectorMutation`, which fails them `connector_intent_outdated` (detail `pre_upgrade` before the v176 cutoff). Standalone entry, page reads and submissions authenticate the current source, local grant and canonical owner and settle retained worktree publications before deriving request identity. Explicit `--retry-failed` atomically admits a linked attempt and stores a per-base-request `managed-connector-retry` pointer. Durable connector cursors, retry pointers and state rows survive generic seven-day checkpoint GC. Tests: `test/persistence-connectors.test.ts`, `test/persistence-connector-retry.test.ts`, `test/connector-checkpoint-identity.test.ts`, `test/connector-wave3.test.ts` and `test/helpers/connector-restart.ts` on PGLite and disposable Postgres.
diff --git a/docs/architecture/key-files/core-services-2-continued.md b/docs/architecture/key-files/core-services-2-continued.md
index f27ebadcc7..6bc8b97c5f 100644
--- a/docs/architecture/key-files/core-services-2-continued.md
+++ b/docs/architecture/key-files/core-services-2-continued.md
@@ -7,7 +7,7 @@ The page-state concurrency foundation under `src/core/page-state/` and the share
- `src/core/page-state/` — Canonical page concurrency foundation shared by both engines. `schema.ts` (migration 150) adds source incarnation UUIDs, logical page revisions, text-projection revisions, and persistent guards for absent pages. `guards.ts` locks sorted sources then page identities in an existing transaction; a transaction or savepoint never re-acquires a key it holds, which covers absent pages because the only pages INSERT runs after `putPage` takes the same guard (`test/e2e/page-guards-postgres.test.ts`); callers lock sources before authority/request/fact rows. `snapshot.ts` computes the normalized body/timeline fingerprints only for a page with fact withdrawals, page-subject purges or a source '*' purge marker (they feed only the withdrawal overlay), as `page-snapshot-batch.ts` does. `snapshot.ts` reads page/tags/withdrawals in one MVCC statement and applies withdrawals using database-normalized text. `transactions.ts` makes helper transaction APIs compose through savepoints. `versions.ts` records the complete canonical snapshot; `rename-alias.ts` records `slug_aliases(old -> new)` inside both engines' `updateSlug` transaction, repoints aliases that named the old slug and drops one spelled like the new slug; `moveSlugBindings` moves the page's facts (`entity_slug`, `source_markdown_slug`) and `page_aliases` in the same transaction, letting a purged page's leftovers at the new slug yield (`test/rename-slug-alias.test.ts`); `movePageIdReferences` (#5431) moves the page-id-keyed rows of a stale rename row onto the surviving row (`links` from/to/origin, `timeline_entries` page and event, `page_versions`), dropping stale-side duplicates on the `links` composite key and the timeline dedup indexes (`test/rename-slug-alias.test.ts`); `materialize.ts` persists only verified canonical overlay bytes without another logical revision. `types.ts` defines revision preconditions: no revision is create-only (an existing page refuses `revision_required`, #5385, its own code since the omission is the caller's and not a race), a stale revision or a page another writer created where an internal writer asserted none (`expectedRevision: null`) is `revision_conflict`, explicit force overwrites. Plain legacy `putPage` calls keep compatibility until their owning operation adopts the managed write protocol. `projection-schema.ts` (migration 153) invalidates unverified prior projections once and queues durable work; `projections.ts` rebuilds Markdown without a worktree/provider and installs only matching canonical revisions. Embedding installs also compare exact chunk identities/text. Source importers seal code/image projections; all read arms hide unsealed projections.
- `src/core/page-state/projections.ts` — `sealPageTextProjection` and `sealImportedPage` write the page keyword vector through `pageSearchVectorSql` (`fts-language.ts`: title weight A, sanitized timeline weight C, both through `gbrain_fts_input`), the same expression `search-vector-backfill.ts` uses. Captures canonical revision, source incarnation, page identity, the complete raw chunk inventory and resolved indexing inputs before preparing derived work. Embedding reads require a current text seal; healing/rebuild capture can explicitly include unsealed pages. Projection installation compares its originating seal, chunk identities/text/source/completion state, chunker version and indexing context (including stored corpus generation) under the page guard before replacing any row. A same-revision re-chunk may replace the snapshot it actually captured; a delayed older installation cannot discard newer chunks or vectors. Rebuild also rechecks its queued job before capture so a completed job from an old listing stays completed. Chunkless healing sanitizes complete body/timeline fences before splitting, preserving withdrawn history in direct page reads while excluding it from retrieval. Tests: `page-projection-origin.test.ts`, `page-projection-vector-preservation.test.ts` (PGLite and isolated Postgres), `embed-stale-chunkless-pages.serial.test.ts` (public healing entry). Shared `markdown-chunks.ts` and `code-chunks.ts` preserve fenced code and source-language metadata. A preserving rebuild keeps a vector only when its `content_chunks.embedding_input_hash` (`src/core/embedding-input-hash.ts`) equals one recomputed from the current page, or, with no recorded hash, when the page is non-contextual and the legacy model/text-hash checks pass; a contextual chunk without provenance is nulled once. `installPageEmbeddings` records the hash in the vector's UPDATE (the plain re-embed tier by default, or the caller's `built` tier and corpus generation), and returns `{ installed, complete }`: it matches each offered vector to the page's current chunk by source and exact text (not index) and writes it only when its input hash for the captured context is one the current context accepts, in batched `jsonb_to_recordset` UPDATEs, so a page that changed under the provider call keeps the vectors of its unchanged chunks; the embedding signature is stamped only when `complete` (same chunk sequence, nothing dropped). A preserving rebuild likewise keys kept vectors by chunk content, so a top insert shifts vectors with their chunks (tests: `page-embedding-content-validity.test.ts`). Also `stampEmbeddingInputs` does the same for full imports. `resealSafeChunks` re-seals a page below the safe-chunk fence from its unchanged body with no canonical write; `projectionBelowSafeFence` is its predicate. Tests add `projection-embedding-input-hash.test.ts` and `safe-chunk-reseal.test.ts`. It replaces outgoing code edges without deleting incoming edges to retained chunks and clears backfill watermarks. Failed jobs rotate with a retained diagnostic; successful drain refreshes planner statistics. `rebuildPendingPageProjections(engine, limit, { deadlineMs, now, notAfter, retryCooldown, onFailure })` (#5401) checks an injectable clock between pages, bounds a run to rows queued at or before its start (`notAfter`, cast from text in SQL so microseconds survive the driver), applies the 30 s `rebuild_failed` cooldown for the resident, and treats a lock or snapshot error as that page's failure instead of aborting the batch; `projectionBacklog` returns counts only (pending, failed, oldest age) for the drain command and the resident's `projection_status` IPC reply. A same-revision conflict throws `PageProjectionConflictError` naming the fields that changed (`text_projection_revision`, `chunk_digest`, `indexing_context`), the slug and source; `retryProjectionConflict(attempt)` re-runs an attempt that captures a fresh snapshot at most three more times with jitter, then rethrows (`page_projection_conflict` on the wire). Tests: `page-projection-origin.test.ts` (resident rebuild race, two-writer progress, exhausted-retry CLI/JSON output).
-- `src/core/page-state/credential-reseal.ts` + `src/core/schema-migrations/v189-pages-credential-projection-pending.ts` + `src/commands/doctor/checks/credential-projection.ts` — the targeted re-chunk of pages indexed before the credential-safe projection. Schema migration v187 (on the first connect after upgrade) sets `text_projection_revision = NULL` on every live markdown/code page whose `compiled_truth` or `timeline` matches `-----(BEGIN|END) [A-Z ]*PRIVATE KEY-----` and upserts a `page_projection_jobs` row (reason `credential_projection`), so the current-text-projection seal withholds their old chunks from every retrieval path, local and remote (code-walk `hydrateChunks` in `search/two-pass.ts` applies the same filter). The marker literal is frozen as shipped. `credentialProjectionPending(engine, sourceIds?)` counts pending pages in active sources as `rebuildable` and `kept` (code pages with no `frontmatter.file` or `source_path`, which wait for their importer). `resealCredentialProjections` re-seals each rebuildable page from its unchanged body through `resealSafeChunks` (the `repair safe-chunks` installer), one page per transaction, with no page write, journal admission or provider call; vectors of unchanged chunk text are kept and re-chunked key chunks wait for `gbrain embed --stale`; a revision conflict counts as superseded, a failure prints the retry command and leaves the page withheld. The doctor check `credential_projection_pending` (a `WAVE_CHECKS` entry, `resolution: 'operator'`, brain category) reports `pages_pending` and `kept_pages` and warns while either is non-zero, naming `gbrain apply-migrations --yes --no-autopilot-install` (no provider calls), then `gbrain embed --stale`, and the re-import for kept code pages; a read error is `warn` with unknown health.
+- `src/core/page-state/credential-reseal.ts` + `src/core/schema-migrations/v189-pages-credential-projection-pending.ts` + `src/commands/doctor/checks/credential-projection.ts` — the targeted re-chunk of pages indexed before the credential-safe projection. Schema migration v187 (on the first connect after upgrade) sets `text_projection_revision = NULL` on every live markdown/code page whose `compiled_truth` or `timeline` matches `-----(BEGIN|END) [A-Z ]*PRIVATE KEY-----` and upserts a `page_projection_jobs` row (reason `credential_projection`), so the current-text-projection seal withholds their old chunks from every retrieval path, local and remote (code-walk `hydrateChunks` in `search/two-pass.ts` applies the same filter). The marker literal is frozen as shipped. `credentialProjectionPending(engine, sourceIds?)` counts pending pages in active sources as `rebuildable` and `kept` (code pages with no `frontmatter.file` or `source_path`, which wait for their importer). `resealCredentialProjections` re-seals each rebuildable page from its unchanged body through `resealSafeChunks` (the `repair safe-chunks` installer), one page per transaction, with no page write, journal admission or provider call; vectors of unchanged chunk text are kept and re-chunked key chunks wait for `gbrain embed --stale`; a revision conflict counts as superseded, a failure prints the retry command and leaves the page withheld. The doctor check `credential_projection_pending` (a `WAVE_CHECKS` entry, `resolution: 'operator'`, brain category) reports `pages_pending` and `kept_pages` and warns while either is non-zero, naming `gbrain apply-migrations --yes --no-autopilot-install` (no provider calls), then `gbrain embed --stale`, and the re-import for kept code pages; a read error is `warn` with unknown health. A segmented page is pending when a live manifest row stores a `pem` region; it is re-sealed through `buildSegmentedProjection`.
Embedding-only publication also requires a live, unarchived source and nondeleted page under the same source/page row locks. A prepared vector cannot bypass a later archive, model change or withdrawal. `test/e2e/migration-wave-prepared-withdrawal.test.ts` exercises both publication orders and exact unchanged-vector refusal on both engines.
@@ -17,3 +17,4 @@ The page-state concurrency foundation under `src/core/page-state/` and the share
- `src/core/progressive-batch/` — shared ramp-up + cost-cap + verification primitive (trial 10 → ramp 100 → ramp 500 → full, with verification at each stage), with verifier+policy injection (callers describe HOW TO MEASURE SUCCESS, not WHEN TO WAIT FOR CTRL-C). Modules: `types.ts` (Stage, StageVerdict, AbortReason, discriminated `Verifier` union `OutputCountVerifier | IdempotentMutationVerifier | NoopVerifier`, Policy, StageReport), `orchestrator.ts` (`runProgressiveBatch(items, verifier, policy, runner)` — reads `getCurrentBudgetTracker()` ahead of `Policy.maxCostUsd` fail-closed; null both ways triggers `abort_cost_cap reason='no_budget_safety_net'`), `audit.ts` (ISO-week JSONL at `~/.gbrain/audit/progressive-batch-YYYY-Www.jsonl` via the shared `audit-writer` primitive), `stage-report.ts` (ASCII formatter for the default `Policy.onStageReport`). Env knobs: `GBRAIN_PROGRESSIVE_BATCH_DISABLED=1`, `GBRAIN_PROGRESSIVE_BATCH_AUTO=1` (skip Ctrl-C grace), `GBRAIN_PROGRESSIVE_BATCH_STAGES=10,100,500`. Sites that "jump straight to full" stay that way by default; ramp is opt-in per-site via `Policy.interactiveAbortMs > 0`. Pinned by `test/progressive-batch/orchestrator.test.ts` (35 cases, every verdict path).
- `src/core/page-body/page-shape.ts` — Wave B PR 1 (spec 1.5): segmented page bodies are unreachable as strings. `guardSegmentedBody` (called by `rowToPage` for a row with `body_storage = 'segmented'`, so by every snapshot and `getPage` read) replaces `compiled_truth` / `timeline` with enumerable getters and setters that throw `page_body_segmented`, so property reads, spread, `JSON.stringify`, `structuredClone` and assignment all fail loud instead of seeing an empty body. `isSegmentedPage`, `assertInlineBody(page, site)` (explicit refusal where a writer would otherwise act before a getter fires, e.g. SQL-only writers), `pageBodyBytes(page)` (`body_bytes` for segmented pages) and `pageBodySegmentedError`. `bodyUnread(page)` says a segmented page's body was not read back as strings (over the single-string ceiling, see `materializedPage`); such a body was written by the streamed import, which holds fenced files, so `fenceBody(page)` reads it as empty for the fence merges and `withoutBody(page)` copies the page's other fields for a render whose body comes from the incoming write (a shrunk file rewrites such a page: `test/large-pages/segmented-shrink-below-ceiling.test.ts`). `Page` stays one shape (`body_storage?`, `body_bytes?`); the static half is `scripts/check-page-body-readers.ts` with `scripts/page-body-readers-baseline.tsv` (docs/TESTING.md#page-body-readers). Pinned by `test/large-pages/segmented-body-unreachable.test.ts`.
+- `src/core/page-body/segment-rewrite.ts` — fence rewrites of a segmented body without holding it as one string (forget strikes, purge drops). Only stored `facts`/`takes` protected regions are decoded and passed to a `FenceTransform` (a region crossing forced cuts is joined with its neighbours, refused above `PAGE_MAX_BYTES`). `rewriteLiveSegmentedFences` re-stages the live body through `prepareSegmentedBody` from the segment stream with the changed units replaced and flips it in the caller's transaction (trust tier and soft delete kept; null when nothing changed); `rewriteSegmentedGeneration` rebuilds one retained generation under its own number and updates its versions' hash and size; `rewrittenContentHash` streams the hash of a rewritten generation; `segmentedBodyContains` searches a body segment by segment with the previous segment's tail carried over. Tests: `test/large-pages/purge-segments.test.ts`, `forget-scope.test.ts`, `page-purge-segments.test.ts`.
diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.md
index 4582fccc17..5f02c5d3ec 100644
--- a/docs/architecture/key-files/core-services-2.md
+++ b/docs/architecture/key-files/core-services-2.md
@@ -12,13 +12,13 @@ Fact and page purge modules (`src/core/facts/purge*.ts`, `deletion-inventory.ts`
- `src/core/facts/extract.ts` — the LLM facts extractor (`extractFactsFromTurnWithOutcome` and friends; the output cap, truncation retry, and salvage behavior are described under the trajectory entry). Model: `resolveFactsExtractionModel(engine)` returns the model and the setting that chose it (`facts.extraction_model`, then the `resolveModelDetailed` chain on the `reasoning` tier); when nothing chose one and the tier's key-aware default resolved through Anthropic, `FACTS_EXTRACTION_MEASURED_DEFAULTS` substitutes `anthropic:claude-haiku-5-5` (source `measured_default`; the facts-absorb quality gate, gbrain-evals `docs/benchmarks/2026-10-08-facts-extraction-model.md`), and `gbrain models` reports that row through the same resolver. `getFactsExtractionModel` is its string wrapper. Deterministic junk gate: `isJunkFact(text, kind?)` tests `JUNK_FACT_PATTERNS` — assistant plan/offer narration, meta-narration about the conversation itself, provider billing/rate-limit strings captured verbatim — and is kind-aware: a candidate the extractor classified `commitment` is exempt from the plan-narration arm ONLY ("I'll send the deck by Friday" is a genuine commitment); meta-narration and provider-error strings are junk for every kind. `isJunkFilterEnabled(engine)` is the config kill switch (fail-open on a config read error); `getFactsExtractionPromptAppendix` supplies the config-driven prompt appendix. Entity gate at the candidate loop (the ONE seam where LLM-emitted entity tokens become `entity_slug`): `isUnknownSpeakerLabel` (anonymous diarizer labels — `Speaker A`, `SPEAKER_00`, `spk_0`, `other|unknown|guest`) and `isNullLikeEntity` (placeholder STRINGS `"null"`/`"None"`/`"n/a"` where the prompt asked for JSON null; shared with `write-single.ts`) both null the attribution and KEEP the fact, so no consumer can mint `entity_slug='null'` through the resolver's fallback slugify. The provider-error arm is start-anchored (`^\W*`, optional error/status token or a `<step> stopped|failed because …` prefix, then `(spend|rate) (limit|cap) … (hit|exceeded|reached)`), so a genuine fact that merely mentions a spend limit or rate limit mid-sentence survives; the verbatim provider strings still match. Two config keys: `facts.extraction_prompt_appendix` (non-empty text is appended to the extraction prompt) and `facts.extraction_junk_filter` (`false` disables the deterministic junk gate; default on), plus the opt-in `facts.extraction_missing_confidence` (stored when confidence is missing, null or non-numeric; unset keeps 1.0). A numeric-string confidence (`"0.3"`) is read as the stated value; unknown kinds are still stored as `fact` but counted in a stderr warning. Every extractor `chat()` call (first attempt, the #2113 truncation retry, the malformed-output retry) carries `responseSchema: FACTS_EXTRACTION_SCHEMA` (mirrors `RawExtracted`: `facts[]` of `{fact, kind ∈ ALL_EXTRACT_KINDS}` plus `entity/confidence/notability/metric/value/unit/period` — EVERY property in `required`, the optional ones nullable via type unions, `additionalProperties: false` at both levels, so the schema is OpenAI-strict-safe for proxies that honor the SDK's default `strict: true`); the gateway honors it only on openai-compatible recipes that declare structured outputs (Ollama's server-side grammar), so small local models cannot emit malformed JSON, while `parseExtractorJsonDetailed` still validates the reply text on every lane. The typed-claim examples keep a bare `$` as USD (series compare by `(metric, unit, period)`, so nulling it would split them) and, since wave 15 (PR #6274 by @jordanschwartz-js), show two explicit non-USD examples (EUR, CAD) with the rule to preserve a stated currency as the unit and never convert; pinned by `test/facts-extract-currency-examples-6274.test.ts`. Pinned by `test/facts-extract-structured-output.test.ts`.
-- `src/core/facts/forget.ts` — `forgetFactInFence(engine, id, {reason?, sourceId?, worldOnly?, supersededBy?})` checks source and visibility before inspecting state, then commits a durable withdrawal through `facts/withdrawal.ts`. With `supersededBy: { rowNum }` (the `writeSingleFact` supersession path) it only expires the row and strikes it with a page-local `#N` supersession reference: no withdrawal, so the old claim stays rememberable and no other page is invalidated. A writable source fence is atomically struck with a date and reason; otherwise the DB-body mirror is best-effort. Both paths remain withdrawn on stale reimport while the withdrawal database is preserved. The file resolver and per-page lock match fence writes. The body-only mirror deliberately leaves a hash mismatch so the next import re-chunks. Forget is retraction, not deletion of original prose, files or backups. `strikeFenceRow` and `supersededFact` are exported for the S9 checked supersede (`facts/proposal-supersede.ts`). `strikeFenceRow` returns null for a fence that parses with warnings (#6385 R12), so forget falls back to the DB-only expire and the file keeps the rows the parser could not read. Pinned by `test/forget-reconcile-durability.test.ts`, `test/privacy-strip-and-forget.test.ts`, and `test/e2e/delegated-grants-withdrawal.test.ts`.
+- `src/core/facts/forget.ts` — `forgetFactInFence(engine, id, {reason?, sourceId?, worldOnly?, supersededBy?})` checks source and visibility before inspecting state, then commits a durable withdrawal through `facts/withdrawal.ts`. With `supersededBy: { rowNum }` (the `writeSingleFact` supersession path) it only expires the row and strikes it with a page-local `#N` supersession reference: no withdrawal, so the old claim stays rememberable and no other page is invalidated. A writable source fence is atomically struck with a date and reason; otherwise the DB-body mirror is best-effort. Both paths remain withdrawn on stale reimport while the withdrawal database is preserved. The file resolver and per-page lock match fence writes. The body-only mirror deliberately leaves a hash mismatch so the next import re-chunks. Forget is retraction, not deletion of original prose, files or backups. `strikeFenceRow` and `supersededFact` are exported for the S9 checked supersede (`facts/proposal-supersede.ts`). `strikeFenceRow` returns null for a fence that parses with warnings (#6385 R12), so forget falls back to the DB-only expire and the file keeps the rows the parser could not read. Pinned by `test/forget-reconcile-durability.test.ts`, `test/privacy-strip-and-forget.test.ts`, and `test/e2e/delegated-grants-withdrawal.test.ts`. A segmented page's row is struck in the segment holding its fence (`rewriteLiveSegmentedFences`, first fence holding the row), on the DB-only and the file-mirror paths.
- `src/core/facts/phantom-audit.ts` — JSONL audit at `${resolveAuditDir()}/phantoms-YYYY-Www.jsonl`. Pattern copy of `src/core/audit-slug-fallback.ts` (ISO-week rotation, honors `GBRAIN_AUDIT_DIR`). Exports `logPhantomEvent(record)` + `readRecentPhantomEvents(days)` + `computePhantomAuditFilename(now?)`. Records every outcome: `redirected | ambiguous | drift | no_canonical | not_phantom_has_residue | pass_skipped_lock_busy`. Best-effort writes — stderr warn on failure, never throws. Separate file from `stub-guard-audit.ts` (distinct consumer + lifecycle: stub-guard logs PREVENTIVE blocks; phantom-audit logs CLEANUP decisions, to be read by a future `phantoms_pending` doctor check).
- `src/core/facts/queue.ts:FactsQueue.drainPending` — method `drainPending({timeout?: number}): Promise<{drained, unfinished}>`. Semantically distinct from `shutdown()` (which calls `this.internalAbort.abort()` and would abort the very facts:absorb worker trying to log its post-completion event). Drain lets in-flight finish; only the wait is bounded. Default timeout `1000ms` so commands that don't enqueue facts pay one fast 0ms check before exit. `src/cli.ts` op-dispatch finally block awaits `getFactsQueue().drainPending({timeout: 1000})` BEFORE `engine.disconnect()`. Lazy-import keeps the facts-queue module off the hot path for ops that never touch it. Prevents a trailing `'No database connection'` line after `gbrain capture` (a post-page-write facts:absorb outliving the CLI process). Pinned by `test/facts-queue-drain-pending.test.ts` (4 cases: empty fast-path, in-flight settled without abort, unfinished count on timeout, default timeout = 1000ms).
-- `src/core/facts/withdrawal.ts` + `withdrawal-schema.ts` + `withdrawal-discovery.ts` — durable withdrawal key is `(source_id, visibility, subject, SHA256(normalized claim))`. `subject` is the forgotten row's `entity_slug`; '*' (all subjects) covers subjectless facts and rows recorded before v169. A withdrawal matches when `subject = '*' OR subject = entity_slug`, so forgetting one entity's claim never touches the same claim about another entity. Fence rows belong to their page's entity: the import overlay, prepared-import check (`preserveWithdrawnFenceRows` / `assertPreparedFactWithdrawals`), snapshot overlay and Markdown export match on the page slug. `updateSlug` (both engines, via `moveSlugBindings`) and the phantom-redirect merge move subjects to the new slug (`MOVE_WITHDRAWAL_SUBJECT_SQL`), so rename and index recreation do not restore a claim. Normalization (`gbrain_fact_normalize`, mirrored in JS by `normalizeLoweredClaim`) folds case, whitespace and an explicit punctuation set, not meaning (migration v174); `+`, `#` and in-word dots are kept ("C++" ≠ "C"); pre-v174 ledger rows keep their exact `gbrain_fact_fingerprint_v1` hash and every ledger match checks both. v174 adds a folded row wherever a fact row still holds the claim text, expires facts that became matching, and builds `idx_facts_withdrawal_fingerprint` (the fingerprint inlines normalization: index builds use a restricted search_path). Discovery (`withdrawal-discovery.ts`) is keyed on claim, subject and fingerprint: SQL shortlists pages and chunks whose lowercased text contains every normalized token of the claim (one `lower(text) LIKE ALL(patterns)` fold per text with `%`, `_` and `\` escaped, #6270; necessary for any match; nothing is normalized in SQL), streams them by keyset, then verifies exactly; a subject-scoped claim reads only its entity's page plus provenance of that entity's facts. There is no source-inventory limit (#5674): refusals come from the matched set (>256 pages, reported with the count and sample slugs), the 10s scan budget, per-batch input limits or matching malformed evidence. Only an existing withdrawal covering the same subject skips discovery. Only affected page revisions/chunks are invalidated. The source row lock serializes withdrawal with the facts trigger; the trigger prevents insert/update from reactivating a matching claim. Import and snapshot overlays cover every complete legacy fence, including inactive rows; withdrawal markers precede preserved context and retain earlier expiry dates before hashing/chunking; malformed fences retain their existing diagnostics and the DB trigger still protects derived facts. `writeSingleFact` refuses an identical withdrawn claim for the resolved entity before embedding, using the protocol error envelope. `writeFactsToFence` rechecks each input under the page lock and drops claims withdrawn for the page's entity (reporting `withdrawnSkipped`), and the backstop skips them in phase 1, so a withdrawn claim is never appended to Markdown as an active row (audit B-10). TTL/supersession expiry creates no withdrawal; backfill trusts only explicit `forgotten:` markers; Markdown-only copies do not preserve DB-only withdrawals. Pinned by `test/facts-withdrawal-subject.test.ts`, `test/fact-withdrawal-normalized.test.ts`, `test/withdrawal-bounded-safety.test.ts` (both engines) and the Postgres scale gate `test/e2e/fact-withdrawal-scope-postgres.test.ts`. `recordFactWithdrawal(…, { semanticReview })` also queues a `withdraw` review row in `decide_review_queue` inside the same transaction when `decide.slots.conflict.review_withdraw` is on (unset counts as on; `reviewWithdrawOn`) and the caller did not opt out, and runs every `registerWithdrawalInvalidation` hook in that transaction for projections beyond pages and chunks. `src/core/facts/similar-active.ts` — `similarActiveAfterForget`: after a committed `forget`, up to five active facts with the same source, entity and visibility (world only for remote callers) at cosine >= 0.80 to the withdrawn fact's stored embedding, returned as ids and scores with the overnight review state and a `next` line (zero model calls; pinned by `test/decide/review-withdraw.serial.test.ts`).
+- `src/core/facts/withdrawal.ts` + `withdrawal-schema.ts` + `withdrawal-discovery.ts` — durable withdrawal key is `(source_id, visibility, subject, SHA256(normalized claim))`. `subject` is the forgotten row's `entity_slug`; '*' (all subjects) covers subjectless facts and rows recorded before v169. A withdrawal matches when `subject = '*' OR subject = entity_slug`, so forgetting one entity's claim never touches the same claim about another entity. Fence rows belong to their page's entity: the import overlay, prepared-import check (`preserveWithdrawnFenceRows` / `assertPreparedFactWithdrawals`), snapshot overlay and Markdown export match on the page slug. `updateSlug` (both engines, via `moveSlugBindings`) and the phantom-redirect merge move subjects to the new slug (`MOVE_WITHDRAWAL_SUBJECT_SQL`), so rename and index recreation do not restore a claim. Normalization (`gbrain_fact_normalize`, mirrored in JS by `normalizeLoweredClaim`) folds case, whitespace and an explicit punctuation set, not meaning (migration v174); `+`, `#` and in-word dots are kept ("C++" ≠ "C"); pre-v174 ledger rows keep their exact `gbrain_fact_fingerprint_v1` hash and every ledger match checks both. v174 adds a folded row wherever a fact row still holds the claim text, expires facts that became matching, and builds `idx_facts_withdrawal_fingerprint` (the fingerprint inlines normalization: index builds use a restricted search_path). Discovery (`withdrawal-discovery.ts`) is keyed on claim, subject and fingerprint: SQL shortlists pages and chunks whose lowercased text contains every normalized token of the claim (one `lower(text) LIKE ALL(patterns)` fold per text with `%`, `_` and `\` escaped, #6270; necessary for any match; nothing is normalized in SQL), streams them by keyset, then verifies exactly; a subject-scoped claim reads only its entity's page plus provenance of that entity's facts. There is no source-inventory limit (#5674): refusals come from the matched set (>256 pages, reported with the count and sample slugs), the 10s scan budget, per-batch input limits or matching malformed evidence. Only an existing withdrawal covering the same subject skips discovery. Only affected page revisions/chunks are invalidated. The source row lock serializes withdrawal with the facts trigger; the trigger prevents insert/update from reactivating a matching claim. Import and snapshot overlays cover every complete legacy fence, including inactive rows; withdrawal markers precede preserved context and retain earlier expiry dates before hashing/chunking; malformed fences retain their existing diagnostics and the DB trigger still protects derived facts. `writeSingleFact` refuses an identical withdrawn claim for the resolved entity before embedding, using the protocol error envelope. `writeFactsToFence` rechecks each input under the page lock and drops claims withdrawn for the page's entity (reporting `withdrawnSkipped`), and the backstop skips them in phase 1, so a withdrawn claim is never appended to Markdown as an active row (audit B-10). TTL/supersession expiry creates no withdrawal; backfill trusts only explicit `forgotten:` markers; Markdown-only copies do not preserve DB-only withdrawals. Pinned by `test/facts-withdrawal-subject.test.ts`, `test/fact-withdrawal-normalized.test.ts`, `test/withdrawal-bounded-safety.test.ts` (both engines) and the Postgres scale gate `test/e2e/fact-withdrawal-scope-postgres.test.ts`. `recordFactWithdrawal(…, { semanticReview })` also queues a `withdraw` review row in `decide_review_queue` inside the same transaction when `decide.slots.conflict.review_withdraw` is on (unset counts as on; `reviewWithdrawOn`) and the caller did not opt out, and runs every `registerWithdrawalInvalidation` hook in that transaction for projections beyond pages and chunks. `src/core/facts/similar-active.ts` — `similarActiveAfterForget`: after a committed `forget`, up to five active facts with the same source, entity and visibility (world only for remote callers) at cosine >= 0.80 to the withdrawn fact's stored embedding, returned as ids and scores with the overnight review state and a `next` line (zero model calls; pinned by `test/decide/review-withdraw.serial.test.ts`). Segmented affected pages are struck segment by segment through `rewriteLiveSegmentedFences` (a new generation whose flip replaces only the rewritten occurrences' chunks); discovery also scans live manifest rows with `facts_slots`, reading only each slot's bytes (a slot split by a forced cut is left to the chunk scan).
- `src/core/facts/write-single.ts` — `writeSingleFact(fact, ctx)`: the zero-LLM single-fact seam behind `remember`. `runFactsPipeline` is extraction-first (LLM-gated) and cannot back a pre-formed fact; this reuses the pipeline's post-extraction stages directly: resolve → embedding-cosine dedup (per-model threshold) → fence-first write with the same legacy DB-only fallbacks (thin-client, unparented, stub-guard). Supersession: deterministic rule — same entity_slug + same kind + similarity ≥ threshold + DIFFERENT text ⇒ the new fact supersedes (fence path: append new + `forgetFactInFence(old, { supersededBy })`, which strikes the old row with a page-local `#N` supersession reference and records no withdrawal, + superseded_by link; DB path: engine insertFact supersedeId). Pinned by `test/facts-supersede-not-withdrawal.test.ts`. Provenance lands on NewFact.source verbatim (no FactsBackstopCtx). No embedding provider ⇒ `degraded_dedup: true` (near-duplicates may insert — documented). `isNullLikeEntity(entity)` (exported) normalizes null-like entity tokens (`"null"`, `"undefined"`, `"none"`, `"n/a"`, `"nil"`, `"-"`, empty/whitespace) to ABSENT before resolution — applied here rather than only at the verb boundary so EVERY writeSingleFact caller gets the guard and the `resolved?.slug ?? entityRef` fallback can never adopt `"null"` as a slug. On a managed brain, after the withdrawal check and embedding, the fact publishes through `publishManagedEntityFacts` (`src/core/facts/managed-fact-write.ts`, the `managed_facts_entity` intent: fence row, index row and file together, dedup at publication, and the same-kind near-duplicate supersession rule via the intent's `supersede` flag, which strikes the old fence row and expires and links the old fact in the same transaction; an explicit per-fact context is kept; an entity without a live page lands database-only on `memory/unattributed` and, through the intent's opt-in `attribute_fallback` flag, which only writeSingleFact sets, keeps the resolver's fallback slug as `entity_slug` with no row number, so dedup and withdrawal checks stay per entity; the facts backstop never sets it and keeps those rows unattributed). `writeFactsToFence` (`fence-write.ts`) takes the same path on a managed brain, after dropping withdrawn claims. A fence append refused because the page's facts fence does not parse cleanly rethrows the typed `fenceRefusal` (`invalid_fence` / `target_fence_malformed`). On an unmanaged brain, #6398 (fix wave 13): when the page's file is missing but a source-scoped row exists (live, with a vanished `source_path` file, or tombstoned), `writeFactsToFence` returns `stubGuardBlocked` with audit reason `db_only_page` and the caller records the facts DB-only, so no stub overwrites the DB body or resurrects a deleted page; an unreadable row returns `fenceWriteFailed`; the #4872 page mirror runs only for a body read from a real file. Doctor `stub_guard_24h` (`commands/doctor/checks/local-audits.ts`) counts `unprefixed`, `fallback_resolution` and `db_only_page` separately; `db_only_page` never feeds the WARN threshold. Tests: `test/fence-write-db-only.test.ts`, `test/doctor-stub-guard.test.ts`.
- `src/core/facts/managed-fact-write.ts` — `publishManagedEntityFacts(engine, sourceId, entity, facts)` builds one managed facts session per visibility (request identity derived from the write, so a retried job replays its receipt; `attributeFallback` sets the intent's `attribute_fallback`), keeps a caller's vector only when it matches the brain's facts embedding signature, and returns ids in input order; `managedFactWritePreflight` runs the same session checks before a caller's model call.
diff --git a/docs/architecture/key-files/memory-purge.md b/docs/architecture/key-files/memory-purge.md
index b61eee4500..0eb0888711 100644
--- a/docs/architecture/key-files/memory-purge.md
+++ b/docs/architecture/key-files/memory-purge.md
@@ -4,16 +4,16 @@
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
User-facing contract: [expire versus purge](../../guides/memory-boundaries.md#purge).
-- `src/core/facts/purge.ts` — `submitPurgeFactMutation`, the handler of the owner-only `purge_fact` op (`gbrain forget <id> --purge`). Refuses every caller whose `ctx.remote !== false` with `trusted_local_only` (`purgeHostOnly`, actor user, the exact host command). `planFactPurge` (read-only) computes the scope: every fact row with the same `gbrain_fact_fingerprint` in the fact's source, visibility and subject (the fact's `entity_slug`, `'*'` with `all_subjects`), verbatim takes (`facts.consolidated_into` plus same-fingerprint takes on the subject's page), affected pages from `discoverWithdrawalTargets`, page_versions carrying the text, terminal request intents carrying it (`findRequestsCarrying` behind the `purge:carrying_lookup` seam; its 57014 is the typed `purge_lookup_timeout`, nothing planned or purged, pinned by `test/fact-purge-lookup-timeout-6511.test.ts`), derived rows from `derivation_inputs`, the fact's P8 review rows, and a `revision` digest. A dry run returns the receipt, `confirm_token` (fingerprint's first 8 hex) and `expected_revision`; a real run requires `confirm === token` and, when given, an unchanged revision. The journaled intent is `{id, reason, all_subjects, fact_hash}`, never claim text; replay by request id returns the stored outcome. One transaction in the global lock order: source `FOR UPDATE` (serializes with the guards' `FOR SHARE`), counters for the purge and every redacted request, admission, then inside `withCoordinatedWrite`: pending-publication refusal (`purge_blocked_pending_recovery`), intent redaction, page locks, derived rows hidden before evidence goes, `fact_purges`/`take_purges` tombstones, deletes (takes, review rows, open loops by fact id, take proposals by fingerprint, facts), core-notice base text nulled, page bodies rewritten through the purge overlay, chunks deleted, versions redacted in place, legacy `query_cache` cleared, and `withdrawal-mirror`/`git`/`embedding` effects with `mode: 'purge'` and `commit_subject: gbrain: purge fact <hash8>`. Chunks are rebuilt before acknowledging; `similar_active` is computed before deletion. Pinned by `test/purge-fact.test.ts` (both engines) and `test/forget-purge-cli.test.ts`.
-- `src/core/facts/purge-verify.ts` — receipts and verification. `verifyFactPurge` runs one bounded adapter per store (row bound, per-statement `statement_timeout`, a total deadline; `__setPurgeProbeLimitsForTests`): swept stores report `deleted`, `incomplete` (still holds the claim) or `unverified` (bound hit); page-text stores report remaining text as `out_of_scope: source_prose`; every `probed_reported` inventory table is probed and listed; derived rows are `retained_inactive`; model-derived pages without edges are `derived_legacy: unverified`. On-disk: page files (`canonical_markdown`), a quarantined `<file>.tmp` carrying the claim is deleted, the facts write-failure log is reported. `gitResidualCommits` scans `git log --all -p -- <page paths>` output in-process (the pattern never enters argv; byte and time bounded) and lists commits; `OUT_OF_REACH_RESIDUALS` lead every receipt. The vector probe returns same-model neighbours as paraphrase candidates and is never a gate. `purgeCompletion` derives `committed | complete | incomplete` from effects (failed or parked = incomplete), a fingerprint probe and the receipt, with exit codes 10/0/75.
+- `src/core/facts/purge.ts` — `submitPurgeFactMutation`, the handler of the owner-only `purge_fact` op (`gbrain forget <id> --purge`). Refuses every caller whose `ctx.remote !== false` with `trusted_local_only` (`purgeHostOnly`, actor user, the exact host command). `planFactPurge` (read-only) computes the scope: every fact row with the same `gbrain_fact_fingerprint` in the fact's source, visibility and subject (the fact's `entity_slug`, `'*'` with `all_subjects`), verbatim takes (`facts.consolidated_into` plus same-fingerprint takes on the subject's page), affected pages from `discoverWithdrawalTargets`, page_versions carrying the text, terminal request intents carrying it (`findRequestsCarrying` behind the `purge:carrying_lookup` seam; its 57014 is the typed `purge_lookup_timeout`, nothing planned or purged, pinned by `test/fact-purge-lookup-timeout-6511.test.ts`), derived rows from `derivation_inputs`, the fact's P8 review rows, and a `revision` digest. A dry run returns the receipt, `confirm_token` (fingerprint's first 8 hex) and `expected_revision`; a real run requires `confirm === token` and, when given, an unchanged revision. The journaled intent is `{id, reason, all_subjects, fact_hash}`, never claim text; replay by request id returns the stored outcome. One transaction in the global lock order: source `FOR UPDATE` (serializes with the guards' `FOR SHARE`), counters for the purge and every redacted request, admission, then inside `withCoordinatedWrite`: pending-publication refusal (`purge_blocked_pending_recovery`), intent redaction, page locks, derived rows hidden before evidence goes, `fact_purges`/`take_purges` tombstones, deletes (takes, review rows, open loops by fact id, take proposals by fingerprint, facts), core-notice base text nulled, page bodies rewritten through the purge overlay, chunks deleted, versions redacted in place, legacy `query_cache` cleared, and `withdrawal-mirror`/`git`/`embedding` effects with `mode: 'purge'` and `commit_subject: gbrain: purge fact <hash8>`. Chunks are rebuilt before acknowledging; `similar_active` is computed before deletion. Pinned by `test/purge-fact.test.ts` (both engines) and `test/forget-purge-cli.test.ts`. Segmented pages (Wave B): live bodies are rewritten fence by fence through `rewriteLiveSegmentedFences` (a new generation; only the rewritten occurrences' chunks change, an unsealed page is projected after commit), retained generations through `rewriteSegmentedGeneration`; the plan (and its digest) also lists open, sealed or prepared stagings whose staged texts or parts hold the claim plus the queued requests whose `body_ref` names them (`findRequestsHoldingStagings`): the stagings are aborted with their parts deleted, the requests cancelled with `purged_content` (a running or recovering one refuses with `purge_blocked_pending_recovery`), and the segment texts no manifest row references any more are deleted in the same transaction, never left to GC.
+- `src/core/facts/purge-verify.ts` — receipts and verification. `verifyFactPurge` runs one bounded adapter per store (row bound, per-statement `statement_timeout`, a total deadline; `__setPurgeProbeLimitsForTests`): swept stores report `deleted`, `incomplete` (still holds the claim) or `unverified` (bound hit); page-text stores report remaining text as `out_of_scope: source_prose`; every `probed_reported` inventory table is probed and listed; derived rows are `retained_inactive`; model-derived pages without edges are `derived_legacy: unverified`. On-disk: page files (`canonical_markdown`), a quarantined `<file>.tmp` carrying the claim is deleted, the facts write-failure log is reported. `gitResidualCommits` scans `git log --all -p -- <page paths>` output in-process (the pattern never enters argv; byte and time bounded) and lists commits; `OUT_OF_REACH_RESIDUALS` lead every receipt. The vector probe returns same-model neighbours as paraphrase candidates and is never a gate. `purgeCompletion` derives `committed | complete | incomplete` from effects (failed or parked = incomplete), a fingerprint probe and the receipt, with exit codes 10/0/75. A segmented page or version is probed segment by segment (`segmentedBodyContains`, a needle split by a cut is found; row and time bounded) and reported with the page stores; `page_segment_texts` gets an exact-bytes probe (an unreferenced text holding the claim is `incomplete`, a referenced one `out_of_scope`); the page purge probes the texts its manifests referenced (`PagePurgeContext.segmentShas`).
- `src/core/facts/purge-overlay.ts` — purge mode of the import overlay: `dropPurgedFenceRows` drops facts-fence rows matching `fact_purges` and takes-fence rows matching `take_purges` (the takes fence re-renders with its reservation rows plus the dropped numbers reserved, so a purged number is never reused; pinned by `test/purge-overlay-reservations.test.ts`) (subject = page slug; malformed fences left to the withdrawal diagnostics, which refuse a purged claim inside one). Called first by `preserveWithdrawnFenceRows`, so `import-file.ts` needs no change; the snapshot overlay (`page-state/snapshot.ts`) and export (`export-snapshot.ts`) carry purge tombstones as `PageWithdrawal.purged`, which `overlayWithdrawalBody` drops instead of striking.
- `src/core/facts/purge-schema.ts` — `MEMORY_PURGE_SCHEMA_SQL` (schema.sql fragment: `fact_purges`, `take_purges`, `page_purges` keyed `(source_id, content_hash)`, `derivation_inputs`, `needs_rederive`) and `MEMORY_PURGE_GUARD_SQL` (migration only): `facts_refuse_purged`, `takes_refuse_purged` and `pages_refuse_purged` raise `P0001 purged_content: …` (mapped to typed `purged_content` by `persistence/publication-failure.ts`) instead of skipping the row, whatever `expired_at` says. The pages guard has no column list so it never pins columns. `FACT_PURGE_LOOKUP_INDEX_SQL` (migration v231, CONCURRENTLY on Postgres) adds `fact_purges_subject_idx` (a page's own tombstones, the '*' lookup by fingerprint) and the partial `fact_purges_all_subjects_idx` (subject '*' only, for the snapshot marker count).
- `src/core/page-state/snapshot.ts` — a page snapshot lists only the page's own `fact_purges` tombstones; subject-'*' ones come back as `PageSnapshot.globalPurges` (count, latest `purged_at`, world-only flag; absent at count 0). `resolveGlobalPurges` turns the marker into purge withdrawals for the fence rows of whatever text is overlaid (stored page, incoming file in `page-prepare.ts`, `overlayCanonicalBodies`), on the caller's query. Reconcile pins/preimages and extract-atoms page-state hashing carry the marker, so a new '*' purge invalidates them and an artifact without it reads stale. Alias resolution: `readPageSnapshot` with `resolveAlias` first runs the exact-slug statement (an exact hit outranks every alias), then, on a miss or for `requireUnambiguous`, one `WITH chosen` statement whose candidates are a UNION ALL of the exact-slug probe and an alias-join probe (`slug_aliases` → `pages` on `(source_id, canonical_slug)`, `p.slug<>$1` keeps the branches disjoint so `count(*) OVER ()` still counts pages). #6281: never `slug=$1 OR EXISTS(alias)`, which read every page of every readable source; `page-snapshot-alias-plan.test.ts` pins fewer than 100 `pages` rows per statement from EXPLAIN on both engines.
- `src/core/facts/derivation-inputs.ts` — `recordDerivationInputs(tx, {table, id, sourceId}, inputs)`: complete derived-row → input edges, written by derivers in the deriving transaction (`write_origin` keeps only a display sample). `derivedRowsFrom` walks edges breadth-first (bounded, reports `truncated`); `hideDerivedRows` expires facts, deactivates takes, soft-deletes pages and upserts `needs_rederive`.
- `src/core/deletion-inventory.ts` — the deletion-target registry: every table with a text, JSON, bytes, array, lexeme or vector column, classed `swept`, `retained_inactive` or `out_of_scope` (`probed_reported` with probe columns, `text_free_ledger`, `secret_material`, `no_memory_text`), plus on-disk stores and out-of-reach residuals. `test/deletion-inventory.test.ts` fails on any unlisted text-bearing column of a fresh schema and pins the AGENTS.md "never promise physical erasure" line.
-- `src/core/persistence/intent-redaction.ts` — accounting-aware intent redaction: `findRequestsCarrying` (intent, outcome, error detail or message, compacted rows included; the fact purge's planning read) / `findRequestsForSlugs` (index-served by `persistence_requests_slug_intent`), the page purge's preparation-time journal census `sweepRequestsCarrying` (#6511: a keyset walk of the source's journal in `JOURNAL_SWEEP_CHUNK_ROWS` chunks, every needle in raw and JSON-escaped form against intent, outcome, error detail and message, compacted rows included, the purge's own row excluded, stopped by the claim clock between chunks and at `JOURNAL_SWEEP_MATCH_CAP`; returns the carrying ids, the ids pending at the scan, the `sequence` ceiling as text and `complete`) with `recheckRequestsCarrying` for the publication's bounded re-check of the tail past the ceiling and of the rows that were pending, `redactRequestIntents` locks counters then request rows, refuses on a non-terminal or recovering request (unless `skipPending`), nulls `intent`/`error_message` and replaces every outcome or error-detail string carrying a needle with `"[purged]"` (`redactJson`), with compaction's terminal-byte accounting, so replay keeps returning the (redacted) stored outcome.
+- `src/core/persistence/intent-redaction.ts` — accounting-aware intent redaction: `findRequestsCarrying` (intent, outcome, error detail or message, compacted rows included; the fact purge's planning read) / `findRequestsForSlugs` (index-served by `persistence_requests_slug_intent`), the page purge's preparation-time journal census `sweepRequestsCarrying` (#6511: a keyset walk of the source's journal in `JOURNAL_SWEEP_CHUNK_ROWS` chunks, every needle in raw and JSON-escaped form against intent, outcome, error detail and message, compacted rows included, the purge's own row excluded, stopped by the claim clock between chunks and at `JOURNAL_SWEEP_MATCH_CAP`; returns the carrying ids, the ids pending at the scan, the `sequence` ceiling as text and `complete`) with `recheckRequestsCarrying` for the publication's bounded re-check of the tail past the ceiling and of the rows that were pending, `redactRequestIntents` locks counters then request rows, refuses on a non-terminal or recovering request (unless `skipPending`), nulls `intent`/`error_message` and replaces every outcome or error-detail string carrying a needle with `"[purged]"` (`redactJson`), with compaction's terminal-byte accounting, so replay keeps returning the (redacted) stored outcome. `findRequestsHoldingStagings` / `cancelRequestsHoldingStagings`: the queued requests whose `intent.body_ref.staging_id` names a staging a fact purge aborts are completed `cancelled` with `purged_content`.
- `src/core/persistence/purged-intent.ts` — `intentCarriesPurgedContent`: `completeWrite` (journal.ts) nulls the intent of any terminal request whose content (`fact`, `claim`, page fence rows, or the page's content hash) matches a subject-scoped purge tombstone, and of any refusal coded `purged_content`; a write refused for another reason, or committed as a no-op after the overlay dropped purged rows, keeps no copy. Only content-bearing intents are checked, and whether the source holds any tombstone is selected by completeWrite's terminal statement itself (`PURGE_PRESENCE_COLUMNS`), so the hook adds no statement to a write on a source without tombstones (#6007 budget). `purged_content` is a write error code, so receipts and the frozen verb path (wire `invalid_params`, canonical `purged_content`) keep it typed.
-- `src/core/persistence/page-purge.ts` — `purgePageInTransaction`, called by the `delete_page purge:true` apply in `page-prepare.ts`: records in `page_purges` the content hash of the page and of every retained version (up to 1000), each as imported and as purge-overlaid, so an older version is refused too; drops the decide rows, trust proposals, gate holds (by slug) and gate receipts naming the page or its rows and clears legacy `query_cache`; tombstones and deletes facts filed on the page, tombstones its takes, deletes take proposals, open loops, core notices and `files` rows, the page's `page_aliases` and the `slug_aliases` redirects whose `canonical_slug` is the page (#6619; a redirect from this slug to another page stays; counted in `removed` and checked by slug in the receipt), redacts finished intents for the slug and the carrying ids the preparation sweep found plus the publication's tail and pending re-check (#6511: `preparePagePurge` runs `readPurgeClaims` and `sweepRequestsCarrying` under the preparation budget at steps `purge_claims` / `purge_journal_sweep`, so the O(journal) substring scan is a charged `preparation_deadline` release and `preparation_stalled` at the attempt limit, never a transaction timeout; the lookups that stay inside the transaction go through `lookup`, which maps a 57014 to the terminal, non-retryable `purge_lookup_timeout` naming `gbrain repair request-indexes` only when `persistence_requests_slug_intent` is missing or INVALID; the receipt's `journal_sweep` reports `ceiling`, `scanned`, `tail`, `pending_rechecked` and `complete`), then deletes the page (FK cascades). `PURGE_RESIDUALS` names what stays out of reach. `finishPagePurge` deletes stored blobs after commit, lists any left by storage path, and attaches `receipt`, the store-by-store receipt from `verifyPagePurge` (same shape as the fact receipt: residuals first, every swept inventory store, other pages' prose naming a purged claim as `source_prose`); the page's claims used as needles live only in process memory, and a same-id replay returns the result built when the purge ran. `residuals` stays the prose string. `readPagePurgeTombstones` feeds `screenImportContent({ purgedPages })` from managed sync's freeze-time screen (`sync-screen.ts`, one read per run) and publication (`sync-prepare.ts`), which hold a matching file as `purged_content`; direct imports and `put_page` hit the pages guard instead; `listPagePurges` / `unpurgePage` (also clears the fact and take tombstones of the same request) back the owner-only ops. Pinned by `test/page-purge.test.ts` and `test/page-purge-journal-timeout-6511.test.ts` (both engines; seams `purge:*` in `fault-points.ts`). #6368: a purge of a tombstone whose file matches `sync.exclude` (discovery's globs via `syncExcludePatterns` in `sync-discovery.ts`, matched relative to the source root) owns no file: `prepareFileTarget`'s `excludeTombstone` option returns no target, the purge is database-only and the receipt says `write_through.skipped: 'sync_excluded'`; the file is neither compared nor removed (an unchanged excluded file used to be deleted, an edited one refused forever). The apply re-reads the exclusion inside the publication transaction and refuses `source_changed` if it was removed meanwhile. Live-page purges and soft deletes are unchanged.
+- `src/core/persistence/page-purge.ts` — `purgePageInTransaction`, called by the `delete_page purge:true` apply in `page-prepare.ts`: records in `page_purges` the content hash of the page and of every retained version (up to 1000), each as imported and as purge-overlaid, so an older version is refused too; drops the decide rows, trust proposals, gate holds (by slug) and gate receipts naming the page or its rows and clears legacy `query_cache`; tombstones and deletes facts filed on the page, tombstones its takes, deletes take proposals, open loops, core notices and `files` rows, the page's `page_aliases` and the `slug_aliases` redirects whose `canonical_slug` is the page (#6619; a redirect from this slug to another page stays; counted in `removed` and checked by slug in the receipt), redacts finished intents for the slug and the carrying ids the preparation sweep found plus the publication's tail and pending re-check (#6511: `preparePagePurge` runs `readPurgeClaims` and `sweepRequestsCarrying` under the preparation budget at steps `purge_claims` / `purge_journal_sweep`, so the O(journal) substring scan is a charged `preparation_deadline` release and `preparation_stalled` at the attempt limit, never a transaction timeout; the lookups that stay inside the transaction go through `lookup`, which maps a 57014 to the terminal, non-retryable `purge_lookup_timeout` naming `gbrain repair request-indexes` only when `persistence_requests_slug_intent` is missing or INVALID; the receipt's `journal_sweep` reports `ceiling`, `scanned`, `tail`, `pending_rechecked` and `complete`), then deletes the page (FK cascades). `PURGE_RESIDUALS` names what stays out of reach. `finishPagePurge` deletes stored blobs after commit, lists any left by storage path, and attaches `receipt`, the store-by-store receipt from `verifyPagePurge` (same shape as the fact receipt: residuals first, every swept inventory store, other pages' prose naming a purged claim as `source_prose`); the page's claims used as needles live only in process memory, and a same-id replay returns the result built when the purge ran. `residuals` stays the prose string. `readPagePurgeTombstones` feeds `screenImportContent({ purgedPages })` from managed sync's freeze-time screen (`sync-screen.ts`, one read per run) and publication (`sync-prepare.ts`), which hold a matching file as `purged_content`; direct imports and `put_page` hit the pages guard instead; `listPagePurges` / `unpurgePage` (also clears the fact and take tombstones of the same request) back the owner-only ops. Pinned by `test/page-purge.test.ts` and `test/page-purge-journal-timeout-6511.test.ts` (both engines; seams `purge:*` in `fault-points.ts`). #6368: a purge of a tombstone whose file matches `sync.exclude` (discovery's globs via `syncExcludePatterns` in `sync-discovery.ts`, matched relative to the source root) owns no file: `prepareFileTarget`'s `excludeTombstone` option returns no target, the purge is database-only and the receipt says `write_through.skipped: 'sync_excluded'`; the file is neither compared nor removed (an unchanged excluded file used to be deleted, an edited one refused forever). The apply re-reads the exclusion inside the publication transaction and refuses `source_changed` if it was removed meanwhile. Live-page purges and soft deletes are unchanged. A segmented page or version is never loaded whole: its stored `content_hash` and the purge-overlaid hash streamed by `rewrittenContentHash` are tombstoned; its stagings (by slug or page id) and the segment texts only its manifests referenced are deleted in the purge transaction (`removed.page_body_manifest` / `page_body_stagings` / `page_segment_texts`).
- `src/core/ops/purge.ts` — `purge_fact`, `list_page_purges`, `unpurge_page`: admin scope, `cliOnly` (every MCP route gets `trusted_local_only`). The resident owner runs them only for its verified local CLI registration (`LOCAL_CLI_OWNER_OPERATIONS` in `persistence/ipc.ts`, checked in `persistence/provider.ts`).
- `src/commands/forget-purge.ts` + `src/commands/pages-purges.ts` — the CLI fronts. `runForgetPurge` always runs the dry run, then a typed token on a terminal or `--yes` plus `--request-id` without one; `--match` lists ids, `--status` polls completion; `PURGE_FAMILY_HELP` is the purge-family table shown by `gbrain forget --help`. `gbrain pages purges list` and `gbrain pages unpurge <slug>` run the page-tombstone ops as the trusted CLI.
diff --git a/src/core/engine-sql/pages.ts b/src/core/engine-sql/pages.ts
index 39df0b0058..919b6938a2 100644
--- a/src/core/engine-sql/pages.ts
+++ b/src/core/engine-sql/pages.ts
@@ -310,14 +310,26 @@ export async function purgeDeletedPages(
}));
return { slugs: pages.map((p) => p.slug), count: pages.length, pages };
}
- const { rows } = await exec.run<{ slug: string }>(sqlFragment`
- DELETE FROM pages
- WHERE deleted_at IS NOT NULL
- AND deleted_at < now() - (${hours} || ' hours')::interval
- RETURNING slug
- `);
- const slugs = rows.map((r) => r.slug);
- return { slugs, count: slugs.length };
+ // Wave B (spec 11): segment texts only the purged pages' manifests reference go in the same purge, not by later GC.
+ return exec.transaction(async (tx) => {
+ const { rows: texts } = await tx.run<{ source_id: string; sha: string }>(sqlFragment`
+ SELECT DISTINCT m.source_id, encode(m.sha256, 'hex') AS sha FROM page_body_manifest m JOIN pages p ON p.id = m.page_id
+ WHERE p.deleted_at IS NOT NULL AND p.deleted_at < now() - (${hours} || ' hours')::interval`);
+ const { rows } = await tx.run<{ slug: string; source_id: string }>(sqlFragment`
+ DELETE FROM pages
+ WHERE deleted_at IS NOT NULL
+ AND deleted_at < now() - (${hours} || ' hours')::interval
+ RETURNING slug, source_id
+ `);
+ if (rows.length) await tx.run(sqlFragment`DELETE FROM page_body_stagings s USING unnest(${rows.map(r => r.source_id)}::text[], ${rows.map(r => r.slug)}::text[]) AS d(source_id, slug)
+ WHERE s.source_id = d.source_id AND s.slug = d.slug`);
+ if (texts.length) await tx.run(sqlFragment`DELETE FROM page_segment_texts t
+ USING unnest(${texts.map(r => r.source_id)}::text[], ${texts.map(r => r.sha)}::text[]) AS d(source_id, sha)
+ WHERE t.source_id = d.source_id AND t.sha256 = decode(d.sha, 'hex')
+ AND NOT EXISTS (SELECT 1 FROM page_body_manifest m WHERE m.source_id = t.source_id AND m.sha256 = t.sha256)`);
+ const slugs = rows.map((r) => r.slug);
+ return { slugs, count: slugs.length };
+ });
}
export async function refreshPageBody(
diff --git a/src/core/facts/forget.ts b/src/core/facts/forget.ts
index 0584f5ffd3..4b23064dc6 100644
--- a/src/core/facts/forget.ts
+++ b/src/core/facts/forget.ts
@@ -20,7 +20,8 @@ import { parseFactsFence, renderFactsTable, type ParsedFact } from '../facts-fen
import { parseMarkdown } from '../markdown.ts';
import { sanitizeText } from '../batch-rows.ts';
import { contentHash } from '../utils.ts';
-import { assertInlineBody } from '../page-body/page-shape.ts';
+import { isSegmentedPage } from '../page-body/page-shape.ts';
+import { rewriteLiveSegmentedFences } from '../page-body/segment-rewrite.ts';
import { recordFactWithdrawal } from './withdrawal.ts';
import { maintenanceTransaction } from '../persistence/attribution.ts';
import { withdrawnFact } from './withdrawal-overlay.ts';
@@ -177,12 +178,23 @@ export async function forgetFactInFence(
// Mirror the retraction in the page body. The withdrawal record protects
// active facts even if this best-effort mirror fails or a stale file returns.
+ // Wave B (spec 11): a segmented page's row is struck in the segment holding its fence (a new generation; only the
+ // rewritten occurrences' chunks are replaced), never by loading the body. The first fence holding the row is struck.
+ const strikeSegments = async (pageId: number): Promise<void> => {
+ let struck = false;
+ await maintenanceTransaction(engine, tx => rewriteLiveSegmentedFences(tx, pageId, async fence => {
+ const next = struck ? null : strikeFenceRow(fence, row.row_num!, strike);
+ if (next === null) return fence;
+ struck = true;
+ return next;
+ }));
+ };
const strikeDbBody = async (): Promise<void> => {
if (row.row_num === null || row.source_markdown_slug === null) return;
const slug = row.source_markdown_slug;
const page = await engine.getPage(slug, { sourceId: row.source_id });
if (!page) return;
- assertInlineBody(page, 'forget fence strike');
+ if (isSegmentedPage(page)) return strikeSegments(page.id);
const struck = strikeFenceRow(page.compiled_truth ?? '', row.row_num, strike);
if (struck === null) return;
// The FILE was not rewritten on this tier, so the row must NOT keep the
@@ -291,8 +303,8 @@ export async function forgetFactInFence(
try {
const reparsed = parseMarkdown(tmpBody, `${slug}.md`);
const page = await engine.getPage(slug, { sourceId: row.source_id });
- if (page) {
- assertInlineBody(page, 'forget fence mirror');
+ if (page && isSegmentedPage(page)) await strikeSegments(page.id);
+ else if (page) {
await maintenanceTransaction(engine, tx => tx.refreshPageBody(slug, row.source_id,
sanitizeText(reparsed.compiled_truth), sanitizeText(reparsed.timeline),
page.content_hash || contentHash(page)));
diff --git a/src/core/facts/purge-verify.ts b/src/core/facts/purge-verify.ts
index 96d76f0918..fbe0a866a1 100644
--- a/src/core/facts/purge-verify.ts
+++ b/src/core/facts/purge-verify.ts
@@ -26,6 +26,7 @@ import type { WriteRequest } from '../persistence/model.ts';
import { DELETION_INVENTORY, OUT_OF_REACH_RESIDUALS, type InventoryEntry } from '../deletion-inventory.ts';
import type { PurgePlan, PurgeTarget } from './purge.ts';
import { gitChildEnv } from '../git-env.ts';
+import { segmentedBodyContains } from '../page-body/segment-rewrite.ts';
export type StoreCount = Record<string, number>;
export type StoreStatus = 'deleted' | 'would_remove' | 'retained_inactive' | 'unverified' | 'out_of_reach' | 'out_of_scope' | 'not_present' | 'incomplete';
@@ -55,16 +56,56 @@ export function __setPurgeProbeLimitsForTests(limits: Partial<typeof probeLimits
}
/**
- * Wave B PR 1: segment text is not probed yet (segment probe in PR 2), so a page-text report over a source
- * holding segmented pages is `unverified` instead of passing on NULL body columns.
+ * Wave B (spec 11): which segmented bodies of the source state one of `needles`, case-insensitively: live pages
+ * (`pages`) or retained versions (`page_versions`), each scanned one segment at a time with the tail of the
+ * previous segment carried over the needle's length (a forced cut can split prose). Bounded like every probe.
*/
-async function unprobedSegmentedPages(engine: BrainEngine, sourceId: string, report: StoreReport): Promise<StoreReport> {
- if (report.status === 'incomplete' || report.status === 'would_remove') return report;
- const [row] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND body_storage='segmented'`, [sourceId]);
- const n = Number(row?.n ?? 0);
- if (!n) return report;
- return { ...report, status: 'unverified', reason: 'segmented_body',
- detail: `${n} page(s) in this source store their body in segments, which this receipt does not search yet; the claim may survive there.` };
+async function segmentedProse(engine: BrainEngine, sourceId: string, needles: readonly string[], deadline: number, store: 'pages' | 'page_versions'):
+ Promise<{ hits: Array<{ slug: string; version_id?: number }> } | { unverified: string }> {
+ const bodies = store === 'pages'
+ ? await engine.executeRaw<{ page_id: number; slug: string; generation: null; version_id: null }>(`SELECT id AS page_id,slug,NULL AS generation,NULL AS version_id FROM pages
+ WHERE source_id=$1 AND deleted_at IS NULL AND body_storage='segmented' ORDER BY id LIMIT $2`, [sourceId, probeLimits.rows + 1])
+ : await engine.executeRaw<{ page_id: number; slug: string; generation: number; version_id: number }>(`SELECT v.page_id,p.slug,v.body_generation AS generation,v.id AS version_id
+ FROM page_versions v JOIN pages p ON p.id=v.page_id WHERE p.source_id=$1 AND v.body_storage='segmented' ORDER BY v.id LIMIT $2`, [sourceId, probeLimits.rows + 1]);
+ if (bodies.length > probeLimits.rows) return { unverified: 'row_bound' };
+ const hits: Array<{ slug: string; version_id?: number }> = [];
+ for (const body of bodies) {
+ const found = await segmentedBodyContains(engine, Number(body.page_id), sourceId, needles,
+ { deadline, ...(body.generation === null ? {} : { generation: Number(body.generation) }) });
+ if (found === 'deadline') return { unverified: 'verification_deadline' };
+ if (found) hits.push({ slug: body.slug, ...(body.version_id === null ? {} : { version_id: Number(body.version_id) }) });
+ }
+ return { hits };
+}
+
+/** A page-text store's report with its segmented bodies folded in: a body still stating the claim is prose, a stopped scan is unverified. */
+async function withSegmentedProse(engine: BrainEngine, report: StoreReport, sourceId: string, needles: readonly string[], deadline: number): Promise<StoreReport> {
+ if (report.status === 'would_remove' || report.status === 'incomplete' || report.status === 'unverified') return report;
+ const scan = await segmentedProse(engine, sourceId, needles, deadline, report.store as 'pages' | 'page_versions');
+ if ('unverified' in scan) return { ...report, status: 'unverified', reason: scan.unverified };
+ if (!scan.hits.length) return report;
+ return { ...report, status: 'out_of_scope', reason: 'source_prose', remaining: (report.remaining ?? 0) + scan.hits.length,
+ items: [...(report.items ?? []), ...scan.hits].slice(0, 20),
+ detail: 'The claim text survives outside a facts fence (page prose); purge the page or edit it to remove it.' };
+}
+
+/**
+ * Segment texts of the source holding the claim's exact bytes: a text no manifest row references any more is a
+ * residual of the sweep (`incomplete`); a referenced one is a body's prose, reported with that body.
+ */
+async function segmentTextReport(engine: BrainEngine, sourceId: string, needles: readonly string[], removed: number, deadline: number): Promise<StoreReport> {
+ const list = needles.filter(Boolean).slice(0, 32);
+ const carrying = `SELECT 1 FROM page_segment_texts t WHERE t.source_id=$1 AND EXISTS (SELECT 1 FROM unnest($2::text[]) n WHERE position(convert_to(n,'UTF8') in t.body)>0)`;
+ const referenced = 'EXISTS (SELECT 1 FROM page_body_manifest m WHERE m.source_id=t.source_id AND m.sha256=t.sha256)';
+ const orphaned = await boundedCount(engine, `${carrying} AND NOT ${referenced}`, [sourceId, list], deadline);
+ if ('unverified' in orphaned) return { store: 'page_segment_texts', status: 'unverified', reason: orphaned.unverified, removed };
+ if (orphaned.count) return { store: 'page_segment_texts', status: 'incomplete', remaining: orphaned.count, removed };
+ const kept = await boundedCount(engine, `${carrying} AND ${referenced}`, [sourceId, list], deadline);
+ if ('unverified' in kept) return { store: 'page_segment_texts', status: 'unverified', reason: kept.unverified, removed };
+ return kept.count
+ ? { store: 'page_segment_texts', status: 'out_of_scope', reason: 'source_prose', remaining: kept.count, removed,
+ detail: 'Segments of live pages or retained versions still state the text outside a facts fence; they are listed under pages and page_versions.' }
+ : { store: 'page_segment_texts', status: removed ? 'deleted' : 'not_present', removed };
}
type ProbeResult = { count: number } | { unverified: string };
@@ -244,12 +285,13 @@ export async function verifyFactPurge(engine: BrainEngine, input: { target: Purg
const prose = { status: 'out_of_scope' as const, reason: 'source_prose', detail: 'The claim text survives outside a facts fence (page prose); purge the page or edit it to remove it.' };
await swept('pages', `SELECT 1 FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND (strpos(lower(compiled_truth),$2)>0 OR strpos(lower(timeline),$2)>0)`,
[src, needle], plan.pages.length, removed.pages, prose);
- stores[stores.length - 1] = await unprobedSegmentedPages(engine, src, stores[stores.length - 1]!);
+ stores[stores.length - 1] = await withSegmentedProse(engine, stores[stores.length - 1]!, src, [claim], deadline);
await swept('content_chunks', `SELECT 1 FROM content_chunks c JOIN pages p ON p.id=c.page_id WHERE p.source_id=$1 AND strpos(lower(c.chunk_text),$2)>0`,
[src, needle], plan.pages.length, removed.chunks, prose);
await swept('page_versions', `SELECT 1 FROM page_versions v JOIN pages p ON p.id=v.page_id WHERE p.source_id=$1
AND (strpos(lower(v.compiled_truth),$2)>0 OR strpos(lower(COALESCE(v.timeline,'')),$2)>0)`,
[src, needle], plan.versions, removed.page_versions, { ...prose, items: (input.prose ?? []).slice(0, 20) });
+ stores[stores.length - 1] = await withSegmentedProse(engine, stores[stores.length - 1]!, src, [claim], deadline);
await swept('persistence_requests', `SELECT 1 FROM persistence_requests WHERE source_id=$1 AND (${['intent', 'outcome', 'error_detail', 'error_message']
.map(c => `strpos(lower(COALESCE(${c}::text,'')),$2)>0 OR strpos(lower(COALESCE(${c}::text,'')),$3)>0`).join(' OR ')})`,
[src, needle, JSON.stringify(claim).slice(1, -1).toLowerCase()], plan.requests.length, removed.persistence_requests);
@@ -270,6 +312,7 @@ export async function verifyFactPurge(engine: BrainEngine, input: { target: Purg
AND NOT EXISTS (SELECT 1 FROM derivation_inputs d WHERE d.derived_table='pages' AND d.derived_id=p.id::text)`, [src]);
if (Number(legacy?.n ?? 0)) stores.push({ store: 'derived_legacy', status: 'unverified', reason: 'legacy_no_derivation_edges', remaining: Number(legacy.n),
detail: `${legacy.n} model-derived page(s) in this source predate derivation edges, so purge cannot tell whether they restate the claim in other words.` });
+ if (!dryRun) stores.push(await segmentTextReport(engine, src, [claim], removed.page_segment_texts ?? 0, deadline));
stores.push(...await sweptInventoryReports(engine, new Set(stores.map(s => s.store)), src, [claim], removed, deadline, dryRun));
for (const entry of DELETION_INVENTORY) {
if (entry.class !== 'out_of_scope' || entry.reason !== 'probed_reported') continue;
@@ -304,7 +347,7 @@ export async function verifyFactPurge(engine: BrainEngine, input: { target: Purg
}
/** In-process context a page purge keeps for its receipt (never journaled): the page's claims as probe needles, and row ids. */
-export interface PagePurgeContext { needles: string[]; factIds: number[]; pageId: number; paths: string[] }
+export interface PagePurgeContext { needles: string[]; factIds: number[]; pageId: number; paths: string[]; segmentShas: string[] }
const outOfReach = (engine: BrainEngine): StoreReport[] => OUT_OF_REACH_RESIDUALS.map(r => ({ store: r.store, status: 'out_of_reach' as const,
detail: r.store === 'database_physical' ? `${r.detail}${engine.kind === 'pglite' ? ' PGLite has no autovacuum.' : ' On Postgres the operator runs VACUUM; WAL archives, replicas and PITR windows are outside gbrain.'}` : r.detail }));
@@ -337,6 +380,9 @@ export async function verifyPagePurge(engine: BrainEngine, input: { sourceId: st
await 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]);
+ if (context?.segmentShas.length) await keyed('page_segment_texts', `SELECT 1 FROM page_segment_texts t WHERE t.source_id=$1
+ AND 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)`, [src, context.segmentShas]);
if (context) {
const refs = context.factIds.map(String);
for (const table of ['decide_review_queue', 'decide_review_proposals']) await keyed(table, `SELECT 1 FROM ${table} WHERE source_id=$1 AND (a_ref=ANY($2::text[]) OR b_ref=ANY($2::text[]))`, [src, refs]);
@@ -369,8 +415,14 @@ export async function verifyPagePurge(engine: BrainEngine, input: { sourceId: st
AND EXISTS (SELECT 1 FROM unnest($2::text[]) n WHERE strpos(lower(t.summary),n)>0 OR strpos(lower(COALESCE(t.detail,'')),n)>0)`,
};
const all = new Set<string>();
+ let unverified: string | null = null;
for (const [store, sql] of Object.entries(proseIn)) {
const slugs = (await engine.executeRaw<{ slug: string }>(`${sql} ORDER BY 1 LIMIT 20`, [src, lowered])).map(r => r.slug);
+ if (store === 'pages' || store === 'page_versions') {
+ const scan = await segmentedProse(engine, src, needles, deadline, store);
+ if ('unverified' in scan) unverified = scan.unverified;
+ else slugs.push(...new Set(scan.hits.map(hit => hit.slug)));
+ }
if (!slugs.length) continue;
slugs.forEach(s => all.add(s));
const at = stores.findIndex(s => s.store === store);
@@ -379,7 +431,8 @@ export async function verifyPagePurge(engine: BrainEngine, input: { sourceId: st
if (at >= 0 && stores[at]!.status !== 'incomplete') stores[at] = report; else if (at < 0) stores.push(report);
}
stores.push(all.size ? { store: 'source_prose', status: 'out_of_scope', reason: 'source_prose', remaining: all.size, items: [...all].sort(),
- detail: 'Other pages still state a claim from the purged page in their prose; edit or purge them.' } : await unprobedSegmentedPages(engine, src, { store: 'source_prose', status: 'not_present' }));
+ detail: 'Other pages still state a claim from the purged page in their prose; edit or purge them.' }
+ : unverified ? { store: 'source_prose', status: 'unverified', reason: unverified } : { store: 'source_prose', status: 'not_present' });
}
const [source] = await engine.executeRaw<{ local_path: string | null }>('SELECT local_path FROM sources WHERE id=$1', [src]);
const files = source?.local_path ? (context?.paths ?? []).filter(p => !p.startsWith('/') && !p.includes('..')).map(p => join(source.local_path!, p)) : [];
diff --git a/src/core/facts/purge.ts b/src/core/facts/purge.ts
index e116a74e81..26d928c8f8 100644
--- a/src/core/facts/purge.ts
+++ b/src/core/facts/purge.ts
@@ -26,7 +26,7 @@ import { opError, OperationError } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
import { faultPoint } from '../persistence/fault-points.ts';
import { contentHash, rowToPage } from '../utils.ts';
-import { assertInlineBody } from '../page-body/page-shape.ts';
+import { rewriteLiveSegmentedFences, rewriteSegmentedGeneration, segmentedBodyContains } from '../page-body/segment-rewrite.ts';
import { discoverWithdrawalTargets, withdrawalDiscoveryFailure } from './withdrawal-discovery.ts';
import { dropPurgedFenceRows } from './purge-overlay.ts';
import { derivedRowsFrom, hideDerivedRows, type DerivationRef } from './derivation-inputs.ts';
@@ -40,9 +40,10 @@ import { withCoordinatedWrite } from '../persistence/context.ts';
import { requestAttribution } from '../persistence/attribution.ts';
import { isTerminal, principalKey, type WriteRequest } from '../persistence/model.ts';
import { retryWriteAdmission } from '../persistence/admission-retry.ts';
-import { findRequestsCarrying, redactionCounterKeys, redactRequestIntents } from '../persistence/intent-redaction.ts';
+import { cancelRequestsHoldingStagings, findRequestsCarrying, findRequestsHoldingStagings, redactionCounterKeys, redactRequestIntents } from '../persistence/intent-redaction.ts';
import { withPageTierKept } from '../trust/fence-append.ts';
import { rebuildPendingPageProjections } from '../page-state/projections.ts';
+import { buildSegmentedProjection } from '../page-body/projection.ts';
import { purgeCompletion, verifyFactPurge, type PurgeReceipt, type StoreCount } from './purge-verify.ts';
export const PURGE_OPERATION = 'purge_fact';
@@ -61,6 +62,10 @@ export interface PurgePlan {
pages: Array<{ slug: string; page_id: number; revision: string }>;
versions: number;
requests: Awaited<ReturnType<typeof findRequestsCarrying>>;
+ /** Live stagings whose staged segment texts or upload parts hold the claim (aborted by the purge). */
+ stagings: string[];
+ /** Unfinished requests whose `intent.body_ref` names one of `stagings` (cancelled with purged_content). */
+ held: Awaited<ReturnType<typeof findRequestsHoldingStagings>>;
derived: Awaited<ReturnType<typeof derivedRowsFrom>>;
reviewRows: number;
/** Per review table: rows naming the purged facts (all dropped by the purge). */
@@ -109,7 +114,14 @@ export async function planFactPurge(engine: BrainEngine, target: PurgeTarget, al
'SELECT slug,id AS page_id,knowledge_revision::text AS revision FROM pages WHERE source_id=$1 AND id=ANY($2::int[])', [target.source_id, extra]) : [];
const pages = [...discovered, ...takePages.map(p => ({ ...p, page_id: Number(p.page_id) }))].sort((a, b) => a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0);
const [versions] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM page_versions v JOIN pages p ON p.id=v.page_id
- WHERE p.source_id=$1 AND (strpos(lower(v.compiled_truth),$2)>0 OR strpos(lower(COALESCE(v.timeline,'')),$2)>0)`, [target.source_id, target.fact.toLowerCase()]);
+ WHERE p.source_id=$1 AND (strpos(lower(v.compiled_truth),$2)>0 OR strpos(lower(COALESCE(v.timeline,'')),$2)>0
+ OR (v.body_storage='segmented' AND ${SEGMENTED_VERSION_CARRIES}))`, [target.source_id, target.fact.toLowerCase()]);
+ const stagings = (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
+ JOIN 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);
+ 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.
const requests = await faultPoint('purge:carrying_lookup', { sourceId: target.source_id, operation: PURGE_OPERATION })
.then(() => findRequestsCarrying(engine, target.source_id, target.fact)).catch(error => {
@@ -129,8 +141,8 @@ export async function planFactPurge(engine: BrainEngine, target: PurgeTarget, al
const review = { decide_review_queue: Number(counts?.q ?? 0), decide_review_proposals: Number(counts?.rp ?? 0), decide_proposals: Number(counts?.dp ?? 0) };
const { createHash } = await import('node:crypto');
const revision = createHash('sha256').update(JSON.stringify({ subject, factIds, takes: takes.map(t => t.id),
- pages: pages.map(p => [p.page_id, p.revision]), requests: requests.map(r => r.id) })).digest('hex').slice(0, 16);
- return { subject, factIds, takes, pages, versions: Number(versions?.n ?? 0), requests, derived,
+ pages: pages.map(p => [p.page_id, p.revision]), requests: requests.map(r => r.id), stagings })).digest('hex').slice(0, 16);
+ return { subject, factIds, takes, pages, versions: Number(versions?.n ?? 0), requests, stagings, held, derived,
reviewRows: review.decide_review_queue + review.decide_review_proposals + review.decide_proposals, review, revision };
}
@@ -149,15 +161,32 @@ async function assertNoPendingPublication(tx: BrainEngine, sourceId: string, pag
why: 'Shows the source\'s pending and recovering writes, read-only.' } });
}
-/** Drop purged rows from each affected page's stored body; returns the slugs rewritten. */
-async function rewritePageBodies(tx: BrainEngine, sourceId: string, pages: PurgePlan['pages']): Promise<string[]> {
- if (!pages.length) return [];
+/** A segmented version (`v`) whose generation's segment texts hold the lowered claim `$2`. */
+const SEGMENTED_VERSION_CARRIES = `EXISTS (SELECT 1 FROM page_body_manifest m JOIN page_segment_texts t ON t.source_id=m.source_id AND t.sha256=m.sha256
+ WHERE m.page_id=v.page_id AND m.staging_id IS NULL AND m.gen_from<=v.body_generation AND (m.gen_to IS NULL OR m.gen_to>v.body_generation)
+ AND strpos(lower(convert_from(t.body,'UTF8')),$2)>0)`;
+
+/** What the body rewrites changed: slugs rewritten, segmented pages touched, and the segment texts they stopped referencing. */
+interface BodyRewrites { rewritten: string[]; segmented: number[]; unsealed: string[]; replaced: Uint8Array[] }
+
+/** Drop purged rows from each affected page's stored body; a segmented page publishes a new generation (spec 11). */
+async function rewritePageBodies(tx: BrainEngine, sourceId: string, pages: PurgePlan['pages']): Promise<BodyRewrites> {
+ const out: BodyRewrites = { rewritten: [], segmented: [], unsealed: [], replaced: [] };
+ if (!pages.length) return out;
const rows = await tx.executeRaw<Record<string, unknown>>(`SELECT p.*,COALESCE((SELECT jsonb_agg(t.tag ORDER BY t.tag) FROM tags t WHERE t.page_id=p.id),'[]'::jsonb) AS purge_tags
FROM pages p WHERE p.source_id=$1 AND p.id=ANY($2::int[]) ORDER BY p.slug`, [sourceId, pages.map(p => p.page_id)]);
- const rewritten: string[] = [];
for (const row of rows) {
+ if (row.body_storage === 'segmented') {
+ const slug = String(row.slug);
+ out.segmented.push(Number(row.id));
+ const done = await rewriteLiveSegmentedFences(tx, Number(row.id), fence => dropPurgedFenceRows(tx, sourceId, fence, slug));
+ if (!done) continue;
+ out.rewritten.push(slug);
+ out.replaced.push(...done.replaced);
+ if (!done.sealed) out.unsealed.push(slug);
+ continue;
+ }
const page = rowToPage(row);
- assertInlineBody(page, 'purge page rewrite');
const compiled = await dropPurgedFenceRows(tx, sourceId, page.compiled_truth, page.slug);
const timeline = await dropPurgedFenceRows(tx, sourceId, page.timeline ?? '', page.slug);
if (compiled === page.compiled_truth && timeline === (page.timeline ?? '')) continue;
@@ -165,17 +194,18 @@ async function rewritePageBodies(tx: BrainEngine, sourceId: string, pages: Purge
// #5575 ENG-1: dropping a fence row is a gbrain-managed fence edit, not authorship: the page keeps its tier and origin.
await withPageTierKept(tx, { sourceId, slug: page.slug }, () => tx.executeRaw(`UPDATE pages SET compiled_truth=$3,timeline=$4,content_hash=$5,updated_at=now(),text_projection_revision=NULL,embedding_signature=NULL
WHERE source_id=$1 AND id=$2`, [sourceId, page.id, compiled, timeline, hash]));
- rewritten.push(page.slug);
+ out.rewritten.push(page.slug);
}
- return rewritten;
+ return out;
}
/** Redact the row from every retained snapshot that carries the claim; returns redacted and still-carrying (prose) counts. */
-async function redactPageVersions(tx: BrainEngine, sourceId: string, claim: string, pageIds: number[]): Promise<{ redacted: number; prose: Array<{ slug: string; version_id: number }> }> {
+async function redactPageVersions(tx: BrainEngine, sourceId: string, claim: string, pageIds: number[]):
+ Promise<{ redacted: number; prose: Array<{ slug: string; version_id: number }>; segmentedPages: number[]; replaced: Uint8Array[] }> {
const needle = claim.toLowerCase();
const rows = await tx.executeRaw<{ id: number; slug: string; compiled_truth: string; timeline: string | null }>(`SELECT v.id,p.slug,v.compiled_truth,v.timeline
FROM page_versions v JOIN pages p ON p.id=v.page_id
- WHERE p.source_id=$1 AND (v.page_id=ANY($3::int[]) OR strpos(lower(v.compiled_truth),$2)>0 OR strpos(lower(COALESCE(v.timeline,'')),$2)>0)
+ WHERE p.source_id=$1 AND v.body_storage='inline' AND (v.page_id=ANY($3::int[]) OR strpos(lower(v.compiled_truth),$2)>0 OR strpos(lower(COALESCE(v.timeline,'')),$2)>0)
ORDER BY v.id LIMIT 5000`, [sourceId, needle, pageIds]);
let redacted = 0;
const prose: Array<{ slug: string; version_id: number }> = [];
@@ -188,7 +218,49 @@ async function redactPageVersions(tx: BrainEngine, sourceId: string, claim: stri
}
if (compiled.toLowerCase().includes(needle) || timeline.toLowerCase().includes(needle)) prose.push({ slug: v.slug, version_id: Number(v.id) });
}
- return { redacted, prose };
+ // Wave B (spec 11): a segmented version references a generation; that generation is rebuilt with the rows dropped.
+ const segmented = await tx.executeRaw<{ id: number; page_id: number; generation: number; slug: string; title: string; type: string;
+ frontmatter: Record<string, unknown>; tags: string[] | null }>(`SELECT v.id,v.page_id,v.body_generation AS generation,p.slug,v.title,v.type,v.frontmatter,v.tags
+ FROM page_versions v JOIN pages p ON p.id=v.page_id
+ WHERE p.source_id=$1 AND v.body_storage='segmented' AND (v.page_id=ANY($3::int[]) OR ${SEGMENTED_VERSION_CARRIES})
+ ORDER BY v.id LIMIT 5000`, [sourceId, needle, pageIds]);
+ const done = new Set<string>();
+ const replaced: Uint8Array[] = [];
+ for (const v of segmented) {
+ const pageId = Number(v.page_id), generation = Number(v.generation);
+ if (!done.has(`${pageId}:${generation}`)) {
+ done.add(`${pageId}:${generation}`);
+ const shas = await rewriteSegmentedGeneration(tx, pageId, generation, fence => dropPurgedFenceRows(tx, sourceId, fence, v.slug),
+ { title: v.title, type: v.type, frontmatter: v.frontmatter ?? {}, tags: v.tags ?? [] });
+ if (shas) { redacted++; replaced.push(...shas); }
+ }
+ if (await segmentedBodyContains(tx, pageId, sourceId, [claim], { generation }) === true) prose.push({ slug: v.slug, version_id: Number(v.id) });
+ }
+ return { redacted, prose, segmentedPages: [...new Set(segmented.map(v => Number(v.page_id)))], replaced };
+}
+
+/**
+ * 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).
+ */
+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 }> {
+ const cancelled = await cancelRequestsHoldingStagings(tx, plan.held, ownRequest);
+ let parts = 0;
+ const 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)]));
+ 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 });
+ const texts = (await tx.executeRaw(`DELETE FROM page_segment_texts d WHERE (d.source_id,d.sha256) IN (SELECT t.source_id,t.sha256 FROM page_segment_texts t
+ WHERE t.source_id=$1 AND NOT EXISTS (SELECT 1 FROM page_body_manifest m WHERE m.source_id=t.source_id AND m.sha256=t.sha256) OFFSET 0)
+ AND (d.sha256=ANY(SELECT decode(h,'hex') FROM unnest($2::text[]) AS h) OR strpos(lower(convert_from(d.body,'UTF8')),$3)>0) RETURNING 1`,
+ [sourceId, replaced.map(sha => Buffer.from(sha).toString('hex')), claim.toLowerCase()])).length;
+ return { texts, stagings: plan.stagings.length, parts, cancelled };
}
interface PurgeParams { id: number; rawId: string; sourceId: string; reason: string | null; allSubjects: boolean; requestId: string }
@@ -269,6 +341,7 @@ export async function submitPurgeFactMutation(ctx: OperationContext, params: Rec
let committedPlan = plan;
let rewritten: string[] = [];
+ let unsealed: string[] = [];
let counts: StoreCount = {};
let prose: Array<{ slug: string; version_id: number }> = [];
const row = await retryWriteAdmission(p.requestId, remaining => ctx.engine.transaction(async tx => {
@@ -289,7 +362,7 @@ export async function submitPurgeFactMutation(ctx: OperationContext, params: Rec
'Run the dry run again, review the new receipt, and confirm that one.');
}
const slug = current.source_markdown_slug ?? current.entity_slug ?? 'memory/unattributed';
- await lockCounters(tx, ['brain', principalKey(principal), ...redactionCounterKeys(committedPlan.requests)]);
+ await lockCounters(tx, ['brain', principalKey(principal), ...redactionCounterKeys([...committedPlan.requests, ...committedPlan.held])]);
const authority = await submissionAuthority({ ...ctx, engine: tx }, PURGE_OPERATION, p.sourceId, source.incarnation, slug);
const admitted = await admitWriteInTransaction(tx, { principal, operation: PURGE_OPERATION, sourceId: p.sourceId, sourceIncarnation: source.incarnation,
slug, requestId: p.requestId, callerIntent, intent: { ...callerIntent, fact_hash: current.fact_hash }, authority, terminalReservation: PURGE_TERMINAL_RESERVATION });
@@ -324,11 +397,16 @@ export async function submitPurgeFactMutation(ctx: OperationContext, params: Rec
const notices = (await tx.executeRaw(`UPDATE core_edit_notices SET base_text=NULL WHERE source_id=$1 AND strpos(lower(base_text),$2)>0 RETURNING 1`,
[p.sourceId, current.fact.toLowerCase()])).length;
const facts = (await tx.executeRaw('DELETE FROM facts WHERE id=ANY($1::bigint[]) AND source_id=$2 RETURNING id', [ids, p.sourceId])).length;
- rewritten = await rewritePageBodies(tx, p.sourceId, plan.pages);
+ const bodies = await rewritePageBodies(tx, p.sourceId, plan.pages);
+ ({ rewritten, unsealed } = bodies);
const pageIds = plan.pages.map(page => page.page_id);
- const chunks = pageIds.length ? (await tx.executeRaw('DELETE FROM content_chunks WHERE page_id=ANY($1::integer[]) RETURNING 1', [pageIds])).length : 0;
+ // A segmented page's flip already retired only the chunks of the occurrences it rewrote.
+ const inline = pageIds.filter(id => !bodies.segmented.includes(id));
+ const chunks = inline.length ? (await tx.executeRaw('DELETE FROM content_chunks WHERE page_id=ANY($1::integer[]) RETURNING 1', [inline])).length : 0;
const versions = await redactPageVersions(tx, p.sourceId, current.fact, pageIds);
prose = versions.prose;
+ const segments = await purgeSegmentStorage(tx, p.sourceId, current.fact, plan, [...new Set([...bodies.segmented, ...versions.segmentedPages])],
+ [...bodies.replaced, ...versions.replaced], admitted.id);
const cache = (await tx.executeRaw('DELETE FROM query_cache RETURNING 1')).length;
const pages = pageIds.length ? await tx.executeRaw<{ id: number; slug: string; knowledge_revision: string }>(
'SELECT id,slug,knowledge_revision::text AS knowledge_revision FROM pages WHERE source_id=$1 AND id=ANY($2::int[]) ORDER BY slug', [p.sourceId, pageIds]) : [];
@@ -341,7 +419,8 @@ export async function submitPurgeFactMutation(ctx: OperationContext, params: Rec
targets: pages.map(page => ({ slug: page.slug, page_id: Number(page.id), revision: page.knowledge_revision })) })]);
counts = { facts, takes, chunks, page_versions: versions.redacted, pages: rewritten.length, persistence_requests: intents,
query_cache: cache, decide_review: review, open_loops: loops, take_proposals: proposals, core_edit_notices: notices,
- write_gate_holds: holdIds.length, write_gate_receipts: gateReceipts,
+ write_gate_holds: holdIds.length, write_gate_receipts: gateReceipts, page_segment_texts: segments.texts,
+ page_body_stagings: segments.stagings, page_body_staging_parts: segments.parts, persistence_requests_cancelled: segments.cancelled,
derived_hidden: Object.values(derived.hidden).reduce((a, b) => a + b, 0) };
return completeWrite(tx, admitted, 'committed', { purge: { fact_id: p.id, hash8: token, fact_hash: current.fact_hash, subject: plan.subject,
visibility: current.visibility, removed: counts, derived: { ...derived, truncated: plan.derived.truncated }, pages: rewritten.length },
@@ -353,6 +432,7 @@ export async function submitPurgeFactMutation(ctx: OperationContext, params: Rec
for (let start = 0; start < slugs.length; start += 100) {
await rebuildPendingPageProjections(ctx.engine, 100, { pages: { sourceId: p.sourceId, slugs: slugs.slice(start, start + 100) } }).catch(() => undefined);
}
+ for (const slug of unsealed) await buildSegmentedProjection(ctx.engine, { sourceId: p.sourceId, slug }).catch(() => undefined);
if (row.state !== 'committed') return { ...(row.outcome ?? {}), request_id: row.request_id, state: row.state, error: row.error_code };
const receipt: PurgeReceipt = await verifyFactPurge(ctx.engine, { target, plan: committedPlan, dryRun: false, removed: counts, prose,
vacuum: params.vacuum === true });
diff --git a/src/core/facts/withdrawal-discovery.ts b/src/core/facts/withdrawal-discovery.ts
index 4fb907d9a6..fb0f99d3be 100644
--- a/src/core/facts/withdrawal-discovery.ts
+++ b/src/core/facts/withdrawal-discovery.ts
@@ -96,6 +96,26 @@ export async function discoverWithdrawalTargets(engine: BrainEngine, sourceId: s
if (pages.length < WITHDRAWAL_LIMITS.batch) break;
after = pages[pages.length - 1].id;
}
+ // Wave B (spec 11): a segmented page's fences live in its segments; only live rows flagged with facts slots are
+ // read, and only each slot's bytes (a fence split by a forced cut is left to the chunk scan below).
+ const slotText = `convert_from(substring(t.body from (s->>'start')::int + 1 for (s->>'end')::int - (s->>'start')::int),'UTF8')`;
+ for (let after = [0, 0]; ;) {
+ if (performance.now() > deadline) refuse();
+ const rows = await engine.executeRaw<{ id: number; occurrence_id: string; slug: string; fences: string[] }>(`SELECT p.id,m.occurrence_id::text AS occurrence_id,p.slug,
+ ARRAY(SELECT ${slotText} FROM jsonb_array_elements(m.facts_slots) s WHERE NOT s ? 'open_start') AS fences
+ FROM page_body_manifest m JOIN pages p ON p.id=m.page_id JOIN page_segment_texts t ON t.source_id=m.source_id AND t.sha256=m.sha256
+ WHERE p.source_id=$1 AND p.body_storage='segmented' AND m.gen_to IS NULL AND m.staging_id IS NULL AND m.facts_slots<>'[]'::jsonb
+ AND (m.page_id,m.occurrence_id)>($3::int,$6::bigint) AND ($5::text[] IS NULL OR p.slug=ANY($5::text[]))
+ AND EXISTS (SELECT 1 FROM jsonb_to_recordset($2::text::jsonb) k(subject text,patterns text[]), jsonb_array_elements(m.facts_slots) s
+ WHERE (k.subject='*' OR k.subject=p.slug) AND NOT s ? 'open_start' AND ${shortlist(slotText)})
+ ORDER BY m.page_id,m.occurrence_id LIMIT $4`, [sourceId, keys, after[0], WITHDRAWAL_LIMITS.batch, subjects, after[1]]);
+ await match(rows.flatMap(row => row.fences.flatMap(fence => [
+ ...withdrawalFenceBlocks(fence).filter(block => !block.parsed.warnings.length).flatMap(block => block.parsed.facts.map(f => ({ id: row.id, slug: row.slug, claim: f.claim, visibility: f.visibility, ambiguous: false }))),
+ ...ambiguousFenceClaims(fence).map(f => ({ id: row.id, slug: row.slug, ...f, ambiguous: true })),
+ ])));
+ if (rows.length < WITHDRAWAL_LIMITS.batch) break;
+ after = [Number(rows[rows.length - 1].id), Number(rows[rows.length - 1].occurrence_id)];
+ }
for (let after = 0; ;) {
if (performance.now() > deadline) refuse();
const chunks = await engine.executeRaw<{ id: number; page_id: number; slug: string; chunk_text: string }>(`SELECT c.id,c.page_id,p.slug,c.chunk_text
diff --git a/src/core/facts/withdrawal.ts b/src/core/facts/withdrawal.ts
index 7ac588c4ac..64de22bd15 100644
--- a/src/core/facts/withdrawal.ts
+++ b/src/core/facts/withdrawal.ts
@@ -6,6 +6,7 @@ import { withdrawnFact, withdrawalFenceBlocks } from './withdrawal-overlay.ts';
import { ambiguousFenceClaims, discoverWithdrawalTargets, withdrawalDiscoveryFailure } from './withdrawal-discovery.ts';
import { dropPurgedFenceRows } from './purge-overlay.ts';
import { privateProvenanceFilterFragment } from '../search/private-visibility.ts';
+import { rewriteLiveSegmentedFences } from '../page-body/segment-rewrite.ts';
export interface WithdrawalCommit {
withdrawn: boolean;
@@ -86,12 +87,19 @@ export async function recordFactWithdrawal(
if (opts.semanticReview !== false && reviewWithdrawOn(await tx.getConfig(REVIEW_WITHDRAW_KEY))) {
await tx.executeRaw(`INSERT INTO decide_review_queue(kind,source_id,a_ref) VALUES ('withdraw',$1,$2) ON CONFLICT DO NOTHING`, [sourceId, String(id)]);
}
+ // Wave B (spec 11): a segmented page's withdrawn rows are struck in the segment holding the fence, a new
+ // generation whose flip retires only the chunks of the occurrences it rewrote.
+ const segmented = affected.length ? await tx.executeRaw<{ id: number; slug: string }>(`SELECT id,slug FROM pages
+ WHERE source_id=$1 AND slug=ANY($2::text[]) AND body_storage='segmented'`, [sourceId, affected.map(page => page.slug)]) : [];
+ for (const page of segmented) await rewriteLiveSegmentedFences(tx, Number(page.id), fence => preserveWithdrawnFenceRows(tx, sourceId, fence, page.slug));
// Logical revision and projection invalidation commit with the withdrawal.
// The revision trigger queues durable rebuild work even for unmanaged calls.
- const pages = affected.length ? await tx.executeRaw<{ id: number; slug: string; knowledge_revision: string }>(
+ const inline = affected.length ? await tx.executeRaw<{ id: number; slug: string; knowledge_revision: string }>(
`UPDATE pages SET knowledge_revision=gen_random_uuid(),text_projection_revision=NULL,embedding_signature=NULL
- WHERE source_id=$1 AND slug=ANY($2::text[]) RETURNING id,slug,knowledge_revision`, [sourceId, affected.map(page => page.slug)]) : [];
- if (pages.length) await tx.executeRaw('DELETE FROM content_chunks WHERE page_id=ANY($1::integer[])', [pages.map(page => page.id)]);
+ WHERE source_id=$1 AND slug=ANY($2::text[]) AND body_storage<>'segmented' RETURNING id,slug,knowledge_revision`, [sourceId, affected.map(page => page.slug)]) : [];
+ if (inline.length) await tx.executeRaw('DELETE FROM content_chunks WHERE page_id=ANY($1::integer[])', [inline.map(page => page.id)]);
+ const pages = [...inline, ...segmented.length ? await tx.executeRaw<{ id: number; slug: string; knowledge_revision: string }>(
+ 'SELECT id,slug,knowledge_revision FROM pages WHERE id=ANY($1::int[])', [segmented.map(page => page.id)]) : []];
if (opts.requestId) {
await tx.executeRaw(`INSERT INTO persistence_effects(request_id,kind,data,source_id,source_incarnation,worktree_id)
SELECT $1::uuid,k.kind,$3::text::jsonb,s.id,s.incarnation,b.worktree_id
diff --git a/src/core/page-body/segment-rewrite.ts b/src/core/page-body/segment-rewrite.ts
new file mode 100644
index 0000000000..4efe05d015
--- /dev/null
+++ b/src/core/page-body/segment-rewrite.ts
@@ -0,0 +1,239 @@
+/**
+ * Fence rewrites of segmented bodies (Wave B, spec 6.4 and 11): forget strikes
+ * and purge drops fence rows of a segmented page without holding its body as
+ * one string. Only the facts and takes regions the segmenter stored
+ * (`protected_regions`) are decoded and handed to the transform; a region that
+ * crosses a forced cut is joined with its neighbours, up to the single-string
+ * ceiling. A changed live body is staged again through `prepareSegmentedBody`
+ * from a stream of its segments with the changed ones replaced, so unchanged
+ * segments keep their rows, texts and chunks, and publishes through the
+ * generation flip in the caller's transaction. A changed retained generation
+ * (purge) is rebuilt under its own number. Memory stays O(segment) on every
+ * path.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { isQuarantined } from '../quarantine.ts';
+import { PAGE_MAX_BYTES } from '../page-size-policy.ts';
+import { maintenanceAttribution } from '../persistence/attribution.ts';
+import { applySegmentedBody, sealSegmentedPage } from '../persistence/segmented-apply.ts';
+import { withPageTierKept } from '../trust/fence-append.ts';
+import { prepareSegmentedBody, readSegmentedBody, type SegmentedStagingOwner } from './ingest.ts';
+import { readPageBodyPolicy, STAGE_BATCH_BYTES } from './limits.ts';
+import { pageBodySegmentedError } from './page-shape.ts';
+import { ContentHashStream } from './content-hash-stream.ts';
+import type { StoredRegion } from './segmenter.ts';
+import type { BodyRegion, JsonObject, ManifestRow } from './types.ts';
+
+/** Rewrites one fence (the text of a stored facts or takes region, markers included). */
+export type FenceTransform = (fence: string) => Promise<string>;
+
+/** Rows `from..to` of a generation, replaced by `bytes`. */
+interface FenceUnit { from: number; to: number; bytes: Uint8Array }
+
+const utf8 = new TextDecoder('utf-8', { fatal: true });
+const hex = (bytes: Uint8Array) => Buffer.from(bytes).toString('hex');
+const fenceRegions = (row: ManifestRow) => (row.protectedRegions as StoredRegion[]).filter(r => r.kind === 'facts' || r.kind === 'takes');
+/** The region runs on into the next segment (it crosses a forced cut there). */
+const runsOn = (r: StoredRegion) => r.open_start !== undefined && r.open_end === undefined;
+
+/** Every fence unit of `rows` the transform changes, in order. Reads only segments holding a fence. */
+async function changedUnits(engine: BrainEngine, sourceId: string, rows: readonly ManifestRow[], transform: FenceTransform): Promise<FenceUnit[]> {
+ const units: FenceUnit[] = [];
+ for (let from = 0; from < rows.length; from++) {
+ if (!fenceRegions(rows[from]!).length) continue;
+ let to = from;
+ while (to + 1 < rows.length && rows[to + 1]!.region === rows[from]!.region && fenceRegions(rows[to]!).some(runsOn)) to++;
+ const span = rows.slice(from, to + 1);
+ if (span.reduce((n, row) => n + row.byteLen, 0) > PAGE_MAX_BYTES) {
+ const [page] = await engine.executeRaw<{ slug: string }>('SELECT slug FROM pages WHERE id=$1', [span[0]!.pageId]);
+ throw pageBodySegmentedError({ slug: page?.slug, source_id: sourceId }, 'fence rewrite of a fence larger than the single-string ceiling');
+ }
+ const texts = await engine.readSegmentTexts(sourceId, span.map(row => row.sha256));
+ const raw = Buffer.concat(span.map(row => {
+ const text = texts.get(hex(row.sha256));
+ if (!text) throw new Error(`Segment text ${hex(row.sha256)} of page ${row.pageId} is missing.`);
+ return text;
+ }));
+ const regions: Array<{ start: number; end: number }> = [];
+ let offset = 0;
+ for (const row of span) {
+ for (const r of fenceRegions(row)) {
+ const last = regions[regions.length - 1];
+ if (last && last.end === offset + r.start) last.end = offset + r.end;
+ else regions.push({ start: offset + r.start, end: offset + r.end });
+ }
+ offset += row.byteLen;
+ }
+ const parts: Buffer[] = [];
+ let cursor = 0, changed = false;
+ for (const r of regions) {
+ const fence = raw.subarray(r.start, r.end).toString('utf8');
+ const next = await transform(fence);
+ parts.push(raw.subarray(cursor, r.start), Buffer.from(next, 'utf8'));
+ cursor = r.end;
+ if (next !== fence) changed = true;
+ }
+ if (changed) units.push({ from, to, bytes: Buffer.concat([...parts, raw.subarray(cursor)]) });
+ from = to;
+ }
+ return units;
+}
+
+/** One region of a generation's stored stream with the changed units replaced, read one segment batch at a time. */
+async function* rewrittenRegion(engine: BrainEngine, sourceId: string, rows: readonly ManifestRow[], units: readonly FenceUnit[], region: BodyRegion): AsyncIterable<Uint8Array> {
+ const unitAt = new Map(units.map(unit => [unit.from, unit]));
+ const batchBytes = STAGE_BATCH_BYTES[engine.kind];
+ let batch: ManifestRow[] = [], bytes = 0;
+ async function* flush(): AsyncIterable<Uint8Array> {
+ const texts = await engine.readSegmentTexts(sourceId, batch.map(row => row.sha256));
+ for (const row of batch) {
+ const text = texts.get(hex(row.sha256));
+ if (!text) throw new Error(`Segment text ${hex(row.sha256)} of page ${row.pageId} is missing.`);
+ yield text;
+ }
+ batch = []; bytes = 0;
+ }
+ for (let i = 0; i < rows.length; i++) {
+ const row = rows[i]!;
+ if (row.region !== region) continue;
+ const unit = unitAt.get(i);
+ if (unit) {
+ yield* flush();
+ yield unit.bytes;
+ i = unit.to;
+ continue;
+ }
+ if (batch.length && bytes + row.byteLen > batchBytes) yield* flush();
+ batch.push(row);
+ bytes += row.byteLen;
+ }
+ if (batch.length) yield* flush();
+}
+
+const bodyBytesOf = (rows: readonly ManifestRow[], units: readonly FenceUnit[]) => rows.reduce((n, row) => n + row.byteLen, 0)
+ + units.reduce((n, unit) => n + unit.bytes.length - rows.slice(unit.from, unit.to + 1).reduce((m, row) => m + row.byteLen, 0), 0);
+
+async function rewriteOwner(engine: BrainEngine): Promise<SegmentedStagingOwner> {
+ const { principal } = await maintenanceAttribution(engine);
+ return { kind: 'edit', principalKind: principal.kind, principalId: principal.id, baseRevision: null };
+}
+
+/** The replaced rows' segment shas: texts the rewrite stopped referencing from this generation. */
+const replacedShas = (rows: readonly ManifestRow[], units: readonly FenceUnit[]) => units.flatMap(unit => rows.slice(unit.from, unit.to + 1).map(row => row.sha256));
+
+export interface LiveFenceRewrite {
+ /** Segment shas the old generation referenced in place of the rewritten units. */
+ replaced: Uint8Array[];
+ /** False when the page was left unsealed (its projection runs after commit: `buildSegmentedProjection`). */
+ sealed: boolean;
+}
+
+/**
+ * Rewrite the fences of a segmented page's live body through `transform`, in
+ * the caller's transaction: a new generation whose unchanged segments keep
+ * their rows and chunks, and whose rewritten segments get new occurrences
+ * (their chunks staged here, the old ones retired by the flip). A fence edit
+ * is not authorship, so the page keeps its trust tier; a soft-deleted page
+ * stays deleted. Null when no fence changed (nothing is written).
+ */
+export async function rewriteLiveSegmentedFences(tx: BrainEngine, pageId: number, transform: FenceTransform): Promise<LiveFenceRewrite | null> {
+ const [page] = await tx.executeRaw<{ id: number; slug: string; source_id: string; title: string; type: string; page_kind: string; frontmatter: JsonObject | null;
+ body_generation: number | string; body_flags: JsonObject | null; body_storage: string; deleted_at: string | null; tags: string[] }>(`SELECT p.id,p.slug,p.source_id,p.title,
+ p.type,p.page_kind,p.frontmatter,p.body_generation,p.body_flags,p.body_storage,p.deleted_at,
+ COALESCE((SELECT jsonb_agg(t.tag ORDER BY t.tag) FROM tags t WHERE t.page_id=p.id),'[]'::jsonb) AS tags FROM pages p WHERE p.id=$1`, [pageId]);
+ if (page?.body_storage !== 'segmented') return null;
+ const sourceId = page.source_id, slug = page.slug, frontmatter = page.frontmatter ?? {};
+ const rows = await tx.readManifest(pageId);
+ const units = await changedUnits(tx, sourceId, rows, transform);
+ if (!units.length) return null;
+ const generation = Number(page.body_generation);
+ const prepared = await prepareSegmentedBody(tx, { sourceId, slug, title: page.title, type: page.type, frontmatter, tags: page.tags,
+ live: { id: pageId, generation, storage: 'segmented', title: page.title, type: page.type, flags: page.body_flags },
+ 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),
+ owner: await rewriteOwner(tx), chunking: { quarantined: isQuarantined(frontmatter), corpusGeneration: null, tier: 'none' } });
+ const { flipRetireMaxRows } = await readPageBodyPolicy(tx);
+ const applied = await withPageTierKept(tx, { sourceId, slug }, () => applySegmentedBody(tx, { slug, sourceId, pageId, prepared, promotion: false,
+ retireMaxRows: flipRetireMaxRows, meta: { title: page.title, type: page.type as never, frontmatter, page_kind: page.page_kind as never } }));
+ if (page.deleted_at) await tx.executeRaw('UPDATE pages SET deleted_at=$2 WHERE id=$1', [pageId, page.deleted_at]);
+ if (applied.complete) await sealSegmentedPage(tx, pageId);
+ return { replaced: replacedShas(rows, units), sealed: applied.complete };
+}
+
+const MANIFEST_COLUMNS = `page_id,occurrence_id,seq,region,source_id,sha256,byte_start,byte_len,line_start,line_count,cut_kind,entry_state,
+ protected_regions,facts_slots,static_proj_bytes,static_proj_lines,outline,date_min,date_max,hash_state`;
+
+/**
+ * Rebuild retained generation `generation` of a segmented page with its fences
+ * rewritten (purge of a version), in the caller's transaction. The generation
+ * gets rows of its own: rows it shared with neighbouring generations keep
+ * 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.
+ */
+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]);
+ 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;
+ 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),
+ owner: await rewriteOwner(tx), chunking: { quarantined: true, corpusGeneration: null, tier: 'none' } });
+ const staging = prepared.stagingId, next = generation + 1;
+ // The part of each shared row after this generation moves to a copy (staged, so the live-seq index sees one live row);
+ // the part before it ends here; rows that began here go. Then the rebuilt rows take [generation, next).
+ await tx.executeRaw(`INSERT INTO page_body_manifest (${MANIFEST_COLUMNS},gen_from,gen_to,staging_id) SELECT ${MANIFEST_COLUMNS},$3::bigint,gen_to,$4::uuid
+ FROM page_body_manifest WHERE page_id=$1 AND staging_id IS NULL AND gen_from<=$2 AND (gen_to IS NULL OR gen_to>$3)`, [pageId, generation, next, staging]);
+ await tx.executeRaw('UPDATE page_body_manifest SET gen_to=$2 WHERE page_id=$1 AND staging_id IS NULL AND gen_from<$2 AND (gen_to IS NULL OR gen_to>$2)', [pageId, generation]);
+ await tx.executeRaw('DELETE FROM page_body_manifest WHERE page_id=$1 AND staging_id IS NULL AND gen_from=$2', [pageId, generation]);
+ await tx.stageManifestRows(prepared.createRows!.map(row => ({ ...row, pageId, genFrom: generation })));
+ await tx.executeRaw(`UPDATE page_body_manifest SET staging_id=NULL, gen_to=CASE WHEN gen_from=$2 THEN $3 ELSE gen_to END
+ WHERE page_id=$1 AND staging_id=$4::uuid`, [pageId, generation, next, staging]);
+ await tx.setBodyStagingState(staging, 'committed');
+ await tx.executeRaw(`UPDATE page_versions SET content_hash=$3,body_bytes=$4 WHERE page_id=$1 AND body_generation=$2 AND body_storage='segmented'`,
+ [pageId, generation, prepared.body.content_hash, prepared.body.body_bytes]);
+ return replacedShas(rows, units);
+}
+
+/**
+ * `content_hash` of a segmented page's body at `generation` with its fences
+ * rewritten (as an import through the purge overlay would hash it), streamed;
+ * null when no fence changes, so the stored hash stands.
+ */
+export async function rewrittenContentHash(engine: BrainEngine, pageId: number, sourceId: string, generation: number, transform: FenceTransform,
+ meta: { title: unknown; type: unknown; frontmatter: Record<string, unknown>; tags: string[] }): Promise<string | null> {
+ const rows = await engine.readManifest(pageId, { generation });
+ const units = await changedUnits(engine, sourceId, rows, transform);
+ if (!units.length) return null;
+ const hash = ContentHashStream.begin(meta);
+ for await (const bytes of rewrittenRegion(engine, sourceId, rows, units, 'truth')) hash.pushTruth(utf8.decode(bytes));
+ for await (const bytes of rewrittenRegion(engine, sourceId, rows, units, 'timeline')) hash.pushTimeline(utf8.decode(bytes));
+ return hash.finish(meta);
+}
+
+/**
+ * Whether a segmented body (live, or `generation`) contains any of `needles`,
+ * case-insensitively, within one region: each segment is lower-cased on its
+ * own and searched with the tail of the previous one prepended (a needle split
+ * by a cut is found). `'deadline'` when `deadline` (performance.now()) passed.
+ */
+export async function segmentedBodyContains(engine: BrainEngine, pageId: number, sourceId: string, needles: readonly string[],
+ opts: { generation?: number; deadline?: number } = {}): Promise<boolean | 'deadline'> {
+ const lowered = needles.map(n => n.toLowerCase()).filter(Boolean);
+ if (!lowered.length) return false;
+ const keep = Math.max(...lowered.map(n => n.length)) - 1;
+ let carry = '', region: BodyRegion | null = null;
+ for await (const part of readSegmentedBody(engine, pageId, sourceId, opts.generation === undefined ? {} : { generation: opts.generation })) {
+ if (opts.deadline !== undefined && performance.now() > opts.deadline) return 'deadline';
+ if (part.region !== region) { carry = ''; region = part.region; }
+ const text = carry + utf8.decode(part.bytes).toLowerCase();
+ if (lowered.some(n => text.includes(n))) return true;
+ carry = keep > 0 ? text.slice(-keep) : '';
+ }
+ return false;
+}
diff --git a/src/core/page-state/credential-reseal.ts b/src/core/page-state/credential-reseal.ts
index 2c9063b7da..bc89038dfd 100644
--- a/src/core/page-state/credential-reseal.ts
+++ b/src/core/page-state/credential-reseal.ts
@@ -9,13 +9,17 @@
*/
import type { BrainEngine } from '../engine.ts';
import { resealSafeChunks } from './projections.ts';
+import { buildSegmentedProjection } from '../page-body/projection.ts';
import { PageRevisionConflictError } from './types.ts';
const KEY_MARKER = `'-----(BEGIN|END) [A-Z ]*PRIVATE KEY-----'`;
const REBUILDABLE = `(p.page_kind='markdown' OR (p.page_kind='code' AND COALESCE(p.frontmatter->>'file',p.source_path) IS NOT NULL))`;
+/** Wave B: a segmented page's private keys are its live manifest rows' `pem` regions (its body columns are NULL). */
+const SEGMENTED_KEYS = `EXISTS (SELECT 1 FROM page_body_manifest m WHERE m.page_id=p.id AND m.gen_to IS NULL AND m.staging_id IS NULL
+ AND m.protected_regions @> '[{"kind":"pem"}]'::jsonb)`;
const PENDING = `p.deleted_at IS NULL AND p.page_kind IN ('markdown','code')
AND p.text_projection_revision IS DISTINCT FROM p.knowledge_revision
- AND (p.compiled_truth ~ ${KEY_MARKER} OR COALESCE(p.timeline,'') ~ ${KEY_MARKER})`;
+ AND (p.compiled_truth ~ ${KEY_MARKER} OR COALESCE(p.timeline,'') ~ ${KEY_MARKER} OR (p.body_storage='segmented' AND ${SEGMENTED_KEYS}))`;
export interface CredentialPending { rebuildable: number; kept: number }
@@ -33,13 +37,17 @@ export interface CredentialResealResult { resealed: number; superseded: number;
/** Re-seal every rebuildable pending page, one page per transaction, so an interrupted run resumes where it stopped. */
export async function resealCredentialProjections(engine: BrainEngine): Promise<CredentialResealResult> {
- const rows = await engine.executeRaw<{ source_id: string; slug: string }>(`SELECT p.source_id,p.slug
+ const rows = await engine.executeRaw<{ source_id: string; slug: string; body_storage: string }>(`SELECT p.source_id,p.slug,p.body_storage
FROM pages p JOIN sources s ON s.id=p.source_id AND s.archived IS NOT TRUE
WHERE ${PENDING} AND ${REBUILDABLE} ORDER BY p.id`);
const result: CredentialResealResult = { resealed: 0, superseded: 0, failed: 0, kept: 0 };
for (const row of rows) {
try {
- if (await resealSafeChunks(engine, row.slug, row.source_id)) result.resealed++;
+ // A segmented page's chunks are built from its stored pem regions; its projection rebuild re-seals it.
+ const resealed = row.body_storage === 'segmented'
+ ? (await buildSegmentedProjection(engine, { sourceId: row.source_id, slug: row.slug })).sealed
+ : await resealSafeChunks(engine, row.slug, row.source_id);
+ if (resealed) result.resealed++;
else result.superseded++;
} catch (error) {
if (error instanceof PageRevisionConflictError) { result.superseded++; continue; }
diff --git a/src/core/persistence/intent-redaction.ts b/src/core/persistence/intent-redaction.ts
index 4bd4db0afb..a573b4e0c6 100644
--- a/src/core/persistence/intent-redaction.ts
+++ b/src/core/persistence/intent-redaction.ts
@@ -32,7 +32,7 @@ import { opError } from '../ops/contract.ts';
import type { BrainEngine } from '../engine.ts';
import { enterClaimStep, type ClaimPhaseClock } from './claim-phase.ts';
import { EFFECT_BYTES_SQL, retainedReceiptBytes } from './receipt-bytes.ts';
-import { lockCounters } from './journal.ts';
+import { completeWrite, lockCounters } from './journal.ts';
import { isTerminal, principalKey, requestPrincipal, type WriteRequest } from './model.ts';
export interface IntentRedactionTarget { id: string; principal_kind: string; principal_id: string }
@@ -174,6 +174,41 @@ export async function findRequestsForSlugs(engine: BrainEngine, sourceId: string
WHERE source_id=$1 AND slug=ANY($2::text[]) AND NOT compacted AND intent IS NOT NULL ORDER BY sequence LIMIT $3`, [sourceId, [...slugs], limit]);
}
+/**
+ * Wave B (spec 11): unfinished requests of `sourceId` whose intent references one of `stagingIds` by
+ * `body_ref` (the request publishes that staged body, so its text lives in the staging, not the intent).
+ */
+export async function findRequestsHoldingStagings(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, stagingIds: readonly string[]): Promise<IntentRedactionTarget[]> {
+ if (!stagingIds.length) return [];
+ return engine.executeRaw<IntentRedactionTarget>(`SELECT id::text AS id,principal_kind,principal_id FROM persistence_requests
+ WHERE source_id=$1 AND state IN ('queued','running','recovering') AND intent->'body_ref'->>'staging_id'=ANY($2::text[]) ORDER BY sequence`, [sourceId, [...stagingIds]]);
+}
+
+/**
+ * Cancel the queued requests of `targets` with `purged_content` inside the purge's transaction (the caller holds their
+ * counter locks): the staged body they would publish is being purged. A request already claimed (running,
+ * recovering, or with a recovery record) refuses the purge with retryable `purge_blocked_pending_recovery`.
+ */
+export async function cancelRequestsHoldingStagings(tx: BrainEngine, targets: readonly IntentRedactionTarget[], exclude?: string): Promise<number> {
+ const ids = targets.map(t => t.id).filter(id => id !== exclude);
+ if (!ids.length) return 0;
+ const rows = await tx.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE id=ANY($1::uuid[]) ORDER BY id FOR UPDATE', [ids]);
+ const blocked = rows.find(row => (!isTerminal(row) && row.state !== 'queued') || row.recovery);
+ if (blocked) {
+ throw opError('purge_blocked_pending_recovery', 'A pending write is publishing a staged body that holds this content, so nothing was purged.',
+ `Request ${blocked.request_id} (${blocked.operation} on ${blocked.slug}, state ${blocked.state}) is publishing the staged body. Wait for it to finish, then retry the purge with the same request id.`,
+ { fix: { argv: ['gbrain', 'write-request', '--', blocked.request_id], consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'Shows the blocking write\'s state, read-only; retry the purge once it is final.' } });
+ }
+ let cancelled = 0;
+ for (const row of rows) {
+ if (isTerminal(row)) continue;
+ await completeWrite(tx, row, 'cancelled', {}, { code: 'purged_content', message: 'Cancelled: the staged body this request would publish held purged content.' });
+ cancelled++;
+ }
+ return cancelled;
+}
+
/** The counter keys an affected request set touches; lock them before admitting the purge's own request. */
export function redactionCounterKeys(targets: readonly IntentRedactionTarget[]): string[] {
return [...new Set(targets.map(t => principalKey({ kind: t.principal_kind as WriteRequest['principal_kind'], id: t.principal_id })))];
diff --git a/src/core/persistence/page-purge.ts b/src/core/persistence/page-purge.ts
index 5ba3f2a286..eae705309d 100644
--- a/src/core/persistence/page-purge.ts
+++ b/src/core/persistence/page-purge.ts
@@ -39,6 +39,9 @@ import { faultPoint } from './fault-points.ts';
import { findRequestsForSlugs, recheckRequestsCarrying, redactRequestIntents, sweepRequestsCarrying, type JournalSweep } from './intent-redaction.ts';
import { dropPurgedFenceRows } from '../facts/purge-overlay.ts';
import { contentHash } from '../utils.ts';
+import { isSegmentedPage } from '../page-body/page-shape.ts';
+import { rewrittenContentHash } from '../page-body/segment-rewrite.ts';
+import type { PagePurgeContext } from '../facts/purge-verify.ts';
export const PURGE_RESIDUALS = 'Removed from live stores: the page row with its chunks, versions, takes, timeline, links and raw data, the facts filed on it (tombstoned), '
+ 'its take proposals, open loops and core notices, stored write intents for the slug and its attached file records. Still out of reach: the brain repository\'s '
@@ -55,7 +58,7 @@ function hostOnly(command: string) {
* needles) and row ids, keyed by `<source_id>:<request_id>`, in this process only. A receipt built where the
* map has no entry reports the prose probe as unverified.
*/
-const purgeContext = new Map<string, { needles: string[]; factIds: number[]; pageId: number; paths: string[] }>();
+const purgeContext = new Map<string, PagePurgeContext>();
const PURGE_CONTEXT_LIMIT = 64;
const purgeReceipts = new Map<string, { receipt: Record<string, unknown>; purge: Record<string, unknown> }>();
@@ -116,7 +119,7 @@ async function journalLookup<T>(row: WriteRequest, point: PurgeLookupPoint, slug
export async function purgePageInTransaction(tx: BrainEngine, row: WriteRequest, snapshot: PageSnapshot, prepared: PreparedPagePurge): Promise<Record<string, unknown>> {
const page = snapshot.page, sourceId = row.source_id, slug = page.slug;
const actor = `${row.principal_kind}:${row.principal_id}`;
- const [stored] = await tx.executeRaw<{ content_hash: string | null }>('SELECT content_hash FROM pages WHERE id=$1', [page.id]);
+ const [stored] = await tx.executeRaw<{ content_hash: string | null; body_generation: number | string }>('SELECT content_hash,body_generation FROM pages WHERE id=$1', [page.id]);
const storedHash = stored?.content_hash ?? null;
await tx.executeRaw(`INSERT INTO fact_purges(source_id,visibility,subject,fact_hash,request_id,actor,reason)
SELECT DISTINCT source_id,visibility,COALESCE(entity_slug,'*'),gbrain_fact_fingerprint(fact),$3::uuid,$4,'page purge'
@@ -126,16 +129,28 @@ export async function purgePageInTransaction(tx: BrainEngine, row: WriteRequest,
// Tombstone the content hash of the page and of every retained version, each as an import of that body would
// compute it and as the purge overlay leaves it (the overlay now drops this page's tombstoned fence rows), so
// neither the stale file nor an older version of it imports again under any slug.
- const versions = await tx.executeRaw<Record<string, unknown>>(`SELECT title,type,compiled_truth,timeline,frontmatter,tags,source_path FROM page_versions
- WHERE page_id=$1 ORDER BY id DESC LIMIT 1000`, [page.id]);
- const bodies = [{ ...page, tags: snapshot.tags }, ...versions.map(v => ({ title: String(v.title ?? ''), type: v.type as never,
- compiled_truth: String(v.compiled_truth ?? ''), timeline: String(v.timeline ?? ''), frontmatter: (v.frontmatter ?? {}) as Record<string, unknown>,
- tags: Array.isArray(v.tags) ? v.tags.map(String) : [] }))];
+ const versions = await tx.executeRaw<Record<string, unknown>>(`SELECT title,type,compiled_truth,timeline,frontmatter,tags,source_path,body_storage,body_generation,content_hash
+ FROM page_versions WHERE page_id=$1 ORDER BY id DESC LIMIT 1000`, [page.id]);
+ const meta = (v: Record<string, unknown>) => ({ title: String(v.title ?? ''), type: v.type as never, frontmatter: (v.frontmatter ?? {}) as Record<string, unknown>,
+ tags: Array.isArray(v.tags) ? v.tags.map(String) : [] });
const hashes = new Set<string>(storedHash ? [storedHash] : []);
- for (const body of bodies) {
+ // Wave B (spec 5, 11): a segmented body is never held whole: its stored hash (and a version's) is the import hash, and
+ // the purge-overlaid hash is streamed from its segments.
+ const overlaid = (fence: string) => dropPurgedFenceRows(tx, sourceId, fence, slug);
+ const segmented = isSegmentedPage(page) ? [{ generation: Number(stored?.body_generation), meta: { ...meta(page as never), tags: snapshot.tags } }] : [];
+ const inline = isSegmentedPage(page) ? [] : [{ ...page, tags: snapshot.tags }];
+ for (const v of versions) {
+ if (v.body_storage !== 'segmented') { inline.push({ ...meta(v), compiled_truth: String(v.compiled_truth ?? ''), timeline: String(v.timeline ?? '') } as never); continue; }
+ if (typeof v.content_hash === 'string') hashes.add(v.content_hash);
+ segmented.push({ generation: Number(v.body_generation), meta: meta(v) });
+ }
+ for (const body of inline) {
hashes.add(contentHash(body));
- hashes.add(contentHash({ ...body, compiled_truth: await dropPurgedFenceRows(tx, sourceId, body.compiled_truth, slug),
- timeline: await dropPurgedFenceRows(tx, sourceId, body.timeline ?? '', slug) }));
+ hashes.add(contentHash({ ...body, compiled_truth: await overlaid(body.compiled_truth), timeline: await overlaid(body.timeline ?? '') }));
+ }
+ for (const body of segmented) {
+ const hash = await rewrittenContentHash(tx, page.id, sourceId, body.generation, overlaid, body.meta);
+ if (hash) hashes.add(hash);
}
await tx.executeRaw(`INSERT INTO page_purges(source_id,content_hash,slug,request_id) SELECT $1,h,$3,$4::uuid FROM unnest($2::text[]) AS h
ON CONFLICT (source_id,content_hash) DO UPDATE SET slug=EXCLUDED.slug,request_id=EXCLUDED.request_id,purged_at=now()`, [sourceId, [...hashes], slug, row.id]);
@@ -181,10 +196,17 @@ export async function purgePageInTransaction(tx: BrainEngine, row: WriteRequest,
(SELECT count(*)::int FROM takes WHERE page_id=$1) AS takes, (SELECT count(*)::int FROM timeline_entries WHERE page_id=$1) AS timeline`, [page.id]);
Object.assign(removed, { content_chunks: cascade?.chunks ?? 0, page_versions: cascade?.versions ?? 0, takes: cascade?.takes ?? 0, timeline_entries: cascade?.timeline ?? 0, pages: 1 });
const paths = [...new Set([page.source_path, ...versions.map(v => v.source_path as string | null)].filter((p): p is string => !!p))].slice(0, 64);
+ // Wave B (spec 11): the segment texts only this page's manifests reference go with it, in this transaction, and so do
+ // its stagings (one of a create has no page row to cascade from).
+ const shas = (await tx.executeRaw<{ sha: string }>(`SELECT DISTINCT encode(sha256,'hex') AS sha FROM page_body_manifest WHERE page_id=$1`, [page.id])).map(r => r.sha);
+ removed.page_body_manifest = (await tx.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM page_body_manifest WHERE page_id=$1', [page.id]))[0]?.n ?? 0;
+ removed.page_body_stagings = await count('DELETE FROM page_body_stagings WHERE source_id=$1 AND (slug=$2 OR page_id=$3) RETURNING 1', [sourceId, slug, page.id]);
await tx.deletePage(slug, { sourceId });
+ removed.page_segment_texts = shas.length ? await count(`DELETE FROM page_segment_texts t WHERE t.source_id=$1 AND 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) RETURNING 1`, [sourceId, shas]) : 0;
const key = `${sourceId}:${row.request_id}`;
purgeContext.delete(key);
- purgeContext.set(key, { needles, factIds, pageId: page.id, paths });
+ purgeContext.set(key, { needles, factIds, pageId: page.id, paths, segmentShas: shas.slice(0, 4096) });
while (purgeContext.size > PURGE_CONTEXT_LIMIT) purgeContext.delete(purgeContext.keys().next().value!);
return { status: 'purged', slug, source_id: sourceId, residuals: PURGE_RESIDUALS, journal_sweep: journalSweep,
purge: { content_hash8: storedHash?.slice(0, 8) ?? null, tombstoned: hashes.size > 0, content_hashes_tombstoned: hashes.size, removed,
diff --git a/test/large-pages/credential-reseal-segments.test.ts b/test/large-pages/credential-reseal-segments.test.ts
new file mode 100644
index 0000000000..0512101386
--- /dev/null
+++ b/test/large-pages/credential-reseal-segments.test.ts
@@ -0,0 +1,69 @@
+/**
+ * Credential-safe re-seal of segmented pages (Wave B, spec 11, reader
+ * inventory row 8).
+ *
+ * 1. Protects: a segmented page whose segments hold a private key (a stored
+ * `pem` region; its body columns are NULL) and whose projection is unsealed
+ * is counted as pending by the credential check and re-sealed by
+ * `resealCredentialProjections` through its segmented projection, with no
+ * chunk carrying the key body.
+ * 2. Fails when: the pending scan only matches the inline body columns, so a
+ * segmented page with a key stays withheld and uncounted.
+ * 3. Runs on PGLite, and on Postgres when DATABASE_URL is set.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+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 { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { importFromContent } from '../../src/core/import-file.ts';
+import { credentialProjectionPending, resealCredentialProjections } from '../../src/core/page-state/credential-reseal.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { segmentedPageRow } from '../helpers/segmented-page-checks.ts';
+import { withEnv } from '../helpers/with-env.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-credential-segments-'));
+const engines: BrainEngine[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+
+const KEY_LINE = 'MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCexampleNOTREAL0';
+const KEY = `-----BEGIN PRIVATE KEY-----\n${Array.from({ length: 12 }, (_, i) => `${KEY_LINE.slice(0, -1)}${i % 10}`).join('\n')}\n-----END PRIVATE KEY-----`;
+function filler(tag: string, bytes: number): string {
+ const parts: string[] = [];
+ for (let i = 0, n = 0; n < bytes; i++) {
+ const part = `## ${tag} ${i}\n\n${`Deployment runbook notes for the staging cluster, step ${i}. `.repeat(30)}\n\n`;
+ parts.push(part);
+ n += part.length;
+ }
+ return parts.join('');
+}
+const BODY = `---\ntitle: Runbook\ntype: note\n---\n\n# Runbook\n\n${filler('Before', 700_000)}## Old deploy key\n\n${KEY}\n\n${filler('After', 700_000)}`;
+
+beforeAll(async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);
+ if (process.env.DATABASE_URL) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL); engines.push(pg.engine); closePostgres = pg.close; }
+ for (const engine of engines) await engine.setConfig('pages.segmented_storage', 'on');
+}), 120_000);
+afterAll(async () => { for (const engine of engines) await engine.disconnect(); await closePostgres?.(); rmSync(home, { recursive: true, force: true }); });
+
+describe('credential re-seal of segmented pages', () => {
+ test('a segmented page holding a private key is counted pending and re-sealed from its segments', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ await importFromContent(engine, 'notes/runbook', BODY, { noEmbed: true, sourceId: 'default' });
+ const page = await segmentedPageRow(engine, 'notes/runbook');
+ expect(page.body_storage).toBe('segmented');
+ expect(await engine.executeRaw(`SELECT 1 FROM page_body_manifest WHERE page_id=$1 AND gen_to IS NULL AND protected_regions @> '[{"kind":"pem"}]'::jsonb`, [page.id])).not.toHaveLength(0);
+ // What migration v189 does to a page carrying a key: its projection is unsealed until re-chunked.
+ await engine.executeRaw('UPDATE pages SET text_projection_revision=NULL WHERE id=$1', [page.id]);
+ expect(await credentialProjectionPending(engine, ['default'])).toEqual({ rebuildable: 1, kept: 0 });
+
+ expect(await resealCredentialProjections(engine)).toMatchObject({ resealed: 1, failed: 0, superseded: 0 });
+ expect(await credentialProjectionPending(engine, ['default'])).toEqual({ rebuildable: 0, kept: 0 });
+ const after = await segmentedPageRow(engine, 'notes/runbook');
+ expect(after.text_projection_revision).toBe(after.knowledge_revision);
+ expect(await engine.executeRaw(`SELECT 1 FROM content_chunks WHERE page_id=$1 AND strpos(chunk_text,$2)>0`, [page.id, KEY_LINE.slice(0, 40)])).toHaveLength(0);
+ expect(await engine.executeRaw('SELECT 1 FROM content_chunks WHERE page_id=$1', [page.id])).not.toHaveLength(0);
+ }
+ }), 300_000);
+});
diff --git a/test/large-pages/forget-scope.test.ts b/test/large-pages/forget-scope.test.ts
new file mode 100644
index 0000000000..5be54ea522
--- /dev/null
+++ b/test/large-pages/forget-scope.test.ts
@@ -0,0 +1,142 @@
+/**
+ * Forget (withdrawal) on segmented pages (Wave B, spec 11).
+ *
+ * 1. Protects: withdrawing a claim strikes its row in the segment holding the
+ * fence and publishes a new generation; only the chunk rows of that
+ * occurrence are replaced (every other occurrence keeps its rows, ids
+ * unchanged), the fence's other row is untouched and the stored
+ * content_hash is the reconstructed body's. Discovery finds a segmented page that states
+ * the claim in a fence without any fact row pointing at it, by scanning
+ * only segments flagged with facts slots.
+ * 2. Fails when: forget deletes every chunk of a segmented page, leaves the
+ * row unstruck in the segment, or discovery reads only inline bodies.
+ * 3. Runs on PGLite, and on Postgres when DATABASE_URL is set.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+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 { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { importFromContent } from '../../src/core/import-file.ts';
+import { registerLocalWriter } from '../../src/core/persistence/identity.ts';
+import { withCoordinatedWrite } from '../../src/core/persistence/context.ts';
+import { recordFactWithdrawal } from '../../src/core/facts/withdrawal.ts';
+import { discoverWithdrawalTargets } from '../../src/core/facts/withdrawal-discovery.ts';
+import { forgetFactInFence } from '../../src/core/facts/forget.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { reconstructedPage, segmentedPageRow } from '../helpers/segmented-page-checks.ts';
+import { TEST_WRITE_ATTRIBUTION } from '../helpers/write-attribution.ts';
+import { withEnv } from '../helpers/with-env.ts';
+
+const CLAIM = 'Prefers the window seat';
+const home = mkdtempSync(join(tmpdir(), 'gbrain-forget-scope-'));
+const engines: BrainEngine[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+
+const fence = (rows: string[]) => `<!--- gbrain:facts:begin -->
+| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |
+|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|
+${rows.join('\n')}
+<!--- gbrain:facts:end -->`;
+const row = (n: number, claim: string, visibility = 'world') => `| ${n} | ${claim} | preference | 1.0 | ${visibility} | medium | 2026-01-01 | | chat | |`;
+function filler(tag: string, bytes: number): string {
+ const parts: string[] = [];
+ for (let i = 0, n = 0; n < bytes; i++) {
+ const part = `## ${tag} ${i}\n\n${`Meeting notes on hiring, budget and the design review, item ${i}. `.repeat(30)}\n\n`;
+ parts.push(part);
+ n += part.length;
+ }
+ return parts.join('');
+}
+const body = (title: string) => `---\ntitle: ${title}\ntype: note\n---\n\n# ${title}\n\n${filler('Part one', 700_000)}`
+ + `## Facts\n\n${fence([row(1, CLAIM), row(2, 'Walks to work')])}\n\n${filler('Part two', 700_000)}`;
+
+const coordinated = <T>(engine: BrainEngine, fn: (tx: BrainEngine) => Promise<T>) =>
+ engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => fn(tx), TEST_WRITE_ATTRIBUTION));
+
+beforeAll(async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);
+ if (process.env.DATABASE_URL) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL); engines.push(pg.engine); closePostgres = pg.close; }
+ for (const engine of engines) { await registerLocalWriter(engine, 'cli'); await engine.setConfig('pages.segmented_storage', 'on'); }
+}), 120_000);
+afterAll(async () => { for (const engine of engines) await engine.disconnect(); await closePostgres?.(); rmSync(home, { recursive: true, force: true }); });
+
+/** Live chunk ids by occurrence, and the occurrence whose segment holds `text`. */
+async function liveChunks(engine: BrainEngine, pageId: number, text: string) {
+ const rows = await engine.executeRaw<{ id: number; occurrence_id: number; holds: boolean }>(`SELECT c.id,c.occurrence_id,
+ position(convert_to($2::text,'UTF8') in t.body)>0 AS holds
+ FROM content_chunks c JOIN page_body_manifest m ON m.page_id=c.page_id AND m.occurrence_id=c.occurrence_id AND m.gen_to IS NULL AND m.staging_id IS NULL
+ JOIN page_segment_texts t ON t.source_id=m.source_id AND t.sha256=m.sha256 WHERE c.page_id=$1 ORDER BY c.id`, [pageId, text]);
+ return { all: rows.map(r => Number(r.id)), holding: rows.filter(r => r.holds).map(r => Number(r.id)), occurrences: new Set(rows.filter(r => r.holds).map(r => Number(r.occurrence_id))) };
+}
+
+describe('forget on segmented pages', () => {
+ test('strikes the row in its segment and replaces only that occurrence\'s chunks, on every page stating the claim', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ await importFromContent(engine, 'notes/seating', body('Seating'), { noEmbed: true, sourceId: 'default' });
+ await importFromContent(engine, 'notes/seating-copy', body('Seating copy'), { noEmbed: true, sourceId: 'default' });
+ const page = await segmentedPageRow(engine, 'notes/seating'), copy = await segmentedPageRow(engine, 'notes/seating-copy');
+ expect(page.body_storage).toBe('segmented');
+ const before = await liveChunks(engine, page.id, CLAIM);
+ expect(before.occurrences.size).toBe(1);
+ expect(before.all.length).toBeGreaterThan(before.holding.length);
+ 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','notes/seating',1) RETURNING id`, [CLAIM]));
+
+ const result = await coordinated(engine, tx => recordFactWithdrawal(tx, Number(fact!.id), 'default'));
+ expect(result.withdrawn).toBe(true);
+ expect(result.pages.map(p => p.slug).sort()).toEqual(['notes/seating', 'notes/seating-copy']);
+
+ for (const target of [page, copy]) {
+ const after = await segmentedPageRow(engine, target.id === page.id ? 'notes/seating' : 'notes/seating-copy');
+ expect(after.body_generation).toBe(target.body_generation + 1);
+ const { body: stored, hash } = await reconstructedPage(engine, target.id === page.id ? 'notes/seating' : 'notes/seating-copy');
+ expect(stored.compiled_truth).toMatch(new RegExp(`\\| 1 \\| ~~${CLAIM}~~ \\| preference \\|.*\\| forgotten: memory withdrawn \\|`));
+ expect(stored.compiled_truth).not.toContain(`| ${CLAIM} |`);
+ expect(stored.compiled_truth).toContain(row(2, 'Walks to work'));
+ expect(after.content_hash).toBe(hash);
+ }
+ const after = await liveChunks(engine, page.id, 'forgotten: memory withdrawn');
+ const kept = before.all.filter(id => !before.holding.includes(id));
+ expect(after.all.filter(id => kept.includes(id))).toEqual(kept);
+ expect(after.all.filter(id => before.holding.includes(id))).toEqual([]);
+ expect(after.holding.length).toBeGreaterThan(0);
+ expect([...after.occurrences].some(id => before.occurrences.has(id))).toBe(false);
+ }
+ }), 300_000);
+
+ test('a superseded row is struck in its segment (DB-only forget path), not skipped as an inline-only body', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ await importFromContent(engine, 'notes/commute', body('Commute'), { noEmbed: true, sourceId: 'default' });
+ const page = await segmentedPageRow(engine, 'notes/commute');
+ expect(page.body_storage).toBe('segmented');
+ const prior = (await reconstructedPage(engine, 'notes/commute')).body.compiled_truth;
+ 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','Walks to work',NULL,'world','test','notes/commute',2) RETURNING id`));
+ const result = await withCoordinatedWrite(engine, ['default'], () => forgetFactInFence(engine, Number(fact!.id), { supersededBy: { rowNum: 3 } }), TEST_WRITE_ATTRIBUTION);
+ expect(result.path).toBe('legacy_db');
+ expect((await segmentedPageRow(engine, 'notes/commute')).body_generation).toBe(page.body_generation + 1);
+ const { body: stored, hash } = await reconstructedPage(engine, 'notes/commute');
+ const struck = stored.compiled_truth.match(/\| 2 \| ~~Walks to work~~ \|.*\| superseded by #3 \|/)?.[0];
+ expect(struck).toBeDefined();
+ expect(stored.compiled_truth).toBe(prior.replace(row(2, 'Walks to work'), struck!));
+ expect((await segmentedPageRow(engine, 'notes/commute')).content_hash).toBe(hash);
+ }
+ }), 300_000);
+
+ test('discovery finds a private fence row that only the segment holds (chunks never carry private rows)', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const secret = 'Keeps a spare key under the mat';
+ for (const engine of engines) {
+ const text = body('Spare key').replace(row(2, 'Walks to work'), row(2, secret, 'private'));
+ await importFromContent(engine, 'notes/spare-key', text, { noEmbed: true, sourceId: 'default' });
+ const page = await segmentedPageRow(engine, 'notes/spare-key');
+ expect(page.body_storage).toBe('segmented');
+ const [chunked] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM content_chunks WHERE page_id=$1 AND chunk_text LIKE '%spare key%'`, [page.id]);
+ expect(Number(chunked!.n)).toBe(0);
+ const [hash] = await engine.executeRaw<{ h: string }>('SELECT gbrain_fact_fingerprint($1) AS h', [secret]);
+ const targets = await discoverWithdrawalTargets(engine, 'default', [{ visibility: 'private', fact_hash: hash!.h, claim: secret }]);
+ expect(targets.map(t => t.slug)).toEqual(['notes/spare-key']);
+ }
+ }), 300_000);
+});
diff --git a/test/large-pages/page-purge-segments.test.ts b/test/large-pages/page-purge-segments.test.ts
new file mode 100644
index 0000000000..6c1936ef81
--- /dev/null
+++ b/test/large-pages/page-purge-segments.test.ts
@@ -0,0 +1,142 @@
+/**
+ * Page purge and TTL hard delete of segmented pages (Wave B, spec 11).
+ *
+ * 1. Protects: `delete_page purge:true` on a segmented page over the
+ * single-string ceiling (stream-imported, with a retained version) removes
+ * the page, its manifest rows, the segment texts only it referenced and its
+ * stagings in the same transaction, and tombstones its stored content hash
+ * without holding the body as one string; the same file then refuses to
+ * import (purged_content). The TTL hard delete (`purgeDeletedPages`) of a
+ * soft-deleted segmented page sweeps its texts and stagings the same way,
+ * and keeps texts another page still references.
+ * 2. Fails when: the purge refuses a segmented page (page_body_segmented),
+ * leaves its texts or stagings for a later GC, or tombstones no hash.
+ * 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 { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import type { OperationContext } from '../../src/core/ops/contract.ts';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { importFromContent, importFromFile } from '../../src/core/import-file.ts';
+import { operations } from '../../src/core/operations.ts';
+import { readPageBodyPolicy } from '../../src/core/page-body/limits.ts';
+import { PAGE_MAX_BYTES } from '../../src/core/page-size-policy.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 { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { conversationPage } from '../helpers/conversation-page.ts';
+import { segmentedPageRow } from '../helpers/segmented-page-checks.ts';
+import { TEST_WRITE_ATTRIBUTION } from '../helpers/write-attribution.ts';
+import { withEnv } from '../helpers/with-env.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-page-purge-segments-'));
+const env = { GBRAIN_HOME: home, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };
+const engines: BrainEngine[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+
+const ctx = (engine: BrainEngine): OperationContext => ({ engine, sourceId: 'default', remote: false, dryRun: false,
+ config: { engine: engine.kind, embedding_disabled: true, storage: { backend: 'local', bucket: 'b', localPath: join(home, 'storage') } },
+ logger: { info() {}, warn() {}, error() {} } } as OperationContext);
+const op = (name: string) => operations.find(o => o.name === name)!;
+const coordinated = <T>(engine: BrainEngine, fn: (tx: BrainEngine) => Promise<T>) =>
+ engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => fn(tx), TEST_WRITE_ATTRIBUTION));
+async function errorText(p: Promise<unknown>): Promise<string> {
+ try { await p; return 'ok'; } catch (e) { return `${(e as { code?: string }).code ?? ''}: ${(e as Error).message}`; }
+}
+async function shasOf(engine: BrainEngine, pageId: number): Promise<string[]> {
+ return (await engine.executeRaw<{ sha: string }>(`SELECT DISTINCT encode(sha256,'hex') AS sha FROM page_body_manifest WHERE page_id=$1`, [pageId])).map(r => r.sha);
+}
+async function textsLeft(engine: BrainEngine, shas: readonly string[]): Promise<number> {
+ const [row] = 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]);
+ return Number(row!.n);
+}
+async function openStaging(engine: BrainEngine, slug: string, pageId: number) {
+ const [source] = await engine.executeRaw<{ incarnation: string }>(`SELECT incarnation FROM sources WHERE id='default'`);
+ await coordinated(engine, tx => tx.openBodyStaging({ id: randomUUID(), kind: 'upload', principalKind: 'application', principalId: 'test:fixture',
+ clientRequestId: randomUUID(), sourceId: 'default', sourceIncarnation: source!.incarnation, slug, pageId, mode: 'replace', baseRevision: null,
+ baseGeneration: null, declaredBytes: 16, declaredSha256: null, reservedBytes: 0,
+ idleExpiresAt: new Date(Date.now() + 3_600_000), hardExpiresAt: new Date(Date.now() + 7_200_000) }));
+}
+const stagingsOf = async (engine: BrainEngine, slug: string) =>
+ (await engine.executeRaw(`SELECT 1 FROM page_body_stagings WHERE source_id='default' AND slug=$1`, [slug])).length;
+
+beforeAll(async () => withEnv(env, async () => {
+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);
+ if (process.env.DATABASE_URL) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL); engines.push(pg.engine); closePostgres = pg.close; }
+ for (const engine of engines) { await registerLocalWriter(engine, 'cli'); await engine.setConfig('pages.segmented_storage', 'on'); }
+}), 120_000);
+afterAll(async () => withEnv(env, async () => {
+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }
+ await closePostgres?.();
+ rmSync(home, { recursive: true, force: true });
+}));
+
+describe('page purge of segmented pages', () => {
+ test('delete_page purge:true of a page over the ceiling sweeps texts and stagings and tombstones the content', async () => withEnv(env, async () => {
+ const content = conversationPage(PAGE_MAX_BYTES + 1024 * 1024, { seed: 83, needles: [{ at: 0.6, word: 'AKIAEXAMPLENOTREAL' }] });
+ for (const engine of engines) {
+ const dir = join(home, `purge-${randomUUID().slice(0, 8)}`);
+ mkdirSync(dir, { recursive: true });
+ const file = join(dir, 'huge.md');
+ writeFileSync(file, content);
+ const slug = `notes/huge-${randomUUID().slice(0, 8)}`;
+ expect(await importFromFile(engine, file, `${slug}.md`, { noEmbed: true, bodyPolicy: await readPageBodyPolicy(engine) })).toMatchObject({ status: 'imported' });
+ const page = await segmentedPageRow(engine, slug);
+ expect(page.body_storage).toBe('segmented');
+ const [bytes] = await engine.executeRaw<{ n: string }>('SELECT body_bytes::text AS n FROM pages WHERE id=$1', [page.id]);
+ expect(Number(bytes!.n)).toBeGreaterThan(PAGE_MAX_BYTES);
+ await coordinated(engine, tx => tx.createVersion(slug, { sourceId: 'default' }));
+ await openStaging(engine, slug, page.id);
+ const shas = await shasOf(engine, page.id);
+ expect(await textsLeft(engine, shas)).toBe(shas.length);
+ expect(await stagingsOf(engine, slug)).toBeGreaterThan(0);
+
+ const snapshot = await engine.readPageSnapshot(slug, { sourceId: 'default', includeDeleted: true });
+ const result = await op('delete_page').handler(ctx(engine), { slug, purge: true, request_id: randomUUID(), expected_revision: snapshot!.revision }) as Record<string, any>;
+ expect(result.status).toBe('purged');
+ expect(result.purge.removed.page_body_manifest).toBeGreaterThan(0);
+ expect(result.purge.removed.page_segment_texts).toBe(shas.length);
+ expect(result.purge.removed.page_body_stagings).toBeGreaterThan(0);
+ expect(result.purge.removed.page_versions).toBe(1);
+ expect(await engine.executeRaw('SELECT 1 FROM pages WHERE source_id=$1 AND slug=$2', ['default', slug])).toHaveLength(0);
+ expect(await engine.executeRaw('SELECT 1 FROM page_body_manifest WHERE page_id=$1', [page.id])).toHaveLength(0);
+ expect(await textsLeft(engine, shas)).toBe(0);
+ expect(await stagingsOf(engine, slug)).toBe(0);
+ const segmentStore = (result.receipt.stores as Array<{ store: string; status: string }>).find(s => s.store === 'page_segment_texts');
+ expect(segmentStore?.status).toBe('deleted');
+ expect(await engine.executeRaw(`SELECT 1 FROM page_purges WHERE source_id='default' AND content_hash=$1`, [page.content_hash])).toHaveLength(1);
+ expect(await errorText(importFromFile(engine, file, `${slug}.md`, { noEmbed: true, bodyPolicy: await readPageBodyPolicy(engine) }))).toContain('purged_content');
+ }
+ }), 900_000);
+
+ test('the TTL hard delete sweeps a soft-deleted segmented page\'s texts and stagings, keeping shared texts', async () => withEnv(env, async () => {
+ const shared = conversationPage(1_400_000, { seed: 89 });
+ for (const engine of engines) {
+ const slug = `notes/expired-${randomUUID().slice(0, 8)}`, keeper = `notes/keeper-${randomUUID().slice(0, 8)}`;
+ await importFromContent(engine, slug, `${shared}\n## Own tail\n\nOnly the expired page says this.\n`, { noEmbed: true, sourceId: 'default' });
+ await importFromContent(engine, keeper, `${shared}\n## Own tail\n\nOnly the keeper says this.\n`, { noEmbed: true, sourceId: 'default' });
+ const page = await segmentedPageRow(engine, slug), kept = await segmentedPageRow(engine, keeper);
+ expect(page.body_storage).toBe('segmented');
+ await openStaging(engine, slug, page.id);
+ const shas = await shasOf(engine, page.id), keeperShas = new Set(await shasOf(engine, kept.id));
+ const own = shas.filter(sha => !keeperShas.has(sha)), common = shas.filter(sha => keeperShas.has(sha));
+ expect(own.length).toBeGreaterThan(0);
+ expect(common.length).toBeGreaterThan(0);
+ await coordinated(engine, tx => tx.softDeletePage(slug, { sourceId: 'default' }));
+ await engine.executeRaw(`UPDATE pages SET deleted_at=now() - interval '48 hours' WHERE source_id='default' AND slug=$1`, [slug]);
+
+ const purged = await engine.purgeDeletedPages(24);
+ expect(purged.slugs).toEqual([slug]);
+ expect(await engine.executeRaw('SELECT 1 FROM page_body_manifest WHERE page_id=$1', [page.id])).toHaveLength(0);
+ expect(await textsLeft(engine, own)).toBe(0);
+ expect(await textsLeft(engine, common)).toBe(common.length);
+ expect(await stagingsOf(engine, slug)).toBe(0);
+ }
+ }), 600_000);
+});
diff --git a/test/large-pages/purge-segments.test.ts b/test/large-pages/purge-segments.test.ts
new file mode 100644
index 0000000000..b8f4497550
--- /dev/null
+++ b/test/large-pages/purge-segments.test.ts
@@ -0,0 +1,144 @@
+/**
+ * Fact purge across segmented pages (Wave B, spec 11).
+ *
+ * 1. Protects: purge_fact on a claim whose facts row lives in a segment two
+ * pages share removes it everywhere a segment holds it: both live bodies
+ * (each a new generation, whose content_hash is the reconstructed body's),
+ * a retained version's generation (rebuilt, the version's content_hash
+ * updated), the old shared text row, an upload staging's part (the staging
+ * aborted) and the queued request whose `body_ref` names that staging
+ * (cancelled with purged_content). The receipt finds nothing: the page,
+ * version, segment-text and staging-part stores read deleted. Untouched
+ * segments keep their chunk rows.
+ * 2. Fails when: the purge refuses or skips a segmented page, leaves the claim
+ * in a retained generation or in an unreferenced text, keeps the staging or
+ * the request alive, or the receipt does not probe segment texts.
+ * 3. Runs on PGLite, and on Postgres when DATABASE_URL is set.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { createHash, 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 { operations } from '../../src/core/operations.ts';
+import { registerLocalWriter } from '../../src/core/persistence/identity.ts';
+import { withCoordinatedWrite } from '../../src/core/persistence/context.ts';
+import { admitWrite } from '../../src/core/persistence/journal.ts';
+import { requestPrincipalForContext } from '../../src/core/persistence/page-mutations.ts';
+import { submissionAuthority } from '../../src/core/persistence/authority.ts';
+import { segmentedBodyContains } from '../../src/core/page-body/segment-rewrite.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { reconstructedPage, segmentedPageRow } from '../helpers/segmented-page-checks.ts';
+import { TEST_WRITE_ATTRIBUTION } from '../helpers/write-attribution.ts';
+import { withEnv } from '../helpers/with-env.ts';
+
+const CLAIM = 'Door code is 4417';
+const home = mkdtempSync(join(tmpdir(), 'gbrain-purge-segments-'));
+const engines: BrainEngine[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+
+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 -->`;
+function filler(bytes: number): string {
+ const parts: string[] = [];
+ for (let i = 0, n = 0; n < bytes; i++) {
+ const part = `## Section ${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 COMMON = `# Shared notes\n\nIntro paragraph.\n\n## Facts\n\n${FENCE}\n\n${filler(1_300_000)}`;
+const page = (title: string, tail: string) => `---\ntitle: ${title}\ntype: note\n---\n\n${COMMON}## Tail\n\n${tail}\n`;
+
+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 run = (engine: BrainEngine, params: Record<string, unknown>) => purge.handler(ctx(engine), params) as Promise<Record<string, any>>;
+const coordinated = <T>(engine: BrainEngine, fn: (tx: BrainEngine) => Promise<T>) =>
+ engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => fn(tx), TEST_WRITE_ATTRIBUTION));
+
+beforeAll(async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);
+ if (process.env.DATABASE_URL) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL); engines.push(pg.engine); closePostgres = pg.close; }
+ for (const engine of engines) { await registerLocalWriter(engine, 'cli'); await engine.setConfig('pages.segmented_storage', 'on'); }
+}), 120_000);
+afterAll(async () => { for (const engine of engines) await engine.disconnect(); await closePostgres?.(); rmSync(home, { recursive: true, force: true }); });
+
+describe('purge_fact on segmented pages', () => {
+ test('a claim in a segment two pages share leaves live bodies, a retained generation, texts, a staged part and a body_ref request', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ await importFromContent(engine, 'notes/shared-a', page('Shared A', 'First tail of page A.'), { noEmbed: true, sourceId: 'default' });
+ await coordinated(engine, tx => tx.createVersion('notes/shared-a', { sourceId: 'default' }));
+ await importFromContent(engine, 'notes/shared-a', page('Shared A', 'Second tail of page A, rewritten.'), { noEmbed: true, sourceId: 'default' });
+ await importFromContent(engine, 'notes/shared-b', page('Shared B', 'The tail of page B.'), { noEmbed: true, sourceId: 'default' });
+ const a = await segmentedPageRow(engine, 'notes/shared-a'), b = await segmentedPageRow(engine, 'notes/shared-b');
+ expect([a.body_storage, b.body_storage]).toEqual(['segmented', 'segmented']);
+ const [version] = await engine.executeRaw<{ body_generation: number }>(`SELECT body_generation FROM page_versions WHERE page_id=$1 AND body_storage='segmented'
+ ORDER BY id LIMIT 1`, [a.id]);
+ expect(Number(version!.body_generation)).toBeLessThan(a.body_generation);
+ // The fence's segment is one text both pages reference.
+ const [shared] = await engine.executeRaw<{ sha: string; pages: number }>(`SELECT encode(sha256,'hex') AS sha,count(DISTINCT page_id)::int AS pages
+ FROM page_body_manifest WHERE page_id=ANY($1::int[]) AND seq=0 AND gen_to IS NULL GROUP BY sha256`, [[a.id, b.id]]);
+ expect(shared!.pages).toBe(2);
+ const untouched = await engine.executeRaw<{ id: number }>(`SELECT c.id FROM content_chunks c JOIN page_body_manifest m ON m.page_id=c.page_id
+ AND m.occurrence_id=c.occurrence_id AND m.gen_to IS NULL AND m.staging_id IS NULL WHERE c.page_id=$1 AND m.seq>0 ORDER BY c.id`, [a.id]);
+ expect(untouched.length).toBeGreaterThan(0);
+
+ 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','notes/shared-a',1) RETURNING id`, [CLAIM]));
+ // An upload staging whose part holds the claim, and the queued request that would publish it.
+ const [source] = await engine.executeRaw<{ incarnation: string }>(`SELECT incarnation FROM sources WHERE id='default'`);
+ const stagingId = randomUUID();
+ const part = Buffer.from(`Uploaded notes.\n${FENCE}\n`, 'utf8');
+ await coordinated(engine, async tx => {
+ await tx.openBodyStaging({ id: stagingId, kind: 'upload', principalKind: 'application', principalId: 'test:fixture', clientRequestId: randomUUID(),
+ sourceId: 'default', sourceIncarnation: source!.incarnation, slug: 'notes/upload-example', pageId: null, mode: 'create', baseRevision: null,
+ baseGeneration: null, declaredBytes: part.length, declaredSha256: null, reservedBytes: 0,
+ idleExpiresAt: new Date(Date.now() + 3_600_000), hardExpiresAt: new Date(Date.now() + 7_200_000) });
+ await tx.executeRaw(`INSERT INTO page_body_staging_parts(staging_id,part_no,byte_start,byte_len,sha256,body) VALUES ($1::uuid,0,0,$2,$3,$4)`,
+ [stagingId, part.length, createHash('sha256').update(part).digest(), part]);
+ });
+ const c = ctx(engine);
+ const principal = await requestPrincipalForContext(c);
+ const held = await admitWrite(engine, { principal, operation: 'put_page', sourceId: 'default', sourceIncarnation: source!.incarnation,
+ slug: 'notes/upload-example', requestId: randomUUID(), callerIntent: { body_ref: { staging_id: stagingId } }, intent: { body_ref: { staging_id: stagingId } },
+ authority: await submissionAuthority(c, 'put_page', 'default', source!.incarnation, 'notes/upload-example') });
+
+ const dry = await run(engine, { id: Number(fact!.id), dry_run: true });
+ expect(dry.stores.find((s: any) => s.store === 'pages')).toMatchObject({ status: 'would_remove', removed: 2 });
+ const done = await run(engine, { id: Number(fact!.id), confirm: dry.confirm_token, expected_revision: dry.expected_revision, request_id: randomUUID() });
+ expect(done.state).toBe('committed');
+
+ for (const slug of ['notes/shared-a', 'notes/shared-b']) {
+ const { page: row, body, hash } = await reconstructedPage(engine, slug);
+ expect(body.compiled_truth).not.toContain(CLAIM);
+ expect(body.compiled_truth).toContain('Likes green tea');
+ expect(row.content_hash).toBe(hash);
+ }
+ expect(await segmentedBodyContains(engine, a.id, 'default', [CLAIM], { generation: Number(version!.body_generation) })).toBe(false);
+ expect(await segmentedBodyContains(engine, a.id, 'default', ['likes green tea'], { generation: Number(version!.body_generation) })).toBe(true);
+ expect(await engine.executeRaw(`SELECT 1 FROM page_segment_texts WHERE sha256=decode($1,'hex')`, [shared!.sha])).toHaveLength(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(await engine.executeRaw(`SELECT 1 FROM page_body_staging_parts WHERE staging_id=$1::uuid`, [stagingId])).toHaveLength(0);
+ expect((await engine.executeRaw<{ state: string }>(`SELECT state FROM page_body_stagings WHERE id=$1::uuid`, [stagingId]))[0]?.state).toBe('aborted');
+ expect((await engine.executeRaw<{ state: string; error_code: string }>(`SELECT state,error_code FROM persistence_requests WHERE id=$1::uuid`, [held.id]))[0])
+ .toEqual({ state: 'cancelled', error_code: 'purged_content' });
+ const kept = await engine.executeRaw<{ id: number }>(`SELECT id FROM content_chunks WHERE id=ANY($1::bigint[]) ORDER BY id`, [untouched.map(r => r.id)]);
+ expect(kept.length).toBe(untouched.length);
+ for (const store of ['pages', 'page_versions', 'page_segment_texts', 'page_body_staging_parts']) {
+ expect(done.stores.find((s: any) => s.store === store)).toMatchObject({ status: 'deleted' });
+ }
+ expect(done.residuals.filter((r: any) => r.reason === 'source_prose')).toEqual([]);
+ expect(JSON.stringify(done)).not.toContain(CLAIM);
+ }
+ }), 300_000);
+});
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 163998e07a..50bc66d2b6 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -64,8 +64,12 @@ test/import-revision-concurrency.test.ts
test/keyword-statement-timeout-knob-6495.test.ts
test/lane-apply-pipelining.test.ts
test/large-pages/chunk-visibility.test.ts
+test/large-pages/credential-reseal-segments.test.ts
+test/large-pages/forget-scope.test.ts
test/large-pages/managed-streamed-import.test.ts
test/large-pages/managed-sync-segmented-rename.test.ts
+test/large-pages/page-purge-segments.test.ts
+test/large-pages/purge-segments.test.ts
test/large-pages/segment-vector-reuse.test.ts
test/large-pages/segmented-body-unreachable.test.ts
test/large-pages/segmented-derived-work.test.ts