Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

large pages: segmented storage on by default behind the writer-version gate (Wave B PR 2, lane S)

garrytan2b9c27b3f4cf
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index 03550eebfd..344a3ba9ea 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -343,6 +343,7 @@ and the fix is the read-only `gbrain migrate --to postgres --plan --json`.
| Cost | Free | Supabase Pro ($25/mo) |
| Concurrency | Single process | Connection pooling |
| Backups | Manual (file copy) | Managed by Supabase |
+| Largest page | 128 MiB, stored in segments (`pages.max_bytes`) | 256 MiB, stored in segments (`pages.max_bytes`) |
**Migration:** on a PGLite brain, `gbrain migrate --to postgres` (alias `--to supabase`) graduates the brain to Postgres. Without `--yes` it prints the plan and exits 3; `--yes --expect <plan_hash>` runs it. Graduation drains pending writes, copies every table verbatim with its primary keys (pages, facts, takes, versions, links, timeline, embeddings, transcripts and paid caches, request history and withdrawals, token and OAuth rows) into a fenced target, verifies row counts and digests, runs `gbrain doctor` on the target, and only then flips routing. It works for brains with write history and for managed brains. The PGLite data dir is retained as `<path>.graduated-<run_id>` and a tombstone file takes its place. Walkthrough, recovery by error code, rollback and what stays on this computer: [Move a PGLite brain to Postgres](guides/move-to-postgres.md).
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.md
index 6b2e763af1..134e0a1edc 100644
--- a/docs/architecture/key-files/core-persistence.md
+++ b/docs/architecture/key-files/core-persistence.md
@@ -14,7 +14,7 @@ Managed facts extraction (withdrawn-candidate skip and recovery, conversation fa
- `src/core/persistence/git-durability-policy.ts` + `git-durability-administration.ts` — whether the persistence owner commits and pushes page writes through its Git effect is a per-host-binding setting (#5182): `persistence_host_bindings.git_durability` (`enabled` | `disabled` | NULL, migration v234, column SQL kept out of the replayed schema blob as `PERSISTENCE_GIT_DURABILITY_COLUMN_SQL`). `gitDurabilityPolicy(binding, root)` is tri-state and fail-closed: a recorded value wins, NULL falls back to the legacy post-commit-hook probe, a probe error fails the effect instead of skipping it; `effects.ts` takes its per-root verdict from it. `gitDurabilityState` renders `on`/`off`/`unknown` for `writer status` and `writer activate`'s `git_durability` listing. `planGitDurabilityCatchUp`/`requeueGitDurabilityCatchUp` re-queue the Git effects completed `durability_not_enabled` while the setting was off by resetting the existing rows, never inserting under `UNIQUE(request_id, kind)`. The verb `writer_git_durability` (`gbrain sources writer git-durability <source> --enable|--disable [--pat-file <path>] [--dry-run]`, administration-gated like the other writer verbs) runs a read-only `git push --dry-run` probe before enabling (codes `git_branch_unborn`, `git_checkout_required`, `git_detached_head`), wires the repo-scoped credential under `gbrain.durability.managedcredential` from a 0600 `--pat-file` (`pat_file_unreadable` otherwise) and retries the worktree's parked pushes. `sources push` (`managedPushRefusal` in `workspace-push.ts`), `bootstrap verify`'s `checkPushProbe` and the skill-pack writer guard name this route on a managed worktree (#5606). Pinned by `test/persistence-admin-git-durability.test.ts`, `test/managed-push-remedy.serial.test.ts`.
- `src/core/persistence/deactivation.ts` — private CLI `sources writer deactivate` (#5455/#5628), brain-wide and trusted-local. `deactivationBlockers` lists the admin lock, queued/running/recovering requests, recovering topology changes, uncommitted effects, held connector items (managed holds that classic mode would not read) and live `gbrain_cycle_locks` leases, each with its CLI exit; `physicalRootBlockers(engine, mode)` (#5914 [R9a]) adds `physical_root` for this host's owned checkouts, probed as the mode's real run will: strict `assertPhysicalRoot` for managed, `assertPhysicalRootReservation` for the classic pre-activation release, so each preview lists exactly what its real operation refuses on; `--dry-run` returns them plus the worktrees that would retire, the kept shared-skill settings and, when clean, `apply_command` bound to the admin state read before the preview. `deactivatePersistence` takes the local native worktree locks, then in one transaction locks `persistence_brain FOR UPDATE`, checks the expected admin state and the admin lock, locks worktrees then sources `FOR UPDATE` (admission's order), rechecks the blockers, sets `enabled=false`, increments `mode_epoch`, retires every worktree, deletes source and host bindings and records a committed `writer_deactivate` topology change (brain id, retired epoch, retired worktree ids and roots, source roots). `cleanupRetiredManagedMarkers` runs on CLI connect, after deactivate and from `writer status`: it removes this brain's registry records, `.gbrain-managed` / Git `gbrain-managed.json`, `.gbrain-owner.json` and reservations only when their `mode_epoch` is a retired one below the current epoch, or, without an epoch, their worktree id (or, for markers without one, their root outside any active binding) is recorded as retired; unknown or newer epochs are kept and reported `pending`, each file is re-read before unlinking and other brains' files are never touched. `root-registry.ts` writes `mode_epoch` into new registry records and managed markers. Tests: `test/persistence-deactivate.test.ts` (PGLite and Postgres), `test/e2e/persistence-deactivate-race.test.ts`. See [persistence stalls](persistence-stalls.md).
-- `src/core/persistence/{admin-lock,blocking-effects,writer-versions}.ts` — `admin-lock.ts` owns the opt-in brain-level writer admin lock: reserved config key `persistence.writer_admin_lock` (`{locked, set_at, host_id, generation}`), written only by local `gbrain sources writer lock|unlock` under the `persistence_brain` row `FOR UPDATE`; lock refuses while a prepared transfer is unaccepted. `assertWriterAdminUnlocked` runs inside the claim, managed claim, activation, shared-skill activation and transfer prepare/accept transactions for every caller (share lock on the brain row) and refuses with `writer_admin_locked`; only the ordinary first-write auto-claim (`claimWorktree(..., { automatic: true })` from page and memory mutations) is exempt. Generic `config set`/`unset`/`unset --pattern` refuse the key; engine migration copies it. It is not a security boundary and older binaries ignore it. `blocking-effects.ts` lists queued, running or recovering effects (`listBlockingEffects`) and builds `writer_not_quiesced` suggestions naming the first blocking request or effect with `gbrain sources writer status <source> --json`. `writer-versions.ts` stamps admitter version/host at admission and consumer version/host/`published_at` only on committed publication (migration 178, cutoff `persistence_brain.writer_version_cutoff` on the database clock); replay and compaction keep stamps. `sources writer status` reports `admin_lock`, `local_host_id`, `blocking_effects` and `writer_versions`; `src/commands/doctor/checks/writer-version.ts` is the seven-day `writer_version` advisory. Tests: `test/persistence-writer-admin-lock.test.ts`, `test/persistence-writer-versions.test.ts`, `test/persistence-blocking-effects.test.ts`, `test/e2e/persistence-writer-{admin-lock,stamps}.test.ts`.
+- `src/core/persistence/{admin-lock,blocking-effects,writer-versions}.ts` — `admin-lock.ts` owns the opt-in brain-level writer admin lock: reserved config key `persistence.writer_admin_lock` (`{locked, set_at, host_id, generation}`), written only by local `gbrain sources writer lock|unlock` under the `persistence_brain` row `FOR UPDATE`; lock refuses while a prepared transfer is unaccepted. `assertWriterAdminUnlocked` runs inside the claim, managed claim, activation, shared-skill activation and transfer prepare/accept transactions for every caller (share lock on the brain row) and refuses with `writer_admin_locked`; only the ordinary first-write auto-claim (`claimWorktree(..., { automatic: true })` from page and memory mutations) is exempt. Generic `config set`/`unset`/`unset --pattern` refuse the key; engine migration copies it. It is not a security boundary and older binaries ignore it. `blocking-effects.ts` lists queued, running or recovering effects (`listBlockingEffects`) and builds `writer_not_quiesced` suggestions naming the first blocking request or effect with `gbrain sources writer status <source> --json`. `writer-versions.ts` stamps admitter version/host at admission and consumer version/host/`published_at` only on committed publication (migration 178, cutoff `persistence_brain.writer_version_cutoff` on the database clock); replay and compaction keep stamps. `sources writer status` reports `admin_lock`, `local_host_id`, `blocking_effects` and `writer_versions`; `src/commands/doctor/checks/writer-version.ts` is the seven-day `writer_version` advisory. `SEGMENTED_WRITER_FLOOR` is the release that understands segmented page bodies (stamped at merge with the switch-on BEHAVIOR_CHANGES row's `since`); `page-body/limits.ts` `segmentedWriterBlockers` reads the seven-day committed writers below it (cached a minute per root engine) and any one keeps `pages.segmented_storage` effectively off; doctor `segmented_storage` (`src/commands/doctor/checks/segmented-storage.ts`) reports configured, effective and blocking hosts. Tests: `test/persistence-writer-admin-lock.test.ts`, `test/persistence-writer-versions.test.ts`, `test/persistence-blocking-effects.test.ts`, `test/e2e/persistence-writer-{admin-lock,stamps}.test.ts`.
- `src/core/persistence/{atom-maintenance,atom-retry,page-prepare,facts-maintenance,facts-prepare,prepared-maintenance}.ts` — resident dispatch for durable atom publication/completion, explicit atom retry (`retryManagedAtomBatch` takes the job's signal and deadline, stops between stages on caller cancel, deadline or cycle-lock loss, shares one deadline-bound `MaintenanceWriteWait` with the model rerun, and reports a stop after admission as `write_pending` or an `AbortError` carrying the receipts, never `cancelled`; #6622), authorized multi-entity fact-fence/backstop append, local synthesize/patterns/consolidation, and the cycle's lint repairs on a managed brain (`runLintCore` publishes each fix through `maintenancePreflight` + `publishMaintenancePage`; #5180, `test/managed-lint.test.ts`). `page-prepare.ts` exports `fileMatchesSnapshot`, the canonical file-versus-page comparison `prepareFileTarget` applies, so lint can bind a repair to the revision it read (it takes the importer's path for the file: a frontmatter-less file under a directory-inference rule also matches when `readCanonicalAsImported` (BOM strip + `applyInference` at `scannerSourcePath`) reproduces the stored row, with an inferred type treated as undeclared, #6605; reconcile reads the file side through `reconcileFileReading` in `reconcile-state.ts`); the uncoordinated-local-edit refusal carries detail `file_database_drift` and a `sources reconcile <src> <slug> --brain host --preview` fix; a shared-origin delete: canonical-reconciliation.md. In `prepareFileTarget`, a live page whose canonical file is missing refuses `source_changed` unless it is declared or derive-phase database-only, or it is a `delete_page` (`deleting`, no content) of a page with no recorded `source_path` and no captured file URI: that delete plans no file, so it publishes database-only and its receipt reports no file or Git effect (`test/persistence-captured-file-target.test.ts`, `test/persistence-never-published-delete.test.ts`). `atomOwnerTarget` is the one owner decision for an atom session and for `atomDrainOwnerRefusal`, the auto-drain dispatch pre-check; an unbound Google/GitHub source publishes atom maintenance through the `connector_database` target (its `local_path` is connector state, not a checkout) and the publication refuses with `source_changed` when the source gained an owner after preflight. `submitMaintenance` scans every content-carrying intent with `scanCanonicalFences` (the check the canonical projection runs) over the whole submitted body and timeline before a request exists (#6278): a defect no adoption clears (a second facts fence in the timeline; `replaceOrInsertFactsFence` replaces only the first) is refused with its fence reason, so `fenceManaged` reports the page in `failed_pages` and the others still adopt, while a repair whose postimage is clean passes. `prepareFactFenceAdoption` names its steps for `enterClaimStep`, compares the fence cell with the legacy fact modulo whitespace, writes the cell's parsed text back into `facts.fact` in the same `UPDATE` that sets `row_num` (so the projection keeps the fact's id), and throws the registered `fence_unrenderable` (class `server`) as its last-line defence. `maintenancePreflight` creates the job's `MaintenanceWriteWait` (optional `deadlineAtMs`) and `submitMaintenance` uses it for new and replayed requests; its owner check goes through `checkOwner` / `ownerUnavailableError` (`owner-refusal.ts`), so a missing binding, a changed incarnation, another owner host, a draining or recovering worktree and a missing local or coordination path each refuse `owner_unavailable` with their own `reason`, and nothing claims or transfers ownership to get past them. #6325: `resumeManagedAtoms` returns `run | done | held`. The drain does not replay a failed batch: it resumes the next automatic attempt, whose run key is `digest([drainKey, failedRequestId, 'automatic'])` (one stable id per failure, so a crashed attempt resumes and two runs admit the same requests), and whose completion advances the failed drain-key checkpoint by the same compare-and-set an explicit retry uses. The completion counts one strike per completed failure on that checkpoint (`attempts`); at `MAX_DETERMINISTIC_FAILURES` it sets `held`, which `MANAGED_ATOM_DISCOVERY_SQL` excludes from discovery and the backlog and `listHeldManagedAtoms` reports (doctor `extract_atoms_held_failed`, code `held_failed`). Reading a held or failed checkpoint never strikes; storage, authority and conflict errors fail the attempt without completing it, so they never strike either. A content change is a new drain key, so the count starts over. An explicit retry (`session.retry`) ignores `held`, and its failure refusal (`extraction_failed`) names the recorded failure reason (malformed output or a response stopped before the end) and carries a paid `fix` (`gbrain jobs submit extract-atoms-drain --params '{sourceId, retryRequestId}'`) with a read-only `gbrain write-request` verify; the drain raises it only for a failed batch whose checkpoint is gone. Tests: `test/managed-atoms-retry.test.ts`. Managed facts extraction (the withdrawn-candidate skip and its recovery route, the conversation facts batches, the unmanaged derived index) continues in [Core Persistence (managed facts)](core-persistence-facts.md).
- `src/core/persistence/maintenance-wait.ts` — how long a maintenance publisher waits for its accepted write to commit before the receipt reports `write_pending` (#5854). `MAINTENANCE_WRITE_WAIT_MS` is 30 s; `MaintenanceWriteWait` is one budget per job: each wait is capped by the job's remaining deadline (zero at or past it), and once one publish is still pending after its wait (`observe`) every later publish in that job waits zero and is deferred like it. A pending write keeps its request identity and commits later; it is never reported as committed. A `MaintenanceWriteWait` with no deadline also sets the replay window of a subagent tool write whose job has none (`minions/tool-write-identity.ts`). `__setMaintenanceWriteWaitForTests` replaces the base wait, those tool writes included. Tests: `test/maintenance-write-wait.test.ts`, `test/e2e/maintenance-write-wait.test.ts`.
diff --git a/docs/architecture/key-files/core-services-2-continued.md b/docs/architecture/key-files/core-services-2-continued.md
index c3164265b8..308092d861 100644
--- a/docs/architecture/key-files/core-services-2-continued.md
+++ b/docs/architecture/key-files/core-services-2-continued.md
@@ -17,5 +17,6 @@ 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/limits.ts` — Wave B size classes, ceilings, retention numbers and config keys in one place. `readPageBodyPolicy` is the single question every write asks: `segmented` is the effective `pages.segmented_storage` (default `on`; `off` or an unrecognized value is off; held off while `segmentedWriterBlockers` finds a recent writer below `SEGMENTED_WRITER_FLOOR`, and an unreadable gate counts as blocked), `maxBytes` the engine ceiling (256 MiB Postgres, 128 MiB PGLite, lowered by `pages.max_bytes`) while on and `PAGE_MAX_BYTES` while off. Config is read per call; only the writer gate is cached (`SEGMENTED_WRITER_GATE_TTL_MS`, `_resetSegmentedWriterGateForTests`). `chooseBodyStorage` applies the 1 MiB / 512 KiB hysteresis. Tests: `test/large-pages/segmented-switch.test.ts`.
- `src/core/page-body/read-range.ts` + `segment-projection.ts` + `segment-ledger.ts` — Wave B PR 2 (spec 7.1, 7.3): the segment reader. `openSegmentedBody` reads a page's live manifest rows and its withdrawal ledger (`readBodyLedger`); `readBodyRange(engine, { pageId, space, start, end, audience, region?, body? })` streams pieces one segment text at a time, never the whole body. Remote reads and every projected-space read serve the read projection: `projectSegment` projects whole segments from their stored protected regions (takes, truncated tail and markers out, keys as the projection token, facts regions rendered world-only and credential-projected), after the withdrawal overlay (`overlaySegmentText`; a fence split by a forced cut is omitted for reads and refuses a trusted read) and the fence overlay (held and purged rows out, rows below the page tier in the low-tier block after the truth). A transform or stale metadata recomputes the regions from the segment's entry state; with none usable the read refuses `page_projection_stale`, never raw text. Trusted stored-space reads give the overlaid stored stream. `projectedLayout` (cached on the handle), `projectedTotals`, `projectedLineStart` and `projectedOutline` (outline from stored metadata, no segment text) locate projected bytes; the concatenation equals `projectPageText` of the joined body byte for byte except where a facts fence is longer than a segment (shows less). The chunker (`segment-chunks.ts`) chunks the same projection, so sealed segmented pages carry `MARKDOWN_CHUNKER_VERSION`; `sealSegmentedPage` indexes the overlaid, sanitized timeline lead. Pinned by `test/large-pages/projection-parity.test.ts`, `remote-window-privacy.test.ts` and `sealed-segmented-search.test.ts` (fixture `test/helpers/segmented-privacy-fixture.ts`).
- `src/core/page-body/segment-rewrite.ts` — fence rewrites of a segmented body without holding it as one string (forget strikes, purge drops). Only stored `facts`/`takes` protected regions are decoded and passed, in body order with their region, to a `FenceTransform` (a region crossing forced cuts is joined with its neighbours, refused above `PAGE_MAX_BYTES`). `rewriteLiveSegmentedFences` re-stages the live body through `prepareSegmentedBody` from the segment stream with the changed units replaced and flips it in the caller's transaction (trust tier and soft delete kept; null when nothing changed); `rewriteSegmentedGeneration` rebuilds one retained generation under its own number and updates its versions' hash and size; `rewrittenContentHash` streams the hash of a rewritten generation; `segmentedBodyContains` searches a body segment by segment with the previous segment's tail carried over. Tests: `test/large-pages/purge-segments.test.ts`, `forget-scope.test.ts`, `page-purge-segments.test.ts`.
diff --git a/docs/guides/memory-boundaries.md b/docs/guides/memory-boundaries.md
index 37d1095b40..55d2b09f52 100644
--- a/docs/guides/memory-boundaries.md
+++ b/docs/guides/memory-boundaries.md
@@ -88,14 +88,16 @@ asks before `gbrain embed --held --max-usd <N>`.
A page stays one page whatever its size: one slug, one title, one set of
links. Size no longer decides whether search can find it. Every Markdown page
-up to 24 MiB (25,165,824 bytes) is stored, chunked and keyword-indexed when it
-is written, on every engine. Don't split a page by hand to make it searchable.
+up to the page ceiling is stored, chunked and keyword-indexed when it is
+written: 256 MiB on Postgres and 128 MiB on PGLite (`pages.max_bytes` lowers
+it), or 24 MiB (25,165,824 bytes) while [segmented storage](#segmented-page-storage)
+is off. Don't split a page by hand to make it searchable.
| Page body | Keyword search | Meaning (vector) search |
| --- | --- | --- |
| Up to 1 MiB | right after the write | right after the write |
-| Over 1 MiB, up to 24 MiB (a *large* page) | right after the write | after the write commits, when the stale sweep embeds it (`gbrain embed --stale`, sync's embed pass, autopilot) |
-| Over 24 MiB | refused with [`file_too_large`](write-refusals.md#file_too_large); nothing is stored | — |
+| Over 1 MiB, up to the page ceiling (a *large* page) | right after the write | after the write commits, when the stale sweep embeds it (`gbrain embed --stale`, sync's embed pass, autopilot) |
+| Over the page ceiling | refused with [`file_too_large`](write-refusals.md#file_too_large); nothing is stored | — |
Code files keep a lower limit; see [limits per entry point](#large-page-limits).
@@ -112,7 +114,7 @@ An operator who set a lower `content_sanity.bytes_block` (the
stops embedding above that value: such a page is stored with an `embed_skip`
marker and gets no vectors, but it is still chunked, so keyword search finds
it. The same holds for any page with an `embed_skip` marker. The default is
-the 24 MiB ceiling, so nothing is skipped for size unless someone lowered it.
+the page ceiling, so nothing is skipped for size unless someone lowered it.
**What a write says about size.** `put_page`, `remember` and sync receipts
carry the same field for a large or `embed_skip` page, so the writer learns on
@@ -131,8 +133,39 @@ An ordinary page carries no field.
| `skipped` | `oversized` | Over the operator's `bytes_block`: chunked and keyword-searchable, never embedded. |
| `skipped` | `operator_marker` | Another `embed_skip` marker: chunked and keyword-searchable, never embedded. |
-A body over the 24 MiB ceiling has no receipt: the write is refused as
-`request_too_large`.
+A body over the page ceiling, or `put_page` content over 24 MiB, has no
+receipt: the write is refused as `request_too_large`.
+
+<a id="segmented-page-storage"></a>
+### Segmented page storage
+
+A page over 1 MiB is stored as segments of about 256 KiB instead of one text
+column (`pages.segmented_storage`, on by default). Reading a window, an
+outline or a chunk's context costs the size of the window, not the page, and
+a rewrite re-indexes only the segments that changed. Pages at or under 1 MiB
+are stored exactly as before; a segmented page goes back to one column when a
+write leaves it at or under 512 KiB.
+
+A body that arrives as one string (`put_page`, `put_pages`, `capture` content
+and `gbrain put` stdin) stays limited to 24 MiB per call. A larger page comes
+in by `gbrain import` or `gbrain sync` of its file. On a source backed by
+files that is only the file at its own place in the checkout, which gbrain
+never rewrites; a database-only source takes it by `gbrain import`.
+
+The switch stays off while an older gbrain writes to the same brain: a
+writer older than the release that turned it on, or one that stamps no
+version, that admitted or published a managed write in the last 7 days keeps
+new pages inline, even when the setting is `on`. `gbrain doctor` check
+`segmented_storage` shows the configured and effective value and names each
+blocking host by UUID. Run `gbrain upgrade` there; the hold clears 7 days
+after that writer's last write. An older binary that writes without managed
+persistence (a classic brain shared by several hosts) is not detected, so
+upgrade every host before writing pages over 1 MiB.
+
+While the switch is off (`gbrain config set pages.segmented_storage off`, or
+held by an older writer), new pages are stored inline up to 24 MiB as before.
+Pages already stored in segments stay readable and exportable; a write that
+would leave one over 24 MiB is refused until the switch is on again.
<a id="large-page-limits"></a>
### Limits per entry point
@@ -143,8 +176,8 @@ wrong with the page.
| Entry point | Limit | What to do above it today |
| --- | --- | --- |
-| Markdown import and sync (`gbrain import`, `gbrain sync`, the managed sync blob read) | 24 MiB | — |
-| CLI stdin (`gbrain put`, `gbrain capture --stdin`) | 24 MiB (was 5 MB) | — |
+| Markdown import and sync (`gbrain import`, `gbrain sync`, the managed sync blob read) | the page ceiling: 256 MiB on Postgres, 128 MiB on PGLite (24 MiB while segmented storage is off); above 24 MiB on a source backed by files, only from the file's own place in the checkout | — |
+| CLI stdin (`gbrain put`, `gbrain capture --stdin`) | 24 MiB (was 5 MB) | `gbrain import` the file |
| MCP stdio (local agents, `gbrain serve`) | 64 MiB per JSON-RPC message (the MCP SDK default of 10 MiB is raised), so a JSON-escaped page at the ceiling fits | — |
| MCP over HTTP (`gbrain serve --http`) | 4 MiB request body (the MCP SDK default) | the same: sync or the CLI on the brain host (chunked uploads arrive in a later release) |
| Legacy HTTP transport | 1 MiB (`GBRAIN_HTTP_MAX_BODY_BYTES`) | the same |
@@ -153,7 +186,7 @@ wrong with the page.
| Local persistence socket (IPC) | 32 MiB per frame, JSON-escaped | nothing for ordinary text; only a pathological page (mostly quotes or backslashes) reaches it below the ceiling |
| Pre-push secret scan | 25 MiB per file; gbrain never writes a canonical file over it | — |
| GitHub | warns at 50 MB, rejects at 100 MB | — |
-| Export | aborts on a page over 32 MiB, which the 24 MiB ceiling makes unreachable | — |
+| Export | streams a page stored in segments, up to the page ceiling; aborts on an inline page whose payload is over 32 MiB, which the 24 MiB ceiling makes unreachable | — |
| Company-brain inspection | 5 MB per file | unchanged |
| Transcript ingest input (Claude Code `.jsonl`) | 10 MiB by default, 50 MiB hard cap | unchanged |
| Code files | 5 MB | unchanged |
@@ -165,7 +198,7 @@ describes how to read the next window.
**Cost.** Chunking and keyword indexing run locally and cost nothing.
Embedding a large page costs about $0.15 per 10 MB at the default embedding
-model, so a page at the 24 MiB ceiling costs about $0.40. Each page has a paid
+model, so a 24 MiB page costs about $0.40 and one at the 256 MiB ceiling about $4. Each page has a paid
spend cap, `embed.max_usd_per_page` (default $2), covering its embedding at
every paid entry point (the stale sweep, `gbrain embed`, the post-write
embedding job). A large page uses the free title context tier, never paid
diff --git a/docs/guides/windowed-reads.md b/docs/guides/windowed-reads.md
index ca5fbdbffd..42b824234f 100644
--- a/docs/guides/windowed-reads.md
+++ b/docs/guides/windowed-reads.md
@@ -92,8 +92,9 @@ refusal instead of a partial page: upgrade it (`gbrain upgrade`).
## page_body_segmented
-The page's body is stored in segments (pages over 1 MiB with
-`pages.segmented_storage` on), and the command or tool that hit it reads or
+The page's body is stored in segments (a page over 1 MiB written while
+`pages.segmented_storage` is on, the default; see
+[segmented page storage](memory-boundaries.md#segmented-page-storage)), and the command or tool that hit it reads or
writes the whole body as one string. It stopped before reading or changing
anything, so the page is intact. Read the page's revision and stored size with
`get_page` `body: "none"` (`gbrain get --body none <slug>`; the size is
diff --git a/docs/storage-tiering.md b/docs/storage-tiering.md
index 3bfac52b45..4307073308 100644
--- a/docs/storage-tiering.md
+++ b/docs/storage-tiering.md
@@ -344,7 +344,13 @@ completed run prints `Exported N pages` (or `Restored N pages`).
Enumeration uses 256-key batches, not OFFSET or a total-page cap. Private on-disk
SQLite staging is bounded to 8 GiB, individual payloads/withdrawal ledgers to 32 MiB,
-and snapshot collection to ten minutes with a 60-second statement timeout. Reaching
+and snapshot collection to ten minutes with a 60-second statement timeout. A page
+stored in segments (over 1 MiB, see
+[segmented page storage](guides/memory-boundaries.md#segmented-page-storage)) is
+streamed to a staged file instead: its limit is the page ceiling plus 8 MiB of
+metadata (256 MiB on Postgres, 128 MiB on PGLite), it needs that much free space
+plus 512 MiB on the staging filesystem, and each MiB of it adds a second to the
+collection limit. Reaching
a bound is failure, not truncation or success. Use `--source`, `--type` or
`--slug-prefix` to make smaller snapshots. These are fixed safety limits, not a
promise about export duration or a paid-work budget. No model provider is called.
diff --git a/llms-full.txt b/llms-full.txt
index 400d7ed1c5..ab5cce79d9 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -5582,6 +5582,7 @@ and the fix is the read-only `gbrain migrate --to postgres --plan --json`.
| Cost | Free | Supabase Pro ($25/mo) |
| Concurrency | Single process | Connection pooling |
| Backups | Manual (file copy) | Managed by Supabase |
+| Largest page | 128 MiB, stored in segments (`pages.max_bytes`) | 256 MiB, stored in segments (`pages.max_bytes`) |
**Migration:** on a PGLite brain, `gbrain migrate --to postgres` (alias `--to supabase`) graduates the brain to Postgres. Without `--yes` it prints the plan and exits 3; `--yes --expect <plan_hash>` runs it. Graduation drains pending writes, copies every table verbatim with its primary keys (pages, facts, takes, versions, links, timeline, embeddings, transcripts and paid caches, request history and withdrawals, token and OAuth rows) into a fenced target, verifies row counts and digests, runs `gbrain doctor` on the target, and only then flips routing. It works for brains with write history and for managed brains. The PGLite data dir is retained as `<path>.graduated-<run_id>` and a tombstone file takes its place. Walkthrough, recovery by error code, rollback and what stays on this computer: [Move a PGLite brain to Postgres](guides/move-to-postgres.md).
diff --git a/src/commands/doctor/checks/graph-health.ts b/src/commands/doctor/checks/graph-health.ts
index ee1d51e914..62bd08eaa2 100644
--- a/src/commands/doctor/checks/graph-health.ts
+++ b/src/commands/doctor/checks/graph-health.ts
@@ -337,6 +337,7 @@ export const timelineHistoryEntry: DoctorEntry = {
'foreign_ownership_marker',
'unbound_source',
'writer_version',
+ 'segmented_storage',
'self_capture',
'vector_plan',
'keyword_plan',
diff --git a/src/commands/doctor/checks/segmented-storage.ts b/src/commands/doctor/checks/segmented-storage.ts
new file mode 100644
index 0000000000..c4a12436c2
--- /dev/null
+++ b/src/commands/doctor/checks/segmented-storage.ts
@@ -0,0 +1,45 @@
+import type { BrainEngine } from '../../../core/engine.ts';
+import type { Check } from '../../doctor.ts';
+import { agentFix, checkError, doctorVerify, infoCheck } from '../check-fix.ts';
+import { PAGE_BODY_CONFIG_KEYS, parseSegmentedStorage, readPageBodyPolicy, segmentedWriterBlockers, SEGMENTED_WRITER_WINDOW_DAYS } from '../../../core/page-body/limits.ts';
+import { SEGMENTED_WRITER_FLOOR } from '../../../core/persistence/writer-versions.ts';
+
+const NAME = 'segmented_storage';
+const DOCS = 'docs/guides/memory-boundaries.md#segmented-page-storage';
+const SAMPLE = 20;
+const enableFix = (why: string) => agentFix(['gbrain', 'config', 'set', PAGE_BODY_CONFIG_KEYS.segmentedStorage, 'on'], why, NAME, { actor: 'user', docs: DOCS });
+
+/**
+ * Wave B activation gate: the configured `pages.segmented_storage`, the value writes use, and the recent
+ * writers (committed requests in the last seven days) older than SEGMENTED_WRITER_FLOOR or unstamped that keep
+ * it off. While it is off, pages over 1 MiB are written inline up to 24 MiB; stored segmented pages stay readable.
+ */
+export async function segmentedStorageCheck(engine: BrainEngine): Promise<Check> {
+ try {
+ const configured = parseSegmentedStorage(await engine.getConfig(PAGE_BODY_CONFIG_KEYS.segmentedStorage));
+ const blockers = await segmentedWriterBlockers(engine, { fresh: true });
+ const policy = await readPageBodyPolicy(engine);
+ const listed = blockers.slice(0, SAMPLE).map(row => ({ host_id: row.host_id, principal: row.principal, role: row.role, version: row.version_label,
+ last_seen: row.last_seen, clears_at: row.last_seen ? new Date(Date.parse(row.last_seen) + SEGMENTED_WRITER_WINDOW_DAYS * 86_400_000).toISOString() : null }));
+ const details = { configured, effective: policy.segmented ? 'on' : 'off', max_bytes: policy.maxBytes, floor: SEGMENTED_WRITER_FLOOR,
+ window_days: SEGMENTED_WRITER_WINDOW_DAYS, blockers: listed, truncated: blockers.length > SAMPLE, docs: DOCS };
+ if (configured === 'off') return infoCheck(NAME, 'Segmented page storage is off by choice (pages.segmented_storage=off): pages over 1 MiB are stored inline up to 24 MiB; pages already stored in segments stay readable.',
+ 'disabled_by_choice', enableFix('Turns segmented storage back on: pages over 1 MiB are stored in segments, up to the engine ceiling.'), details);
+ if (configured === 'invalid') return { name: NAME, status: 'warn', details, fix: enableFix('Replaces the unrecognized value with on, the default.'),
+ message: 'pages.segmented_storage holds an unrecognized value, so segmented page storage is off. Set it to on (the default) or off.' };
+ if (blockers.length) {
+ const hosts = listed.map(row => `host ${row.host_id ?? 'unknown (not recorded)'} (principal ${row.principal}) ${row.role} ${row.version}, last seen ${row.last_seen}`);
+ return { name: NAME, status: 'warn', details,
+ message: `Segmented page storage is configured ${configured === 'on' ? 'on' : 'on by default'} but held off: ${blockers.length} writer(s) older than v${SEGMENTED_WRITER_FLOOR} `
+ + `committed a request in the last ${SEGMENTED_WRITER_WINDOW_DAYS} days: ${hosts.join('; ')}${blockers.length > SAMPLE ? ` (first ${SAMPLE} shown)` : ''}. `
+ + 'An older writer does not understand segmented pages, so pages over 1 MiB are written inline up to 24 MiB until it is upgraded. '
+ + `The hold clears ${SEGMENTED_WRITER_WINDOW_DAYS} days after each one's last request (clears_at).`,
+ fix: { argv: ['gbrain', 'upgrade'], consent: [], actor: 'host_admin', requires_exclusive: false, verify: doctorVerify(NAME), docs: DOCS,
+ why: 'Run on each host doctor names (by host UUID), then restart its gbrain processes; the hold clears once no older writer has committed a request for seven days.' } };
+ }
+ return { name: NAME, status: 'ok', details,
+ message: `Segmented page storage is on: pages over 1 MiB are stored in segments, up to ${policy.maxBytes} bytes on this ${engine.kind === 'pglite' ? 'PGLite' : 'Postgres'} brain.` };
+ } catch (error) {
+ return checkError(NAME, 'read the segmented storage gate', error, { details: { configured: 'unknown', effective: 'unknown', docs: DOCS } });
+ }
+}
diff --git a/src/commands/doctor/wave-checks.ts b/src/commands/doctor/wave-checks.ts
index 2c438a4620..df4cf4848b 100644
--- a/src/commands/doctor/wave-checks.ts
+++ b/src/commands/doctor/wave-checks.ts
@@ -243,6 +243,13 @@ export const WAVE_CHECKS: readonly WaveCheckSpec[] = [
count: d => Number(d.count ?? 0),
run: async engine => (await import('./checks/writer-version.ts')).writerVersionCheck(engine),
},
+ {
+ id: 'segmented_storage', resolution: 'operator', registration: 'wave',
+ impact: 'A recent writer older than this release keeps segmented page storage off, so pages over 1 MiB are written inline up to 24 MiB',
+ instruction: 'Run `gbrain upgrade` on each host doctor names (by host UUID), then restart its gbrain processes; the hold clears seven days after that writer\'s last request.',
+ count: d => (Array.isArray(d.blockers) ? d.blockers.length : 0),
+ run: async engine => (await import('./checks/segmented-storage.ts')).segmentedStorageCheck(engine),
+ },
{
id: 'self_capture', resolution: 'operator', registration: 'wave',
count: d => Number(d.classified ?? 0),
diff --git a/src/commands/export.ts b/src/commands/export.ts
index b7d26961f0..58a8344de3 100644
--- a/src/commands/export.ts
+++ b/src/commands/export.ts
@@ -12,7 +12,7 @@ import { ExportStage, EXPORT_SNAPSHOT_MS, EXPORT_STREAM_BYTES_PER_MS, exportPath
import { publishExport } from '../core/export-publish.ts';
import { nativeFileTarget } from '../core/persistence/native-file-target.ts';
import { readExportPage, readExportWithdrawals, segmentedExportMarkdown } from '../core/export-snapshot.ts';
-import { readPageBodyPolicy } from '../core/page-body/limits.ts';
+import { readPageBodyPolicy, segmentedPageCeiling } from '../core/page-body/limits.ts';
import { isSegmentedPage } from '../core/page-body/page-shape.ts';
function option(args: string[], name: string): string | undefined {
@@ -69,11 +69,12 @@ a fresh directory. See docs/storage-tiering.md#safe-export.`);
const storage = restoreOnly && repo ? loadStorageConfig(repo) : null;
if (restoreOnly && !storage) throw new Error('--restore-only requires a storage tiering config (gbrain.yml with a storage section).');
const payloadLimit = exportPayloadLimit((await readPageBodyPolicy(tx)).maxBytes);
+ const segmentedLimit = exportPayloadLimit(segmentedPageCeiling(tx.kind));
let cursor = '0';
for (;;) {
checkDeadline();
- const batch = await tx.executeRaw<{ id: string; slug: string; source_id: string; source_path: string | null; source_path_bytes: number; raw_count: number; bytes: number }>(
- `SELECT p.id::text, left(p.slug,4097) AS slug, p.source_id, left(p.source_path,4097) AS source_path, octet_length(p.source_path) AS source_path_bytes,
+ const batch = await tx.executeRaw<{ id: string; segmented: boolean; slug: string; source_id: string; source_path: string | null; source_path_bytes: number; raw_count: number; bytes: number }>(
+ `SELECT p.id::text, p.body_storage='segmented' AS segmented, left(p.slug,4097) AS slug, p.source_id, left(p.source_path,4097) AS source_path, octet_length(p.source_path) AS source_path_bytes,
(SELECT count(*) FROM raw_data r WHERE r.page_id=p.id) AS raw_count,
CASE WHEN p.body_storage='segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth)::bigint + octet_length(p.timeline) END
+ octet_length(p.frontmatter::text)
@@ -96,7 +97,7 @@ a fresh directory. See docs/storage-tiering.md#safe-export.`);
if (!isDbOnly(key.slug, storage)) continue;
if (existsSync(nativeFileTarget(repo, restoreFilePath(repo, key.slug, key.source_path, Number(key.source_path_bytes), await scannerSlugRootMode(tx, batchSource, repo))))) continue;
}
- if (Number(key.bytes) > payloadLimit) throw new Error('Export page payload limit exceeded. No destination output was published.');
+ if (Number(key.bytes) > (key.segmented ? segmentedLimit : payloadLimit)) throw new Error('Export page payload limit exceeded. No destination output was published.');
const snapshot = await readExportPage(tx, key, withdrawals);
const page = snapshot.page;
// #5966: the slug stamp rule lives in slugStampedFrontmatter (markdown.ts), shared with every render.
@@ -105,7 +106,7 @@ a fresh directory. See docs/storage-tiering.md#safe-export.`);
if (isSegmentedPage(page)) {
streamedBytes += Number(key.bytes);
const head = serializeMarkdown(frontmatter, '', '', meta).slice(0, -1);
- await staged.addStream(page.slug + '.md', Number(key.bytes), payloadLimit, segmentedExportMarkdown(tx, page, withdrawals, head));
+ await staged.addStream(page.slug + '.md', Number(key.bytes), segmentedLimit, segmentedExportMarkdown(tx, page, withdrawals, head));
} else staged.add(page.slug + '.md', 'file', serializeMarkdown(frontmatter, page.compiled_truth, page.timeline, meta));
const raw = Number(key.raw_count) ? await tx.getRawData(page.slug, undefined, { sourceId: page.source_id, includeDeleted: true }) : [];
if (raw.length) {
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index f52de40059..0a919d61ee 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -641,6 +641,14 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
// #6610: classic unfenced facts on database-only pages.
{ since: '0.60.249.0', text: 'On a brain without managed persistence, `extract_facts` (and the v0.32.2 fence step) now fences unfenced facts of a database-only page (no recorded file and none at its slug path) into the page\'s database body when such a write is database-only (`sync.write_through` off, or on Postgres an unbound source with `persistence.unbound_write=database_only`, which stamps the page `unbound_source`), instead of reporting a missing canonical file and halting the facts fence every run. Without that opt-in the rows stay unfenced and their page skips reconciliation, but they no longer count as pending (`legacyRowsPending`) or trigger the guard; doctor `fence_integrity` lists them under `unbound_legacy_facts` and asks the user about the opt-in, and the migration reports them as `skipped_unbound_source`.' },
{ since: '0.60.249.0', text: 'On a brain without managed persistence, `gbrain restore` / `restore_page` of a soft-deleted page whose recorded file is gone from the checkout now refuses (`source_changed`, detail `canonical_file_absent`) when the restore writes no file, instead of restoring a page the next `gbrain sync --full` deletes again. Put the file back and sync, or pass `--detach` (`detach: true`) to restore it database-only (`database_only_reason=detached`, no `source_path`); a file synced back at its path binds the page again. New doctor check `missing_recorded_files` lists live pages a full sync would delete this way.' },
+ // Wave B PR 2 (segmented page storage, switch on). `since` is 'TBD' until the merge-slot stamp, which also stamps
+ // SEGMENTED_WRITER_FLOOR (persistence/writer-versions.ts) with the same release.
+ { since: 'TBD', text: 'Pages over 1 MiB are now stored in segments: `pages.segmented_storage` is on by default. Reading a window, outline or chunk context of a large page costs the size of the window, not the page, and a rewrite re-indexes only the segments that changed. A page can be up to 256 MiB on Postgres and 128 MiB on PGLite (`pages.max_bytes` lowers it). `put_page`, `put_pages` and `capture` content and `gbrain put` stdin stay limited to 24 MiB per call, so a larger page comes in by `gbrain import` or `gbrain sync` of its file: on a source backed by files only from the file\'s own place in the checkout, which is never rewritten; a database-only source takes it by import. Pages at or under 1 MiB are stored exactly as before. `gbrain config set pages.segmented_storage off` stores new pages inline up to 24 MiB again; pages already stored in segments stay readable.' },
+ { since: 'TBD', text: 'Segmented page storage stays off while an older gbrain writes to the same brain: a writer older than this release, or one that stamps no version, that admitted or published a managed write in the last 7 days keeps new pages over 1 MiB inline up to 24 MiB, even with `pages.segmented_storage` set to `on`. New doctor check `segmented_storage` shows the configured and effective value and names each blocking host; run `gbrain upgrade` there, and the hold clears 7 days after its last write. An older binary that writes without managed persistence is not detected.' },
+ { since: 'TBD', text: 'Pages stored in segments keep at most `versions.segmented_max_per_page` (default 50) version snapshots, and fewer when the old text they pin exceeds `versions.segmented_max_pinned_bytes` (default 64 MiB, never below the page size). A snapshot of such a page records its segment generation instead of copying the body. History of every other page is unchanged.' },
+ { since: 'TBD', text: 'A page over 24 MiB imported or synced from its file is no longer stamped `embed_skip` and `content_flag: oversized` for its size: while `content_sanity.bytes_block` is unset, a segmented page is judged against its page ceiling, and the markup check samples its head, middle and tail as it does for any large page. A `content_sanity.bytes_block` set above 24 MiB no longer holds such a file; one set below the page still stops its embedding.' },
+ { since: 'TBD', text: 'Forget and purge on a page stored in segments now rewrite and re-index only the segments that hold the struck or purged row.' },
+ { since: 'TBD', text: 'Export accepts a page stored in segments up to the page ceiling (was 32 MiB per page), streams it to disk, and still aborts rather than produce a partial export.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 3f4f5581c7..08404481ca 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -57,7 +57,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'enrich': ['--accept-pending', '--access', '--add', '--allowed-operations', '--apply', '--asof', '--audit', '--background', '--bound-slug-prefixes', '--brain', '--client', '--concurrency', '--confirm-destructive', '--conflicts', '--date', '--dated-since', '--days', '--dry-run', '--embedding-dimensions', '--embedding-model', '--entities', '--expect', '--explain', '--federated-read', '--follow', '--force', '--from-index', '--full', '--fuzzy', '--group', '--help', '--http', '--id', '--include-deleted', '--input', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--min-context', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--non-interactive', '--order', '--output', '--page', '--params', '--path', '--phase', '--prefer', '--preview', '--progress-interval', '--progress-json', '--purge', '--quiet', '--rate', '--recent', '--reenrich-after', '--refresh-operations', '--resume', '--row', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--surface', '--thin', '--thin-threshold', '--timeout', '--to', '--trust', '--types', '--updated-after', '--url', '--wait', '--workers', '--yes'],
'errors': ['--brain', '--changed', '--help', '--json', '--source'],
'eval': ['--ab-relational', '--accept-pending', '--against', '--allow-incomplete-judgments', '--allow-mixed-run-config', '--allow-regression', '--asof', '--autocut', '--background', '--baseline', '--batch', '--brain', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--by-type', '--by-type-floor', '--by-type-floor-metric', '--call-plan', '--call-plan-gate', '--candidate', '--capture-pool', '--committed-baseline', '--compare', '--compare-limit', '--concurrent', '--config-a', '--config-b', '--corpus', '--cycles', '--days', '--decide', '--decide-calibration', '--decide-dataset', '--decide-force-on', '--decide-provider', '--decide-threshold', '--dedup-cosine', '--dedup-max-per-page', '--dedup-type-ratio', '--dimensions', '--distance-min', '--draws', '--embed-cache', '--embedder', '--embedding-dimensions', '--embedding-model', '--error-unmatch', '--eval-pool-depth', '--expand', '--expansion', '--expansion-replay', '--expansion-variant-budget', '--explain', '--fact-extractor', '--fact-keys', '--fact-keys-max-usd', '--fact-keys-model', '--fixtures', '--follow', '--force-rechunk', '--format', '--from-capture', '--from-db', '--gold', '--grounding-min', '--harness', '--help', '--include-abstention', '--include-holdout', '--input', '--json', '--judge', '--judge-concurrency', '--judge-model', '--justification', '--k', '--keyword-only', '--limit', '--llm', '--max-pair-chars', '--max-tokens', '--max-usd', '--mcp-only', '--md', '--metric', '--min-recall', '--mode', '--model', '--models', '--modes', '--name-only', '--no-accept-pending', '--no-cache', '--no-embed-cache', '--no-expand', '--no-llm', '--no-trajectory', '--older-than', '--op-expand', '--out', '--output', '--output-dir', '--parallel', '--parity-baseline', '--porcelain', '--progress-interval', '--progress-json', '--qrels', '--queries-file', '--query', '--question-ids', '--questions', '--quiet', '--reader-max-tokens', '--reader-mode', '--receipt-dir', '--record', '--refresh-cache', '--reranker', '--resume-from', '--retrieval-only', '--rrf-k', '--rubric-version', '--runs', '--sample', '--sampling', '--save', '--search-pin', '--seed', '--severity', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--stale', '--status', '--strategy', '--suite', '--suites', '--supabase', '--synopsis-cache', '--synopsis-concurrency', '--synopsis-max-usd', '--task', '--threshold', '--threshold-expected-top1', '--threshold-first-relevant-hit', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-recall-at-k', '--threshold-top1', '--time-scope', '--time-scope-pool', '--timeout', '--tool', '--top-k', '--top-regressions', '--until', '--untracked-files', '--update-baseline', '--usefulness-min', '--vectors', '--verbose', '--verify', '--via-operation', '--wait', '--with-code-intel', '--yes'],
- 'export': ['--accept-pending', '--background', '--brain', '--dir', '--explain', '--fix', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--repo', '--restore-only', '--slug-prefix', '--source', '--timeout', '--type', '--wait'],
+ 'export': ['--accept-pending', '--background', '--body', '--brain', '--dir', '--explain', '--fix', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--repo', '--restore-only', '--slug-prefix', '--source', '--timeout', '--type', '--wait'],
'extract': ['--accept-pending', '--admin-intent', '--after-slug', '--apply', '--apply-preview', '--background', '--backup-verified', '--brain', '--break-lock', '--by-mention', '--catch-up', '--checkpoint', '--client', '--concurrency', '--confirm', '--confirm-relocated-root', '--db-url', '--dir', '--dry-run', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--from-meetings', '--help', '--http', '--id', '--include-frontmatter', '--infer-dates', '--json', '--kind', '--limit', '--manifest', '--ner', '--no-accept-pending', '--pack', '--page', '--path', '--progress-interval', '--progress-json', '--prune-orphans', '--quiet', '--rebuild', '--repair-attendance', '--scopes', '--self-transfer', '--since', '--source', '--source-id', '--stale', '--timeout', '--type', '--verbose', '--wait', '--workers', '--yes'],
'extract-conversation-facts': ['--accept-pending', '--admin-intent', '--background', '--brain', '--concurrency', '--confirm-destructive', '--confirm-relocated-root', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--help', '--input', '--json', '--limit', '--manifest', '--max-cost', '--max-cost-usd', '--max-runtime', '--no-accept-pending', '--no-autopilot-install', '--no-embedding', '--output', '--override-disabled', '--path', '--progress-interval', '--progress-json', '--quiet', '--rate', '--segment-limit', '--self-transfer', '--since', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--types', '--url', '--wait', '--workers', '--yes'],
'facts': ['--admin-intent', '--after-id', '--brain', '--dry-run', '--entity', '--examples', '--expected-state', '--help', '--include-private', '--json', '--limit', '--max-cost-usd', '--max-usd', '--no-conflict-queue', '--no-llm', '--path', '--retry-model', '--since', '--slug', '--source'],
diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.ts
index 85ba5b7973..7c34fb2602 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -292,6 +292,7 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set([
'vector_plan',
'keyword_plan',
'writer_version',
+ 'segmented_storage',
'pgbouncer_prepare',
'pglite_data_dir',
// db-availability loop: engine-fit + repair-recurrence signals.
diff --git a/src/core/import-screen.ts b/src/core/import-screen.ts
index 6d4842b014..9e88ff7722 100644
--- a/src/core/import-screen.ts
+++ b/src/core/import-screen.ts
@@ -113,6 +113,8 @@ export interface ContentDispositionContext {
writeGate?: WriteGateInput;
/** Wave B: the whole body's bytes when `parsed` holds only its head (a streamed page). */
bodyBytes?: number;
+ /** Wave B: the bytes_block a streamed page is judged against while `content_sanity.bytes_block` is unset (its page ceiling). */
+ defaultBytesBlock?: number;
}
export interface ContentDisposition {
@@ -162,7 +164,7 @@ export async function settleContentDisposition(engine: BrainEngine, parsed: Pars
// Disposition for the high-confidence junk path: quarantine (hide) by
// default, or reject (throw → sync-failure) when the operator opts in.
const junkDisposition = sanityCfg.junkDisposition;
- const sanityResult = await carryStoredQuarantineOverride(engine, parsed, assessImportSanity(parsed, sanityCfg, ctx.bodyBytes), { slug, sourceId, stripped: ctx.stripped });
+ const sanityResult = await carryStoredQuarantineOverride(engine, parsed, assessImportSanity(parsed, sanityCfg, ctx.bodyBytes, ctx.defaultBytesBlock), { slug, sourceId, stripped: ctx.stripped });
if (!sanityDisabled && !sanityResult.shouldQuarantine && sanityResult.flag_reason !== 'oversized' && (parsed.frontmatter[EMBED_SKIP_KEY] as { reason?: unknown } | undefined)?.reason === 'oversized') {
delete parsed.frontmatter[EMBED_SKIP_KEY];
if ((parsed.frontmatter[CONTENT_FLAG_KEY] as { reason?: unknown } | undefined)?.reason === 'oversized') delete parsed.frontmatter[CONTENT_FLAG_KEY];
@@ -320,14 +322,14 @@ export function stripGateOwnedMarkers(parsed: Pick<ParsedMarkdown, 'frontmatter'
/** #6259: a page carrying a current `quarantine_override` keeps the classifier's verdict off (see quarantine-override.ts). */
export function assessImportSanity(page: Pick<ParsedMarkdown, 'compiled_truth' | 'timeline' | 'title' | 'type'> & { frontmatter?: Record<string, unknown> }, cfg: ImportSanityConfig,
- bodyBytes?: number): ContentSanityResult {
+ bodyBytes?: number, defaultBytesBlock?: number): ContentSanityResult {
return withQuarantineOverride(assessContentSanity({
compiled_truth: page.compiled_truth,
...(bodyBytes !== undefined ? { body_bytes: bodyBytes } : {}),
timeline: page.timeline ?? '',
title: page.title,
bytes_warn: cfg.cs.bytes_warn,
- bytes_block: cfg.cs.bytes_block,
+ bytes_block: cfg.cs.bytes_block ?? defaultBytesBlock,
max_markup_ratio: cfg.cs.max_markup_ratio,
prose_check_enabled: cfg.cs.prose_check_enabled,
page_kind: page.type,
diff --git a/src/core/page-body/limits.ts b/src/core/page-body/limits.ts
index 04089e8cec..89194546af 100644
--- a/src/core/page-body/limits.ts
+++ b/src/core/page-body/limits.ts
@@ -3,12 +3,14 @@
* number and config key in one place. The product numbers (ceilings, version
* retention) are open product calls; change them here and nowhere else.
*
- * `pages.segmented_storage` defaults to `off`: while it is off no page is ever
- * segmented, every page stays inline up to `PAGE_MAX_BYTES` (Wave A) and no
- * code path below the inline threshold changes.
+ * `pages.segmented_storage` defaults to `on`, and is effectively on only while
+ * no recent writer predates segmented pages (`segmentedWriterBlockers`). While
+ * it is off no page is newly segmented, every page stays inline up to
+ * `PAGE_MAX_BYTES` (Wave A) and no code path below the inline threshold changes.
*/
import type { BrainEngine } from '../engine.ts';
import { PAGE_INLINE_MAX_BYTES, PAGE_MAX_BYTES } from '../page-size-policy.ts';
+import type { RecentWriterVersion } from '../persistence/writer-versions.ts';
export { PAGE_INLINE_MAX_BYTES };
@@ -84,8 +86,13 @@ export const SEGMENT_TEXT_GC_GRACE_MS = 60 * 60 * 1000;
export const BODY_STAGING_IDLE_MS = 60 * 60 * 1000;
export const BODY_STAGING_HARD_MS = 24 * 60 * 60 * 1000;
+/** A writer below `SEGMENTED_WRITER_FLOOR` keeps the switch off until this many days after its last committed request. */
+export const SEGMENTED_WRITER_WINDOW_DAYS = 7;
+/** The writer-version gate is read at most once per this many ms per engine (a transaction engine shares its root's entry). */
+export const SEGMENTED_WRITER_GATE_TTL_MS = 60_000;
+
export interface PageBodyPolicy {
- /** `pages.segmented_storage = on`. */
+ /** The effective switch: `pages.segmented_storage` is not `off` and no recent writer predates segmented pages. */
segmented: boolean;
/** Largest page body admitted: `PAGE_MAX_BYTES` while the switch is off, else `pages.max_bytes` or the engine ceiling. */
maxBytes: number;
@@ -94,7 +101,7 @@ export interface PageBodyPolicy {
versionsMaxPinnedBytes: number;
}
-type PolicyEngine = Pick<BrainEngine, 'getConfig' | 'kind'>;
+type PolicyEngine = Pick<BrainEngine, 'getConfig' | 'kind' | 'executeRaw'>;
function positiveInt(raw: string | null, fallback: number): number {
if (raw === null || raw.trim() === '') return fallback;
@@ -102,9 +109,35 @@ function positiveInt(raw: string | null, fallback: number): number {
return Number.isSafeInteger(n) && n > 0 ? n : fallback;
}
-/** True when `pages.segmented_storage` is `on` (default `off`). */
-export function parseSegmentedStorage(raw: string | null): boolean {
- return /^(on|true|1|yes)$/i.test((raw ?? '').trim());
+/** The configured `pages.segmented_storage`: unset means the default (`on`); an unrecognized value counts as `off`. */
+export function parseSegmentedStorage(raw: string | null): 'on' | 'off' | 'unset' | 'invalid' {
+ const value = (raw ?? '').trim();
+ if (!value) return 'unset';
+ if (/^(on|true|1|yes)$/i.test(value)) return 'on';
+ return /^(off|false|0|no)$/i.test(value) ? 'off' : 'invalid';
+}
+
+let writerGate = new WeakMap<object, { at: number; blockers: RecentWriterVersion[] }>();
+
+/**
+ * Writers that committed a request in the last `SEGMENTED_WRITER_WINDOW_DAYS` days with a version below
+ * `SEGMENTED_WRITER_FLOOR` or no stamp. Any one keeps segmented storage off. Cached per engine for
+ * `SEGMENTED_WRITER_GATE_TTL_MS`; `fresh` (doctor) reads through.
+ */
+export async function segmentedWriterBlockers(engine: Pick<BrainEngine, 'executeRaw'>, opts: { fresh?: boolean } = {}): Promise<RecentWriterVersion[]> {
+ let root: object = engine;
+ for (let proto = Object.getPrototypeOf(root); proto && !Object.hasOwn(proto, 'constructor'); proto = Object.getPrototypeOf(proto)) root = proto;
+ const cached = writerGate.get(root);
+ if (!opts.fresh && cached && Date.now() - cached.at < SEGMENTED_WRITER_GATE_TTL_MS) return cached.blockers;
+ const { recentWriterVersions, SEGMENTED_WRITER_FLOOR, writerVersionBelowFloor } = await import('../persistence/writer-versions.ts');
+ const blockers = (await recentWriterVersions(engine, SEGMENTED_WRITER_WINDOW_DAYS)).filter(row => writerVersionBelowFloor(row.version, SEGMENTED_WRITER_FLOOR));
+ writerGate.set(root, { at: Date.now(), blockers });
+ return blockers;
+}
+
+/** Test seam: forget cached writer-gate reads. */
+export function _resetSegmentedWriterGateForTests(): void {
+ writerGate = new WeakMap();
}
/** The engine's default segmented ceiling. */
@@ -112,14 +145,19 @@ export function segmentedPageCeiling(kind: BrainEngine['kind']): number {
return kind === 'pglite' ? SEGMENTED_PAGE_CEILING_BYTES.pglite : SEGMENTED_PAGE_CEILING_BYTES.postgres;
}
-/** Read the segmented-storage policy once per write. A configured `pages.max_bytes` never exceeds the engine ceiling. */
+/**
+ * Read the segmented-storage policy once per write. The switch is effectively on when it is not configured
+ * `off` (or an unrecognized value) and no recent writer predates segmented pages; an unreadable gate counts as
+ * blocked. A configured `pages.max_bytes` never exceeds the engine ceiling.
+ */
export async function readPageBodyPolicy(engine: PolicyEngine): Promise<PageBodyPolicy> {
const read = (key: string) => engine.getConfig(key).catch(() => null);
const [switchRaw, maxRaw, retireRaw, versionsRaw, pinnedRaw] = await Promise.all([
read(PAGE_BODY_CONFIG_KEYS.segmentedStorage), read(PAGE_BODY_CONFIG_KEYS.maxBytes), read(PAGE_BODY_CONFIG_KEYS.flipRetireMaxRows),
read(PAGE_BODY_CONFIG_KEYS.versionsMaxPerPage), read(PAGE_BODY_CONFIG_KEYS.versionsMaxPinnedBytes),
]);
- const segmented = parseSegmentedStorage(switchRaw);
+ const setting = parseSegmentedStorage(switchRaw);
+ const segmented = (setting === 'on' || setting === 'unset') && (await segmentedWriterBlockers(engine).catch(() => null))?.length === 0;
const ceiling = segmentedPageCeiling(engine.kind);
return {
segmented,
diff --git a/src/core/page-body/streamed-import.ts b/src/core/page-body/streamed-import.ts
index ed6c7e9ecc..be93c739c0 100644
--- a/src/core/page-body/streamed-import.ts
+++ b/src/core/page-body/streamed-import.ts
@@ -16,15 +16,16 @@
* inference (head: the first 20 lines must be in it); the frontmatter holds
* and the path-authoritative slug; gate-owned marker strip (a quarantine
* override binds the whole body, so it is dropped: fail closed); content
- * sanity (junk patterns read a 2 KB head, size from the stored byte count);
+ * sanity (junk patterns read a 2 KB head and the prose pass the head, middle
+ * and tail windows; size from the stored byte count, against
+ * `content_sanity.bytes_block` or, unset, the page ceiling `pages.max_bytes`);
* type preservation and subtype; provenance,
* effective date, tags, frontmatter aliases; the content hash (resumed per
* segment); the no-op skip; identity dedup by hash (an external `id` holds);
* code-reference edges (per line, skipped when the body has protected
* regions); the read-back check and the gate receipt.
- * - holds: a registered guardrail (it reads the whole payload); the
- * content-sanity prose pass (it runs only when `bytes_block` is above the
- * body size); a write gate that applies to the source's tier; facts or takes
+ * - holds: a registered guardrail (it reads the whole payload); a write gate
+ * that applies to the source's tier; facts or takes
* fences (fence normalization, withdrawal and purge preservation parse the
* whole body); derived entity aliases (a linkable page type); NUL bytes (the
* size check needs the stored byte count before the hash); invalid UTF-8
@@ -45,7 +46,7 @@ import { FRONTMATTER_HEAD_MAX_BYTES, SEGMENT_MAX_BYTES, type PageBodyPolicy } fr
import { PAGE_MAX_BYTES } from '../page-size-policy.ts';
import { classifyImportHold, resolveParsedSubtype, type ParsedMarkdown } from '../markdown.ts';
import { loadImportSanityConfig, settleContentDisposition, stripGateOwnedMarkers } from '../import-screen.ts';
-import { DEFAULT_BYTES_BLOCK, SCAN_HEAD_BYTES } from '../content-sanity.ts';
+import { JUNK_SAMPLE_CHARS } from '../content-sanity.ts';
import { QUARANTINE_OVERRIDE_KEY } from '../quarantine-override.ts';
import { hasGuardrails } from '../guardrails.ts';
import { DEFAULT_WRITE_GATE_CONFIG, writeGateApplies } from '../write-gate.ts';
@@ -128,16 +129,25 @@ async function* regionStream(pieces: readonly BodyPiece[], read: (start: number,
}
}
-/** The first `max` bytes of a region (NUL-free), as text cut on a code-point boundary. */
-async function regionHead(pieces: readonly BodyPiece[], read: (start: number, end: number) => AsyncIterable<Uint8Array>, max: number): Promise<string> {
- const parts: Uint8Array[] = [];
- let bytes = 0;
- for await (const part of regionStream(pieces, (start, end) => read(start, Math.min(end, start + max)), () => undefined)) {
- parts.push(part);
- bytes += part.length;
- if (bytes >= max) break;
+/**
+ * Bytes `[from, from + max)` of a stored body as text, one window of the content-sanity sample (`sampleWindows`
+ * cuts the same head, middle and tail of a string body); a code point cut at either end decodes as U+FFFD.
+ */
+async function bodyWindow(pieces: readonly BodyPiece[], read: (start: number, end: number) => AsyncIterable<Uint8Array>, from: number, max: number): Promise<string> {
+ const parts: Buffer[] = [];
+ let at = 0;
+ for (const piece of pieces) {
+ if (at >= from + max) break;
+ const text = 'text' in piece ? Buffer.from(sanitizeText(piece.text), 'utf8') : null;
+ const length = 'text' in piece ? text!.length : piece.end - piece.start;
+ const start = Math.max(from, at), end = Math.min(from + max, at + length);
+ if (start < end) {
+ if ('text' in piece) parts.push(text!.subarray(start - at, end - at));
+ else for await (const part of read(piece.start + start - at, piece.start + end - at)) parts.push(Buffer.from(part));
+ }
+ at += length;
}
- return utf8Prefix(Buffer.concat(parts), max);
+ return Buffer.concat(parts).toString('utf8');
}
/**
@@ -254,10 +264,11 @@ async function importScanned(engine: BrainEngine, input: { file: FileHandle; bom
const sanity = await loadImportSanityConfig(engine);
if (writeGateApplies(writeGate.tier, sanity.writeGate ?? DEFAULT_WRITE_GATE_CONFIG)) return hold(slug, size, `the write gate scans the whole body of a ${writeGate.tier} page`);
const bodyBytes = scan.truthBytes + (scan.timelineBytes ? 1 + scan.timelineBytes : 0);
- if (!sanity.disabled && (sanity.cs.bytes_block ?? DEFAULT_BYTES_BLOCK) >= bodyBytes) return hold(slug, size, 'the content-sanity prose pass samples the whole body below content_sanity.bytes_block');
- const truthHead = await regionHead(scan.truth, read, SCAN_HEAD_BYTES * 4);
- const head = { ...parsed, compiled_truth: truthHead, timeline: truthHead.length >= SCAN_HEAD_BYTES ? '' : await regionHead(scan.timeline, read, SCAN_HEAD_BYTES * 4) };
- const disposition = await settleContentDisposition(engine, head, { slug, sourceId, stripped: false, writeGate, bodyBytes });
+ const body: BodyPiece[] = [...scan.truth, ...(scan.timelineBytes ? [{ text: '\n' }, ...scan.timeline] : [])];
+ const sample = [0, Math.floor((bodyBytes - JUNK_SAMPLE_CHARS) / 2), bodyBytes - JUNK_SAMPLE_CHARS];
+ const windows = await Promise.all(sample.map(from => bodyWindow(body, read, from, JUNK_SAMPLE_CHARS)));
+ const disposition = await settleContentDisposition(engine, { ...parsed, compiled_truth: windows.join(''), timeline: '' },
+ { slug, sourceId, stripped: false, writeGate, bodyBytes, defaultBytesBlock: input.policy.maxBytes });
const existing = opts.coordinated ? opts.coordinated.snapshot?.page ?? null : await engine.getPage(slug, { sourceId, includeDeleted: true });
if (existing?.deleted_at) return hold(slug, size, 'restoring a deleted page rewrites its body through the inline writer');
if (existing) stabilizeSafetyAssessments(parsed.frontmatter, existing.frontmatter);
diff --git a/src/core/persistence/writer-versions.ts b/src/core/persistence/writer-versions.ts
index 2e67828526..f31c47ed09 100644
--- a/src/core/persistence/writer-versions.ts
+++ b/src/core/persistence/writer-versions.ts
@@ -6,6 +6,13 @@ import type { SqlEngine } from './model.ts';
/** Writers older than this may still delete database-only timeline rows during publication. */
export const WRITER_VERSION_FLOOR = '0.60.5.0';
export const UNSTAMPED_WRITER = 'unstamped (binary older than this release)';
+/**
+ * Writers older than this do not understand segmented page bodies (Wave B): a pre-Wave-B binary reads a segmented
+ * page's NULL body columns, and the release that added segmented storage behind the switch purges, forgets and exports
+ * without its segment texts. A recent one keeps `pages.segmented_storage` effectively off (`page-body/limits.ts`).
+ * Provisional until merge: stamped with the release that turns the switch on, the `since` of its BEHAVIOR_CHANGES row.
+ */
+export const SEGMENTED_WRITER_FLOOR = '0.60.250.0';
/** Numeric comparison on all four components; null when either side is not a version. */
export function compareWriterVersions(a: string, b: string): number | null {
@@ -19,10 +26,10 @@ export function compareWriterVersions(a: string, b: string): number | null {
return 0;
}
export function writerVersionLabel(version: string | null): string { return version ?? UNSTAMPED_WRITER; }
-/** True for a missing stamp or a recorded version below the floor (an unparsable version counts as below). */
-export function writerVersionBelowFloor(version: string | null): boolean {
+/** True for a missing stamp or a recorded version below `floor` (an unparsable version counts as below). */
+export function writerVersionBelowFloor(version: string | null, floor = WRITER_VERSION_FLOOR): boolean {
if (version === null) return true;
- const order = compareWriterVersions(version, WRITER_VERSION_FLOOR);
+ const order = compareWriterVersions(version, floor);
return order === null || order < 0;
}
diff --git a/test/large-pages/managed-streamed-import.test.ts b/test/large-pages/managed-streamed-import.test.ts
index 13e408fe75..1b48666398 100644
--- a/test/large-pages/managed-streamed-import.test.ts
+++ b/test/large-pages/managed-streamed-import.test.ts
@@ -12,7 +12,9 @@
* collects an abandoned preparation's staged rows under the guard. A file that
* changes between admission and preparation publishes nothing; a request_id
* replayed with other bytes is `idempotency_conflict`; with the switch off
- * the refusal is the one before Wave B.
+ * the refusal is the one before Wave B. With the switch unset (default on)
+ * a file-backed source takes a page over 24 MiB only by import of its own
+ * canonical file, never by a managed write of new content.
* 2. Fails when: the journal carries the body, the preparer skips the hash
* check, the publication rewrites the canonical file, or the switch-off
* refusal changes.
@@ -189,6 +191,31 @@ describe('managed import over the single-string ceiling', () => {
}
}), 120_000);
+ test('switch unset (default on): a file over 24 MiB imports only from its place in the canonical root; put_page content stays within 24 MiB', async () => withEnv(env, async () => {
+ for (const engine of engines) {
+ await disposePersistenceConsumer(engine);
+ await engine.unsetConfig('pages.segmented_storage');
+ const f = await fixture(engine);
+ const outside = join(home, `${f.sourceId}-outside.md`);
+ writeFileSync(outside, content);
+ await expect(importManagedFile(engine, outside, 'notes/outside.md', { sourceId: f.sourceId, noEmbed: true }))
+ .rejects.toMatchObject({ code: 'invalid_params', message: `File too large (max ${PAGE_MAX_BYTES} bytes).` });
+ expect(await engine.getPage('notes/outside', { sourceId: f.sourceId })).toBeNull();
+
+ const file = join(f.root, 'notes/inside.md');
+ writeFileSync(file, content);
+ const before = statSync(file);
+ expect(await importManagedFile(engine, file, 'notes/inside.md', { sourceId: f.sourceId, noEmbed: true })).toMatchObject({ slug: 'notes/inside', status: 'imported' });
+ expect((await reconstructedPage(engine, 'notes/inside', f.sourceId)).page.body_storage).toBe('segmented');
+ expect(statSync(file).mtimeMs).toBe(before.mtimeMs);
+
+ const ctx = { engine, remote: false, sourceId: f.sourceId } as OperationContext;
+ await expect(preparePageAdmission(ctx, { operation: 'put_page', params: { slug: 'notes/put-huge', content, source_id: f.sourceId, request_id: randomUUID() } }))
+ .rejects.toMatchObject({ code: 'request_too_large' });
+ expect(await engine.getPage('notes/put-huge', { sourceId: f.sourceId })).toBeNull();
+ }
+ }), 600_000);
+
test('switch off: the refusal is the one before segmented storage', async () => withEnv(env, async () => {
for (const engine of engines) {
await disposePersistenceConsumer(engine);
diff --git a/test/large-pages/segmented-switch.test.ts b/test/large-pages/segmented-switch.test.ts
new file mode 100644
index 0000000000..58ed91ab90
--- /dev/null
+++ b/test/large-pages/segmented-switch.test.ts
@@ -0,0 +1,134 @@
+/**
+ * Wave B PR 2 switch-on (spec 1.1 activation gate, 13 PR 2): `pages.segmented_storage` defaults to on, gated by
+ * the writer versions recorded on committed persistence requests.
+ *
+ * 1. Protects: with no configuration a page over 1 MiB is stored segmented and `pages.max_bytes` is the engine
+ * ceiling; a writer older than SEGMENTED_WRITER_FLOOR (or unstamped) seen in the last seven days keeps writes
+ * inline, even with an explicit `on`, and doctor `segmented_storage` names it with an upgrade fix; once that
+ * observation is gone the next write promotes; an explicit `off` keeps pages inline and reports it as a choice;
+ * a stored segmented page over 32 MiB still exports while the switch is off.
+ * 2. Fails when: the default stays off, the gate ignores old or unstamped writers, an explicit `on` overrides the
+ * gate, a cleared gate keeps writes inline, or export sizes stored segmented pages by the write limit.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { importFromContent } from '../../src/core/import-file.ts';
+import { PAGE_MAX_BYTES } from '../../src/core/page-size-policy.ts';
+import { _resetSegmentedWriterGateForTests, readPageBodyPolicy, segmentedPageCeiling } from '../../src/core/page-body/limits.ts';
+import { declarePersistenceProtocol } from '../../src/core/persistence/protocol.ts';
+import { compareWriterVersions, SEGMENTED_WRITER_FLOOR } from '../../src/core/persistence/writer-versions.ts';
+import { BEHAVIOR_CHANGES } from '../../src/core/behavior-change-notice.ts';
+import { VERSION } from '../../src/version.ts';
+import { localHostId } from '../../src/core/persistence/identity.ts';
+import { segmentedStorageCheck } from '../../src/commands/doctor/checks/segmented-storage.ts';
+import { runExport } from '../../src/commands/export.ts';
+import { conversationPage } from '../helpers/conversation-page.ts';
+import { editRequest, freshBrainFactory, requestFixture } from '../helpers/persistence-request-fixture.ts';
+import { testBackends } from '../helpers/test-backends.ts';
+import { withEnv } from '../helpers/with-env.ts';
+
+const content = conversationPage(2 * 1024 * 1024, { seed: 61 });
+
+async function quietExport(engine: BrainEngine, out: string): Promise<void> {
+ const { log, error } = console;
+ const exit = process.exit;
+ const messages: string[] = [];
+ console.log = console.error = (...args: unknown[]) => { messages.push(args.join(' ')); };
+ process.exit = ((code: number) => { throw new Error(`EXIT:${code} ${messages.join('\n')}`); }) as never;
+ try { await runExport(engine, ['--dir', out]); } finally { console.log = log; console.error = error; process.exit = exit; }
+}
+
+async function storage(engine: BrainEngine, slug: string): Promise<string | undefined> {
+ return (await engine.executeRaw<{ body_storage: string }>('SELECT body_storage FROM pages WHERE slug=$1', [slug]))[0]?.body_storage;
+}
+
+test('SEGMENTED_WRITER_FLOOR is the release of the writer-gate BEHAVIOR_CHANGES row once stamped, and never above this build', () => {
+ const row = BEHAVIOR_CHANGES.find(c => typeof c.text === 'string' && c.text.startsWith('Segmented page storage stays off while an older gbrain'));
+ expect(row).toBeDefined();
+ if (row!.since !== 'TBD') expect(row!.since).toBe(SEGMENTED_WRITER_FLOOR);
+ expect(compareWriterVersions(SEGMENTED_WRITER_FLOOR, VERSION)).toBeLessThanOrEqual(0);
+});
+
+for (const kind of testBackends()) {
+ describe(`segmented storage switch: ${kind}`, () => {
+ let factory: Awaited<ReturnType<typeof freshBrainFactory>>;
+ let engine: BrainEngine;
+ let home: string;
+ beforeAll(async () => {
+ home = mkdtempSync(join(tmpdir(), 'gbrain-segmented-switch-'));
+ factory = await freshBrainFactory(kind, process.env.DATABASE_URL);
+ }, 120_000);
+ afterAll(async () => {
+ await factory?.dispose();
+ rmSync(home, { recursive: true, force: true });
+ });
+ beforeEach(async () => {
+ engine = await factory.fresh();
+ _resetSegmentedWriterGateForTests();
+ });
+ const inHome = <T>(fn: () => Promise<T>) => withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, fn);
+
+ test('default on: a page over 1 MiB is stored segmented and pages.max_bytes is the engine ceiling', async () => {
+ expect(await engine.getConfig('pages.segmented_storage')).toBeNull();
+ expect(await readPageBodyPolicy(engine)).toMatchObject({ segmented: true, maxBytes: segmentedPageCeiling(engine.kind) });
+ expect((await importFromContent(engine, 'notes/default-on', content, { noEmbed: true })).status).toBe('imported');
+ expect(await storage(engine, 'notes/default-on')).toBe('segmented');
+ expect(await segmentedStorageCheck(engine)).toMatchObject({ status: 'ok', details: { configured: 'unset', effective: 'on', blockers: [] } });
+ }, 120_000);
+
+ test('a recent writer below the floor keeps writes inline, even with an explicit on; once it is gone the next write promotes', async () => inHome(async () => {
+ const requests = await requestFixture(engine);
+ const published = await requests.publish(await requests.admit('page'));
+ await editRequest(engine, published.id, "admitter_version='0.60.200.0',consumer_version='0.60.200.0'");
+ for (const setting of [null, 'on']) {
+ if (setting) await engine.setConfig('pages.segmented_storage', setting);
+ _resetSegmentedWriterGateForTests();
+ expect(await readPageBodyPolicy(engine)).toMatchObject({ segmented: false, maxBytes: PAGE_MAX_BYTES });
+ const slug = `notes/held-${setting ?? 'default'}`;
+ expect((await importFromContent(engine, slug, content, { noEmbed: true })).status).toBe('imported');
+ expect(await storage(engine, slug)).toBe('inline');
+ }
+ const check = await segmentedStorageCheck(engine);
+ expect(check).toMatchObject({ status: 'warn', details: { configured: 'on', effective: 'off' }, fix: { argv: ['gbrain', 'upgrade'], actor: 'host_admin' } });
+ expect((check.details!.blockers as Array<{ host_id: string; version: string }>).map(row => [row.host_id, row.version]))
+ .toContainEqual([localHostId(), '0.60.200.0']);
+ expect(check.message).toContain('0.60.200.0');
+
+ await editRequest(engine, published.id, 'admitter_version=NULL,consumer_version=NULL');
+ _resetSegmentedWriterGateForTests();
+ expect((await readPageBodyPolicy(engine)).segmented).toBe(false);
+
+ await engine.transaction(async tx => {
+ await declarePersistenceProtocol(tx);
+ await tx.executeRaw('DELETE FROM persistence_effects WHERE request_id=$1::uuid', [published.id]);
+ await tx.executeRaw('DELETE FROM persistence_requests WHERE id=$1::uuid', [published.id]);
+ });
+ _resetSegmentedWriterGateForTests();
+ expect((await readPageBodyPolicy(engine)).segmented).toBe(true);
+ expect((await importFromContent(engine, 'notes/held-on', `${content}\n\nOne more turn.\n`, { noEmbed: true })).status).toBe('imported');
+ expect(await storage(engine, 'notes/held-on')).toBe('segmented');
+ expect(await segmentedStorageCheck(engine)).toMatchObject({ status: 'ok', details: { effective: 'on' } });
+ }), 120_000);
+
+ test('a stored segmented page over the 32 MiB inline export limit still exports while the switch is off', async () => {
+ expect((await importFromContent(engine, 'notes/stored', content, { noEmbed: true })).status).toBe('imported');
+ expect(await storage(engine, 'notes/stored')).toBe('segmented');
+ await engine.executeRaw('UPDATE pages SET body_bytes=$2 WHERE slug=$1', ['notes/stored', 40 * 1024 * 1024]);
+ await engine.setConfig('pages.segmented_storage', 'off');
+ const out = join(home, `export-${kind}`);
+ await quietExport(engine, out);
+ expect(readFileSync(join(out, 'notes/stored.md'), 'utf8')).toContain(content.trimEnd().slice(-120));
+ }, 120_000);
+
+ test('explicit off keeps pages inline and doctor reports it as a choice', async () => {
+ await engine.setConfig('pages.segmented_storage', 'off');
+ expect((await importFromContent(engine, 'notes/off', content, { noEmbed: true })).status).toBe('imported');
+ expect(await storage(engine, 'notes/off')).toBe('inline');
+ expect(await segmentedStorageCheck(engine)).toMatchObject({ status: 'ok', severity: 'info', readiness_state: 'disabled_by_choice',
+ details: { configured: 'off', effective: 'off' }, fix: { argv: ['gbrain', 'config', 'set', 'pages.segmented_storage', 'on'] } });
+ }, 120_000);
+ });
+}
diff --git a/test/large-pages/streamed-content-sanity.test.ts b/test/large-pages/streamed-content-sanity.test.ts
new file mode 100644
index 0000000000..e37024771e
--- /dev/null
+++ b/test/large-pages/streamed-content-sanity.test.ts
@@ -0,0 +1,100 @@
+/**
+ * Wave B PR 2 switch-on: content sanity of a streamed page (a file over the 24 MiB single-string ceiling).
+ *
+ * 1. Protects: with `content_sanity.bytes_block` unset, the size rule of a segmented page is its page ceiling
+ * (`pages.max_bytes`), so a streamed page is chunked and keyword-searchable and its frontmatter gets no
+ * `embed_skip` / `content_flag: oversized`; the prose pass judges its head, middle and tail windows (a
+ * markup wall is flagged `markup_heavy` and stays searchable); an operator's lower bytes_block still
+ * soft-blocks it (`embed_skip`, chunked for keyword search, #6722); a bytes_block above the body size
+ * imports instead of holding the file.
+ * 2. Fails when: the default block stays at 24 MiB, the prose pass holds the file or reads only its head.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { importFromFile } from '../../src/core/import-file.ts';
+import { PAGE_MAX_BYTES } from '../../src/core/page-size-policy.ts';
+import { readPageBodyPolicy } from '../../src/core/page-body/limits.ts';
+import { conversationBody } from '../helpers/conversation-page.ts';
+
+const BYTES = PAGE_MAX_BYTES + 1024 * 1024;
+let engine: PGLiteEngine;
+let dir: string;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ dir = mkdtempSync(join(tmpdir(), 'gbrain-streamed-sanity-'));
+}, 120_000);
+
+afterAll(async () => {
+ await engine.disconnect();
+ rmSync(dir, { recursive: true, force: true });
+});
+
+beforeEach(async () => {
+ await engine.executeRaw('DELETE FROM pages');
+ await engine.unsetConfig('content_sanity.bytes_block');
+});
+
+async function imported(name: string, body: string) {
+ const file = join(dir, `${name}.md`);
+ writeFileSync(file, `---\ntype: note\ntitle: ${name}\n---\n\n${body}\n`);
+ const result = await importFromFile(engine, file, `notes/${name}.md`, { noEmbed: true, bodyPolicy: await readPageBodyPolicy(engine) });
+ const [row] = await engine.executeRaw<{ body_storage: string; frontmatter: Record<string, unknown>; chunks: number }>(
+ `SELECT p.body_storage, p.frontmatter, (SELECT count(*)::int FROM content_chunks c WHERE c.page_id=p.id) AS chunks FROM pages p WHERE p.slug=$1`, [`notes/${name}`]);
+ return { result, row };
+}
+
+/** A body of `bytes` with a markup wall (HTML tags and table pipes, no prose) at its head, middle or tail. */
+function markupAt(where: 'head' | 'middle' | 'tail', bytes: number): string {
+ const wall = '<div class="nav"><span></span></div>\n| | | |\n'.repeat(4096);
+ const prose = conversationBody(bytes - wall.length, { seed: 71 });
+ const cut = where === 'head' ? 0 : where === 'tail' ? prose.length : prose.indexOf('\n\n', prose.length >> 1) + 2;
+ return `${prose.slice(0, cut)}${wall}${prose.slice(cut)}`;
+}
+
+describe('content sanity of a streamed page', () => {
+ test('bytes_block unset: the page ceiling is the size rule, so the page is chunked and its frontmatter is not stamped', async () => {
+ const { result, row } = await imported('prose', conversationBody(BYTES, { seed: 72 }));
+ expect(result.error ?? null).toBeNull();
+ expect(result.status).toBe('imported');
+ expect(row!.body_storage).toBe('segmented');
+ expect(row!.frontmatter.embed_skip).toBeUndefined();
+ expect(row!.frontmatter.content_flag).toBeUndefined();
+ expect(row!.chunks).toBeGreaterThan(0);
+ }, 300_000);
+
+ test('the prose pass reads head, middle and tail windows: a markup wall in all three is flagged and stays searchable', async () => {
+ const wall = '<div class="nav"><span></span></div>\n| | | |\n';
+ const { result, row } = await imported('markup', wall.repeat(Math.ceil(BYTES / wall.length)));
+ expect(result.status).toBe('imported');
+ expect(row!.frontmatter.content_flag).toMatchObject({ reason: 'markup_heavy' });
+ expect(row!.frontmatter.embed_skip).toBeUndefined();
+ expect(row!.chunks).toBeGreaterThan(0);
+ for (const where of ['head', 'middle', 'tail'] as const) {
+ const one = await imported(`markup-${where}`, markupAt(where, BYTES));
+ expect(one.result.status).toBe('imported');
+ expect(one.row!.frontmatter.content_flag).toBeUndefined();
+ }
+ }, 600_000);
+
+ test('an operator bytes_block below the page soft-blocks it; one above the page imports it', async () => {
+ await engine.setConfig('content_sanity.bytes_block', String(PAGE_MAX_BYTES));
+ const low = await imported('low-block', conversationBody(BYTES, { seed: 73 }));
+ expect(low.result.status).toBe('imported');
+ expect(low.row!.frontmatter.embed_skip).toMatchObject({ reason: 'oversized' });
+ expect(low.row!.frontmatter.content_flag).toMatchObject({ reason: 'oversized' });
+ expect(low.row!.chunks).toBeGreaterThan(0);
+
+ await engine.setConfig('content_sanity.bytes_block', String(64 * 1024 * 1024));
+ const high = await imported('high-block', conversationBody(BYTES, { seed: 74 }));
+ expect(high.result.error ?? null).toBeNull();
+ expect(high.result.status).toBe('imported');
+ expect(high.row!.frontmatter.embed_skip).toBeUndefined();
+ expect(high.row!.chunks).toBeGreaterThan(0);
+ }, 600_000);
+});
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index a93efe1bb8..09689dcd73 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -83,6 +83,7 @@ test/large-pages/segmented-embedding-paths.test.ts
test/large-pages/segmented-embedding.test.ts
test/large-pages/segmented-shrink-below-ceiling.test.ts
test/large-pages/segmented-storage-visibility.test.ts
+test/large-pages/segmented-switch.test.ts
test/large-pages/segmented-versions.test.ts
test/link-cross-source.test.ts
test/link-preparation-shared-index.test.ts