Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Merge remote-tracking branch 'origin/capy/large-pages-segmented-reads' into capy/large-pages-2s

garrytand0f34f84647c
diff --cc docs/architecture/key-files/core-services-2-continued.md
index 308092d861,4aef8f68bb..913b89dbbe
--- a/docs/architecture/key-files/core-services-2-continued.md
+++ b/docs/architecture/key-files/core-services-2-continued.md
@@@ -17,6 -17,8 +17,9 @@@ The page-state concurrency foundation u
- `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`.
+ - `src/core/page-window/bounded-lead.ts` — leads, snippets and synopses read a bounded prefix, never the whole body: fan-out SQL selects `boundedBodyPrefixSql(alias)` (`left(coalesce(alias.compiled_truth, alias.truth_lead), 65536)`: a segmented page's NULL body falls back to its stored lead; the one COALESCE of body and lead the page body reader ratchet allows by name), `boundedRawPrefix` cuts a body at 64 KiB on a code point, and `overlaidBoundedRows` / `overlaidBoundedPrefix` replace a prefix holding a `gbrain:facts:begin` marker with the prefix of the withdrawal-overlaid body (one batched `readPageSnapshotsBatch` read; a page it no longer returns, or a failed read, gets an empty lead). A segmented page's row carries its stored `truth_lead`; when that lead holds a facts fence it is overlaid alone with the withdrawal ledger the snapshot read returns (`overlayCanonicalBodies`, then the same 64 KiB cut), never by reading segments. `pageLeadSource` gives getPage callers (exact-slug and alias snippets) a page's compiled truth, or a segmented page's `truth_lead` without touching its throwing body getters. `projectedLead` is that prefix through `boundedProjectedPrefix` (`document.ts`). Consumers: the exact-slug tier (`exact-lookup.ts`) and alias injection (`alias-hop.ts`) snippets, relational hydrate, the reflex pointer synopsis (`retrieval-reflex.ts` `safeSynopsis`: world-only reads take the projected prefix, the trusted entity-card widening the raw prefix through its own fence strip), the entity card's hit row and `entity names` leads, and think's anchor and window-floor rows (`think/gather.ts`: the raw overlaid prefix for the trusted local CLI, the projected prefix otherwise). Small pages render as before. Pinned by `test/bounded-lead.test.ts` and `test/large-pages/segmented-leads.test.ts`.
+ - `src/core/page-window/document.ts` — the one read projection every remote window, outline and lead slices: `projectPageText` (fence overlay split, `sanitizeRemoteBody` + `credentialSafeProjection`, timeline after `TIMELINE_SEPARATOR`), `pageDocument` / `readPageDocument` (UTF-8 bytes + timeline byte offset, with the page's fence overlay), `chunkDocumentSpan` + `spanHoldsChunk` (a chunk's stored `projected_byte_*` span mapped into the document and verified), `boundedProjectedPrefix`, `locateChunksByStoredSpans` (byte spans to string offsets in one pass), `DEFAULT_INLINE_BODY_BYTES` (256 KB).
+ - `src/core/page-window/window.ts` — byte/line window arithmetic on a UTF-8 buffer: windows snap to code points and line starts (`windowFrom`, `windowForLines`, `windowForBytes`, `windowAround`; a lone line longer than the window is cut on a code point as `forced_cut`), `pageOutline` (single pass: ATX headings outside code fences, or 64 KiB blocks for pages with fewer than two headings, with date ranges, paged by `from`/`limit`), and the opaque revision-bound cursor (`gpw1.`).
diff --cc src/core/behavior-change-notice.ts
index 0a919d61ee,7b12cf89f2..ff52de7ba1
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@@ -641,14 -641,10 +641,18 @@@ export const BEHAVIOR_CHANGES: Readonly
// #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.' },
+ { since: '0.60.250.0', text: 'Remote agents and token-floor connections now get stored contradiction findings from `find_contradictions` instead of an availability note or a refusal: only findings whose two sides they can read now, each side re-read live with its `source_id` and `trust_tier`, never the stored report text; `min_trust` and the token floor filter instead of refusing. A local `gbrain find-contradictions --source <id>` (or `GBRAIN_SOURCE`) now gets that scoped view instead of the note; the bare command still reads the whole stored run.' },
+ // Pre-W1 integrity wave (belief ledger Q6 + inherited purge read gaps). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.
+ { since: '0.60.251.0', text: 'A take graded only in the database (for example by `grade_takes` on a source without managed persistence) keeps its grade when its page is published again from a fence that has no resolution cells: a prose edit, a re-import, a sync or `revert_version` to a version from before the grade. Before, every such publish erased the grade. A fence that carries resolution cells still writes them, and a take whose claim is edited in place (same row number) now drops the old claim\'s grade.' },
+ { since: '0.60.251.0', text: 'After `purge_fact` or a page purge, no read returns the purged text from what the purge hid: a page a purge hid for re-derivation now reads as missing in `get_page` and `fetch` (even with `include_deleted`) and returns no `get_versions` history, and a page purge now hides rows derived from the page and its facts, as `purge_fact` already did. `purge_fact` now redacts every retained version of a page (it stopped after 5,000), and its receipt\'s `pages` and `page_versions` stores also report a page or version that still states the claim in its title or frontmatter, alongside prose (`out_of_scope: source_prose`).' },
+ // 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 --cc src/core/persistence/writer-versions.ts
index f31c47ed09,2e67828526..55682a0c3c
--- a/src/core/persistence/writer-versions.ts
+++ b/src/core/persistence/writer-versions.ts
@@@ -6,13 -6,6 +6,15 @@@ import type { SqlEngine } from './model
/** 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.
++ * A placeholder equal to the branch's VERSION until the merge-slot stamp, which sets it to the release that turns the
++ * switch on (the `since` of its BEHAVIOR_CHANGES row, pinned by test/large-pages/segmented-switch.test.ts). That
++ * release must be above v0.60.252.0, the release that added segmented storage with the switch off.
+ */
- export const SEGMENTED_WRITER_FLOOR = '0.60.250.0';
++export const SEGMENTED_WRITER_FLOOR = '0.60.252.0';
/** Numeric comparison on all four components; null when either side is not a version. */
export function compareWriterVersions(a: string, b: string): number | null {
diff --cc test/postgres-unit-arms.txt
index 09689dcd73,f857224012..417a9133cf
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@@ -81,9 -81,12 +81,13 @@@ test/large-pages/segmented-body-unreach
test/large-pages/segmented-derived-work.test.ts
test/large-pages/segmented-embedding-paths.test.ts
test/large-pages/segmented-embedding.test.ts
+ test/large-pages/segmented-evidence-read-cost.test.ts
+ test/large-pages/segmented-evidence.test.ts
+ test/large-pages/segmented-leads.test.ts
+ test/large-pages/segmented-search-dedup.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