Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Wave B PR 2 lane 2a: segmented get_page windows, outline, none, markdown digests, streaming gbrain get
garrytana785e0710204
diff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.mdindex d431d7e4c7..ce0b84b4aa 100644--- a/docs/architecture/key-files/core-search-2.md+++ b/docs/architecture/key-files/core-search-2.md@@ -69,7 +69,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `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, a segmented page, or a failed read, gets an empty lead). `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`.- `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.`).+- `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.`). `DocumentSlab` / `slabWindow` run the same arithmetic on a slice of a larger document and shift the result back to document coordinates.- `src/core/search/relational-recall.ts` — the relational recall arm: `parseRelationalQuery` → seed resolution per in-scope source (federated set, scalar source, or every non-archived source for an unscoped caller; a literal `__all__` resolves no seeds, fail-closed) → `relationalFanout` → hydrate, fail-open. Seeds resolve through `resolveEntitySlugWithSource` and a `fallback_slugify` result is dropped (confidence gate D3). The entity resolver never returns meetings, so for an incoming `attended` relation (`Who attended <meeting>?`) a live `meeting` or `event` page whose title is exactly the seed phrase (case-insensitive, unique in the source) is the seed; other relations never seed from titles. Pinned by `test/relational-recall.test.ts`, `test/relational-recall-scope-sources.test.ts` and `test/pack-relation-direction-engine.test.ts`. With `planner` on (`search.relational_planner`, on in balanced/tokenmax), a 2-3 relationship question (`parseRelationalPlan`) runs `runRelationalChain` first: answers then evidence pages, each with a `relational` field; nothing found → the one-hop path; refused → no arm (`meta.plan`). With `orientOneHop` (`search.relational_orient_onehop`, off in every bundle) typed one-hop walks add neighbors reached through links written on the other page. `answerRows` limits the pin and evidence slot to answers. Hydrate selects a bounded body prefix and shows its synopsis through `page-window/bounded-lead.ts`. Pinned by `test/relational-recall.test.ts`.- `src/core/search/relational-rerank-pin.ts` — relational-arm rows bypass reranker DEMOTION (ranker wave, receipt R1 in `scripts/r1-namedthing-rerank-ab.ts`: on NamedThingBench's 39 graph-relationship questions the shipped `balanced` default lost hit@1 21/39 → 3/39 and hit@3 27/39 → 5/39 with the reranker on — 19 and 22 paired losses — because the cross-encoder scores chunk TEXT and an edge-derived answer's text need not mention the query's entity; with the pin at its default 3, measured with `--autocut on`, the shape that shipped before rule R2 turned autocut off, the same paired run shows 0 hit@1 / 0 hit@3 losses, 21/39 and 27/39, and the 11 non-relational core queries show 0 losses — one hard-negative gain, hit@1 10/11 → 11/11). `pinRelationalRows(reranked, relationalList, {max, fusedOrder?, onPin?})` is a pure PERMUTATION of the post-rerank pool: relational rows (page key `(source_id, slug)` in the arm's list; ONE row per page — its first, highest-ranked occurrence) claim `min(fused_rank, reranked_rank)` (fused rank = position among relational rows in `fusedOrder`, the pre-rerank `deduped` pool; arm order for rows absent from it), claims sort ascending with ties resolved to the FUSED order then the reranked position, the first `max` claimants form the top block in that order, every other row follows in reranked order (an unpinned row lands at its reranked position or up to `pinned.length` lower, never higher). Pinned rows are shallow copies stamped `relational_pinned: true`; no row is added or removed (re-injecting rows dropped upstream stays `ensureRelationalEvidenceSlot`'s job). Every no-op path (`max <= 0`, empty pool, empty arm, no relational page in the pool) returns the input array itself. `normalizeRelationalRerankPin` is the ONE range contract for the knob (non-negative integer `<= 10` or a string parsing to one → that integer; the literals `off` / `false` (any case) or boolean `false` → 0; anything else → `undefined` = fall through), shared by `mode.ts:loadOverridesFromConfig` and both per-call seams in `hybrid.ts`; `DEFAULT_RELATIONAL_RERANK_PIN` (3) and `RELATIONAL_RERANK_PIN_MAX` (10) are exported. `RelationalRerankPinDecision` (`{max, relational_in_pool, pinned:[{slug, source_id, from_rank, to_rank, fused_rank}], moved}`) is surfaced as `HybridSearchMeta.relational_rerank_pin` for `--explain`. Wired in `hybridSearch` immediately after `applyReranker` and before the alias hop, gated on the reranker having actually reordered (`reranked !== deduped` — `applyReranker` returns its input on every fail-open / skip / pass-through path, and the fused order already carries the arm) and on non-image modality; autocut's `scoreOf` ignores pinned rows and its preserve predicate keeps them, so text-row autocut is byte-identical to the pre-pin behavior. Known cost: a false-positive arm (relational shape parsed AND a real seed resolved, but wrong/stale edges) now puts up to `max` edge pages at ranks 1..max instead of one at `limit`; mitigations are the arm's `fallback_slugify` confidence gate, the tier-2 resolution-margin TODO, config `search.relational_rerank_pin off`, and per-call `SearchOpts.relationalRerankPin`. Pinned by `test/search/relational-rerank-pin.test.ts` (pure contract + tie policy) and `test/search/relational-rerank-pin-hybrid.serial.test.ts` (hermetic PGLite on the relational corpus through the REAL gateway rerank path behind `__setRerankTransportForTests` with an inverted-relevance stub: pin 0 reproduces the regression, pin 3 restores hit@1/hit@3 on all 8 who-invested questions, non-relational queries and reranker-off runs are byte-identical).diff --git a/docs/architecture/key-files/core-services-2-continued.md b/docs/architecture/key-files/core-services-2-continued.mdindex 9c2cbb0a9b..72f550325c 100644--- a/docs/architecture/key-files/core-services-2-continued.md+++ b/docs/architecture/key-files/core-services-2-continued.md@@ -17,4 +17,5 @@ The page-state concurrency foundation under `src/core/page-state/` and the share- `src/core/progressive-batch/` — shared ramp-up + cost-cap + verification primitive (trial 10 → ramp 100 → ramp 500 → full, with verification at each stage), with verifier+policy injection (callers describe HOW TO MEASURE SUCCESS, not WHEN TO WAIT FOR CTRL-C). Modules: `types.ts` (Stage, StageVerdict, AbortReason, discriminated `Verifier` union `OutputCountVerifier | IdempotentMutationVerifier | NoopVerifier`, Policy, StageReport), `orchestrator.ts` (`runProgressiveBatch(items, verifier, policy, runner)` — reads `getCurrentBudgetTracker()` ahead of `Policy.maxCostUsd` fail-closed; null both ways triggers `abort_cost_cap reason='no_budget_safety_net'`), `audit.ts` (ISO-week JSONL at `~/.gbrain/audit/progressive-batch-YYYY-Www.jsonl` via the shared `audit-writer` primitive), `stage-report.ts` (ASCII formatter for the default `Policy.onStageReport`). Env knobs: `GBRAIN_PROGRESSIVE_BATCH_DISABLED=1`, `GBRAIN_PROGRESSIVE_BATCH_AUTO=1` (skip Ctrl-C grace), `GBRAIN_PROGRESSIVE_BATCH_STAGES=10,100,500`. Sites that "jump straight to full" stay that way by default; ramp is opt-in per-site via `Policy.interactiveAbortMs > 0`. Pinned by `test/progressive-batch/orchestrator.test.ts` (35 cases, every verdict path).- `src/core/page-body/page-shape.ts` — Wave B PR 1 (spec 1.5): segmented page bodies are unreachable as strings. `guardSegmentedBody` (called by `rowToPage` for a row with `body_storage = 'segmented'`, so by every snapshot and `getPage` read) replaces `compiled_truth` / `timeline` with enumerable getters and setters that throw `page_body_segmented`, so property reads, spread, `JSON.stringify`, `structuredClone` and assignment all fail loud instead of seeing an empty body. `isSegmentedPage`, `assertInlineBody(page, site)` (explicit refusal where a writer would otherwise act before a getter fires, e.g. SQL-only writers), `pageBodyBytes(page)` (`body_bytes` for segmented pages) and `pageBodySegmentedError`. `bodyUnread(page)` says a segmented page's body was not read back as strings (over the single-string ceiling, see `materializedPage`); such a body was written by the streamed import, which holds fenced files, so `fenceBody(page)` reads it as empty for the fence merges and `withoutBody(page)` copies the page's other fields for a render whose body comes from the incoming write (a shrunk file rewrites such a page: `test/large-pages/segmented-shrink-below-ceiling.test.ts`). `Page` stays one shape (`body_storage?`, `body_bytes?`); the static half is `scripts/check-page-body-readers.ts` with `scripts/page-body-readers-baseline.tsv` (docs/TESTING.md#page-body-readers). Pinned by `test/large-pages/segmented-body-unreachable.test.ts`.-- `src/core/page-body/read-range.ts` + `segment-projection.ts` + `segment-ledger.ts` — Wave B PR 2 (spec 7.1, 7.3): the segment reader. `openSegmentedBody` reads a page's live manifest rows and its withdrawal ledger (`readBodyLedger`); `readBodyRange(engine, { pageId, space, start, end, audience, region?, body? })` streams pieces one segment text at a time, never the whole body. Remote reads and every projected-space read serve the read projection: `projectSegment` projects whole segments from their stored protected regions (takes, truncated tail and markers out, keys as the projection token, facts regions rendered world-only and credential-projected), after the withdrawal overlay (`overlaySegmentText`; a fence split by a forced cut is omitted for reads and refuses a trusted read) and the fence overlay (held and purged rows out, rows below the page tier in the low-tier block after the truth). A transform or stale metadata recomputes the regions from the segment's entry state; with none usable the read refuses `page_projection_stale`, never raw text. Trusted stored-space reads give the overlaid stored stream. `projectedLayout` (cached on the handle), `projectedTotals`, `projectedLineStart` and `projectedOutline` (outline from stored metadata, no segment text) locate projected bytes; the concatenation equals `projectPageText` of the joined body byte for byte except where a facts fence is longer than a segment (shows less). The chunker (`segment-chunks.ts`) chunks the same projection, so sealed segmented pages carry `MARKDOWN_CHUNKER_VERSION`; `sealSegmentedPage` indexes the overlaid, sanitized timeline lead. Pinned by `test/large-pages/projection-parity.test.ts`, `remote-window-privacy.test.ts` and `sealed-segmented-search.test.ts` (fixture `test/helpers/segmented-privacy-fixture.ts`).+- `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), `projectedUnits` (rows and fixed text in projected order, for `page-window/segmented.ts`), `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-window/segmented.ts` — Wave B PR 2 (spec 7.2, 7.4): get_page over a segmented page in projected bytes, the same coordinates as an inline page. `SegmentedDocument` places units (segments from `projectedUnits` plus fixed text) by stored sums and reads only the units a window, line lookup or `around_chunk_id` touches (`slab` adds `EDGE` bytes so code-point and line snapping match the inline arithmetic). `segmentedReadDocument` is the read projection; `segmentedMarkdownDocument` the markdown view (`markdownHead`, then the projection for a remote caller, the overlaid stored body and `TIMELINE_SEPARATOR` for a trusted one). `page_view_digests` (migration v250) caches per page revision, view and audience the read view's line count and the markdown view's size and sha256, checked against the current total. `tailDigest` hashes the last `TAIL_BYTES` raw bytes of the last region, withheld from a remote caller when those rows hold a protected or facts region. `segmentedOutline` pages headings from stored metadata, reading at most `OUTLINE_READ_BYTES` of segments per page. `cli/page-render.ts` uses it for the local `gbrain get` stream (`streamSegmentedGet`); the thin client pages and verifies the markdown view (`printPagedPage`), and `--json` above `PAGE_MAX_BYTES` is refused on both paths. Pinned by `test/large-pages/segmented-get-page-parity.test.ts`, `read-cost.test.ts`, `remote-get-page-privacy.test.ts`, `segmented-get-cli.test.ts` and `segmented-get-over-ceiling.test.ts`.diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.mdindex 4582fccc17..aa6c1e3f3d 100644--- a/docs/architecture/key-files/core-services-2.md+++ b/docs/architecture/key-files/core-services-2.md@@ -43,7 +43,7 @@ Fact and page purge modules (`src/core/facts/purge*.ts`, `deletion-inventory.ts`- `src/core/ops/pages.ts` — page operations share source validation and the persistence coordinator. Replacements require `expected_revision` or explicit `force`; omitted preconditions permit creation only. The put_page description keeps `Keep a request_id UUID; retry with identical arguments` within its 1,460-character schema budget (pinned by `test/mcp-schema-budget.test.ts` minimum guidance; the description and the content param both keep the get_page include_content:true read that `test/mcp-tool-defs.test.ts` pins). `get_page` and `fetch` use `page-state/snapshot.ts` for exact/alias resolution, content, tags, revision and withdrawal overlays in one SQL snapshot; fuzzy fallback uses a short repeatable-read transaction with the same visibility and source ceilings. `get_page` `content_only` (`ops/get-page-projection.ts`) returns slug, source_id, type, title, revision, tags and content (keys pinned by `test/get-page-content-roundtrip-2225.test.ts`). A put_page `revision_conflict` (`ops/put-page-revision-source.ts`) whose expected_revision is the current revision of the same slug in another source the caller may read (grant via `federatedSearchScope`, private pages excluded for untrusted readers) names that source and gets a re-read fix; otherwise the refusal is unchanged. `get_page` adds `file_held` when sync holds the page's newer file (`persistence/held-reads.ts`; path for trusted local callers only). Missing migration dependencies and connection errors propagate. Capture freezes target/type/timestamp/provenance before admission and resolves same-ID replay first. `persistence/links-preparation.ts` prepares trusted automatic graph reconciliation outside locks, then installs it with canonical projections and the receipt; delayed oneshot reconciliation validates its originating revision. `persistence/page-advisories.ts` prepares bounded, content-free lint findings. Tests cover source/alias ownership, concurrent graph replacements, stale delayed reconciliation, private fences and durable retries. `list_pages` passes `listColumnsOnly` so `engine-sql/pages.ts:listPages` projects identity, type, title and dates without reading page bodies or frontmatter (`list-pages-columns-5154.test.ts`). `delete_page` accepts a strict boolean `purge` only from trusted local callers. Immediate purge uses the same durable journal, observed revision (or explicit `force`), stored/current authority and exact request-ID replay as other page mutations. Owner preparation resolves the recorded file from a coherent snapshot, including tombstones; file removal precedes hard deletion and receipt commitment in the guarded publication transaction. Failed publication preserves the prior active row or existing tombstone and never overwrites unexpected file bytes. The receipt reports the actual filesystem/database persistence outcome and warns that repository history, synced copies, exports and derived artifacts may retain content. The `gbrain delete <slug> --purge` flag derives from the operation contract. `list_pages` probes `limit + 1` rows: a local CLI caller gets a stderr truncation notice; every dispatched caller gets `_meta.pagination` (`truncated`, `limit`, `clamped_from?`, `next?`) and a remote caller whose page was truncated also gets the model-visible `listing_truncated` notice whose `fix.mcp` is the next-page call (`ops/list-pages-pagination.ts`; `next` is the `updated_asc` keyset or an offset). Test: `test/list-pages-truncation.test.ts`. An `updated_after` the database cannot cast (SQLSTATE 22007/22008, the shared `isDatetimeInputError` in `core/utils.ts` that the hybrid lexical arms also use) is `invalid_params` with a read-only list_pages fix, never echoing the value; other SQLSTATEs pass through (`test/list-pages-timestamp-input.test.ts`). put_page (dry runs included) refuses a new `.md`/`.mdx`-suffixed slug (`persistence/suffixed-slug.ts`). #6212: `delete_page` and `restore_page` (dry runs included) go through `persistence/page-mutations.ts:validateMutationSlug`, which admits a legacy stored slug (`ops/context.ts:isLegacyStoredPageSlug`: refused by today's grammar, still accepted by `validateSlug`) only when an existing row in the target source holds it; every other operation keeps `validatePageSlug`, and remote purge stays denied by `assertPurgeParams`. Large pages: `get_page` resolves its body mode first (`parseBodyRequest`, `src/core/ops/get-page-body.ts`) and returns `readPartialBody` for none/outline/window/auto-above-256 KB, `assertFullReadFits` guarding whole remote reads; `fetch` of a page over the inline size returns `fetchWindowResult` (window around the id's chunk anchor, `metadata.next_id`); remote `put_page` runs `assertLargePageAdmission` before queueing.-- `src/core/ops/get-page-body.ts` — get_page's body modes (`auto|full|none|outline|window`, selectors `lines`/`bytes`/`around_chunk_id`/`cursor`, `view: read|markdown`). `parseBodyRequest` fixes precedence (explicit body; include_content/content_only → full; a selector → window; the thin client and the local CLI → full; else auto) and rejects conflicting selectors. `readPartialBody` never fills compiled_truth/timeline/content: it slices the read projection (`readPageDocument`) or, for `view: markdown`, the round-trip markdown with its sha256; a window is re-measured as the final encoded frame and shrunk until it fits `resultByteCap`. `around_chunk_id` uses the stored span (`anchor: stored_span`), a unique text match (`located`), or returns the chunk alone (`chunk_only`). Cursors are revision-bound; a stale one is `revision_changed` with a same-offset fix. `readFetchWindow` / `fetchWindowResult` serve fetch's windowed shape; `LARGE_PAGES_CAPABILITY` is advertised by `get_brain_identity`.+- `src/core/ops/get-page-body.ts` — get_page's body modes (`auto|full|none|outline|window`, selectors `lines`/`bytes`/`around_chunk_id`/`cursor`, `view: read|markdown`). `parseBodyRequest` fixes precedence (explicit body; include_content/content_only → full; a selector → window; the thin client and the local CLI → full; else auto) and rejects conflicting selectors. `readPartialBody` never fills compiled_truth/timeline/content: it slices the read projection (`readPageDocument`) or, for `view: markdown`, the round-trip markdown with its sha256; a window is re-measured as the final encoded frame and shrunk until it fits `resultByteCap`. `around_chunk_id` uses the stored span (`anchor: stored_span`), a unique text match (`located`), or returns the chunk alone (`chunk_only`). Cursors are revision-bound; a stale one is `revision_changed` with a same-offset fix. `readFetchWindow` / `fetchWindowResult` serve fetch's windowed shape; `LARGE_PAGES_CAPABILITY` is advertised by `get_brain_identity`. A segmented page (Wave B PR 2, spec 7.2) is never read whole: `full` is `page_body_segmented` locally (fix: `gbrain get`, which streams it) and `page_too_large_for_inline` over a transport (`segmentedFullReadError`), `auto` is the outline plus the first window, and `segmentedWindows` cuts every window, outline page and `around_chunk_id` from `page-window/segmented.ts`. A segmented `around_chunk_id` resolves only from the chunk's live occurrence and segment-relative span (a retired occurrence is `revision_changed`; no text match), and `body: 'none'` reports stored sums plus the tail digest without chunk counts.- `src/core/persistence/large-page-guard.ts` — put_page against a page over 256 KB: `assertLargePageAdmission` (remote, before queueing) refuses `force` without `expected_revision` (`revision_required`) and content under half the stored body (`page_shrink_refused`) unless `allow_shrink`; `assertLargePageReplacement` re-checks the parsed body against the locked snapshot in preparation (`page-prepare.ts`).- `src/core/ops/page-edit.ts` — the `edit_page` operation (write scope, starter surface, client slug-fence allowlist): validates edits, then submits through `submitPageMutation` like put_page; matching and the diff live in `persistence/page-edit.ts`.diff --git a/scripts/check-orphan-modules.mjs b/scripts/check-orphan-modules.mjsindex df505a90bc..4fd946fb5b 100644--- a/scripts/check-orphan-modules.mjs+++ b/scripts/check-orphan-modules.mjs@@ -72,7 +72,7 @@ const PERMITTED_TEST_ONLY = [{ path: 'src/core/ingestion/sources/file-watcher.ts', reason: 'held: ingestion cluster awaits a wire-up vs delete product decision' },{ path: 'src/core/ingestion/sources/gstack-learnings.ts', reason: 'held: ingestion cluster awaits a wire-up vs delete product decision' },{ path: 'src/core/ingestion/sources/inbox-folder.ts', reason: 'held: ingestion cluster awaits a wire-up vs delete product decision (docs/guides/data-ingestion.md promises the inbox folder)' },- { path: 'src/core/ingestion/sources/markdown-greenfield.ts', reason: 'held: ingestion cluster awaits a wire-up vs delete product decision (docs/migrations/v0.41.2-markdown-greenfield.md)' }, { path: 'src/core/page-body/read-range.ts', reason: 'held: Wave B PR 2 segment reader (lane F); the get_page, page-window and evidence lanes of the same PR wire it into their reads' },+ { path: 'src/core/ingestion/sources/markdown-greenfield.ts', reason: 'held: ingestion cluster awaits a wire-up vs delete product decision (docs/migrations/v0.41.2-markdown-greenfield.md)' },];const RULES = {diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 3d9c56dc28..9faaa32f0a 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -3,7 +3,7 @@# Raising a ceiling is a conscious, reviewer-visible act. Lower ceilings in# the same commit as any peel (the guard fails on >50 lines of stale slack).# Columns: path max_lines policy note-src/cli/main.ts 3009 ratchet +1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); moved from src/cli.ts at 3214 (cold start: src/cli.ts is now the 66-line entry with the --version/help fast path; the top-level help text moved to cli/top-help.ts and the exit seam became runCli/exitOnFatalCliError); +2 #6340: the sync status / sync unblock preflight skip (logic in commands/sync/operator.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +2 retrieval feedback: answer id line on stderr and additive answer_id on --json search/query rows (logic in feedback/record.ts); +1 feedback help line and its D3 table-dispatch entry (logic in commands/feedback.ts); 6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x engine graduation composition: both deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x foundations-2 composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); +2 entity recall: the human `gbrain entity` card prints referenced_by groups and a non-complete mention coverage; cat40 entity wave merge with v0.60.61.0 (3179 measured); +3 #4772 (W14 PR3): get_health text output says the entity ratios are n/a because the schema pack did not load (entity_types_status); +1 C4: gbrain questions CLI-only dispatch row (its help line is in cli/top-help.ts); +1 #6696 (A4): a local write captures the capacity notices (one call; logic in cli/op-notices.ts captureCapacityNotices); +1 large pages A6: the stdin cap reads PAGE_MAX_BYTES from core/page-size-policy.ts+src/cli/main.ts 3012 ratchet +1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); moved from src/cli.ts at 3214 (cold start: src/cli.ts is now the 66-line entry with the --version/help fast path; the top-level help text moved to cli/top-help.ts and the exit seam became runCli/exitOnFatalCliError); +2 #6340: the sync status / sync unblock preflight skip (logic in commands/sync/operator.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +2 retrieval feedback: answer id line on stderr and additive answer_id on --json search/query rows (logic in feedback/record.ts); +1 feedback help line and its D3 table-dispatch entry (logic in commands/feedback.ts); 6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x engine graduation composition: both deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x foundations-2 composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); +2 entity recall: the human `gbrain entity` card prints referenced_by groups and a non-complete mention coverage; cat40 entity wave merge with v0.60.61.0 (3179 measured); +3 #4772 (W14 PR3): get_health text output says the entity ratios are n/a because the schema pack did not load (entity_types_status); +1 C4: gbrain questions CLI-only dispatch row (its help line is in cli/top-help.ts); +1 #6696 (A4): a local write captures the capacity notices (one call; logic in cli/op-notices.ts captureCapacityNotices); +1 large pages A6: the stdin cap reads PAGE_MAX_BYTES from core/page-size-policy.ts; +3 Wave B PR 2: local gbrain get of a segmented page streams on the page_body_segmented refusal (logic in cli/page-render.ts streamSegmentedGet)src/commands/autopilot.ts 1642 ratchet refactor wave 1 split target (W4 autopilot, cut line); ceiling rationale: docs/architecture/key-files/commands-1.md entry for src/commands/autopilot.ts; +2 fix wave 5: nosemgrep justifications on the per-brain job launchctl/systemctl calls (#5195); +2 #5813: boot reconcile names attempted and running versions in log + audit; +2 #5855: Bun floor gate before the swap and the swap-refusal hold (logic in core/bun-floor.ts); +3 agent operator wave E9: --dry-run and the persistent_install consent gate before anything is written (logic in autopilot/install-consent.ts)src/commands/doctor.ts 686 ratchet +19 #6696 doctor tiers: Check.elapsed_ms and DoctorReport tier/complete/unknown_sections/elapsed_ms/budget_ms fields, buildChecks/runDoctor deadline params (logic in doctor/budget.ts); +1 agent operator gate fixes: --probe consent gate (logic in doctor/probe-consent.ts); refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.tssrc/commands/embed.ts 2304 ratchet +2 agent operator wave D2: --json failure envelope via writeCliError; lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring; archived eligibility: active-only dispatch with honest stranded-work reporting; explicit archived admission: live-source snapshots and honest refused-installation failures; +2 fw3: embed --stale --images dispatch (sweep lives in core/embed-stale-images.ts); +5 #5289: dry run reports restamp-only chunks apart from chunks to embed (count lives in core/embedding-invalidation.ts); +6 #4616: keep a partially refused batch in embedPageTexts and name the recovery command in failure samples (guard lives in core/ai/embedding-guard.ts); +5 #5226: embed summary counts distinct pages; +3 #5804: null projection snapshot counted as a failure with one batch summary in embed --stale; +18 wave 8 lane D1: #5527 mixed-space warning subtracts current-model chunks (+4), #5885 takes option/result fields and the stale-drain takes call (pass lives in core/embed-takes.ts); +9 Foundations 1 F4d: time-budget stop result fields, stdout verdict and stop recording in embed --stale (logic in core/embed-budget-stop.ts); +8 green-master lane A: chunkless install re-reads through retryProjectionConflict instead of recording an unavailable page (retry lives in core/page-state/projections.ts, failure line in core/agent-output.ts); +8 fix wave 13 P1.18: runEmbed consent parameter, cost-cap stop wiring and result fields, --slugs parsing to the next flag (cap, verdict and resume logic live in core/embed-cost-cap.ts); +28 large pages A9/T3/T16: --held listing and per-page cap metering on every embed path (logic in core/page-embedding-budget.ts meterPageBatch/spendGrant/heldEmbedArgv), approvedPageCapUsd from --max-usd on --slugs; +1 #6722: an explicit slug embed skips an embed_skip page (it keeps keyword chunks, never vectors); merge v0.60.240.0: large pages and master growth compose at 2265; +39 large pages Wave B lane 1e: segmented pages route to the keyset sweep on the slug, --all and --stale paths, with a dry-run count and provenance stamp (logic in core/page-body/segmented-embedding.ts)@@ -40,7 +40,7 @@ src/core/config.ts 1981 ratchet +2 W5: search.page_rank_cut / page_rank_cut_factsrc/core/persistence/sync-run.ts 1690 ratchet new row: crossed the 1500 unlisted cap in #6643 (knock-on re-freeze, checkpoint revival, root cause and the truthful --retry-failed wait all drive the private cursor/gate machinery: holdUnderGate, freezeEntry, saveCursor); classification lives in sync-knock-on.ts, the checkpoint clause in checkpoint-validation.ts; peel the settle path (settleFailedRequest and its recoveries) into a sibling module next; +3 #6722: committed pages' size_state tallied into the cursor and the sync receipt size_states (logic in page-embedding-budget.ts addSizeState); merge v0.60.240.0: large pages and master growth compose at 1687; +2 #6694: the slug-mode checkpoint revival import and its doc line (predicate lives in persistence/sync-slug-mode.ts)src/core/bootstrap/harness.ts 2615 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts); +5 D8 Codex slice: the Codex SessionEnd capture hook obeys the recorded consent (wireCodexCapture: hooks on, capture accepted, never registrar mode) and is disclosed in the consent blocksrc/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option-src/core/ops/pages.ts 707 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +21 large pages (Wave A): get_page body-mode dispatch, fetch window branch, put_page large-page admission and allow_shrink param, description text (logic in ops/get-page-body.ts and persistence/large-page-guard.ts); +1 D8 funnel: committed put_page records a save when the opt-in funnel is on; +1 #6609: restore_page detach param (logic in persistence/detached-pages.ts); +1 Wave B gem A: post-batch auto-link reads a segmented page materialized (helpers in persistence/segmented-apply.ts); merge v0.60.249.0: composes at 707+src/core/ops/pages.ts 711 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +21 large pages (Wave A): get_page body-mode dispatch, fetch window branch, put_page large-page admission and allow_shrink param, description text (logic in ops/get-page-body.ts and persistence/large-page-guard.ts); +1 D8 funnel: committed put_page records a save when the opt-in funnel is on; +1 #6609: restore_page detach param (logic in persistence/detached-pages.ts); +1 Wave B gem A: post-batch auto-link reads a segmented page materialized (helpers in persistence/segmented-apply.ts); merge v0.60.249.0: composes at 707; +4 Wave B PR 2: get_page refuses a segmented page whole and fetch windows one (logic in ops/get-page-body.ts and page-window/segmented.ts)src/core/search/mode.ts 1669 ratchet +53 W3 confidence-gated reranking: reranker_gate / reranker_gate_min_gap bundle fields, overrides, config parse and KNOB_CONFIG_KEY rows, knobsHash v=31 rrg=/rrgg=/ecf= parts (parse contracts in crag.ts); +10 System One v1: decide.* snapshot subset in loadSearchModeConfig, append-only dec= knobsHash part; +5 #3617 follow-up: v27 same-knobs behavioral-change note (relaxed-row fusion demotion rides the bump); new row: crossed the 1500 unlisted cap in the 2026-08 eval fix wave — KNOBS_HASH v=27 adaptive-return fold (ar/arem/arom/armk/ari parts + KnobsHashContext.adaptiveReturn field + contamination rationale comments) | merged v0.48.1.0 (+#4787) true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: four knobs (expansion_variant_budget, relational_rerank_pin, keyword_arm_confidence_floor, metadata_boost_gate) + v29 hash parts + doc receipts (+218); #4781 loadSearchModeConfig reads the config table once via loadConfigSnapshot (+6); +4 #4359: update loadSearchModeConfig docstring — the cached path now reads config once (threaded snapshot), not twice; retired provider integration removed; +12 fw3-search: search.source_boosts + search.alias_token_hop read in the mode snapshot; +10 #5691: KnobsHashContext.queryPrefix and its append-only qp= part; P7 relational_planner / relational_orient_onehop knobs (interface docs, bundles, overrides, config parse, hash parts); +18 P7 relational_chain_slots knob (interface doc, bundles, override, config parse, rcs= hash part); +22 GBRA-60 S1 diverse_pool_depth knob (interface doc, bundles, overrides, pick, config parse, append-only dpd= hash part)src/commands/eval-longmemeval.ts 1544 ratchet new row: crossed the 1500 unlisted cap in fw3-search (#5092 benchmark-brain recycling: configureBrain split + recycler wiring + test seams; the recycler itself lives in src/eval/longmemeval/harness.ts); +1 P6: tokenmax synopsis-tier wiring (logic in eval/longmemeval/synopsis-tier.ts); +13 GBRA-81 lane A: --via-operation query|search (flags, per-call expansion pin, the run's expectExpansion, the op branch in runOneQuestion, row field, via_operation_summary and its FAIL line; logic in eval/longmemeval/via-operation.ts); +12 --call-plan FILE / --call-plan-gate CMD: two LME_FLAGS entries (CLI help lines), two ParsedArgs fields, the parseArgs pairing check and the header invariant (planner lives in eval/longmemeval/call-plan.ts; runEvalLongMemEval is one line shorter)src/commands/doctor/checks/extraction-sync.ts 1523 ratchet +1 undeclared_db_only_pages computes the source Git scope once per source (logic in core/markdown.ts sourceGitScope); new row: crossed the 1500 unlisted cap at the fix wave 9 merge: +7 lane W #5028 (extract_atoms freshness judged by the phase itself) and +3 lane F #5863 (extract_health dates a high halt rate by its last halt), each under the cap alone; +7 #5019: content_hash_duplicates fix pins the pairs' source (GBRAIN_SOURCE) and names a delete that runs; +1 fix wave 10 lane L1 #5556: links_extraction_lag denominator excludes quarantined pages (quarantineFilterFragment import); +11 fix wave 15 P2.8 (#5495): extract_health reads the 7-day halt reasons per kind (halt_reasons, top_halt_reason in details and the top reason in the warn line); the read, the unknown bucket and the ranking live in core/extract/rollup-writer.tsdiff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsvindex 2e3fdf947c..6652250634 100644--- a/scripts/page-body-readers-baseline.tsv+++ b/scripts/page-body-readers-baseline.tsv@@ -351,6 +351,7 @@ src/core/page-window/bounded-lead.ts overlaidBoundedRows field LEAD rows carry bsrc/core/page-window/document.ts projectPageText field STREAMsrc/core/page-window/document.ts readPageDocument call:pageDocument STREAMsrc/core/page-window/document.ts readPageDocument field STREAM+src/core/page-window/segmented.ts markdownHead call:serializePageToMarkdown NONE serializes the frontmatter head only: compiled_truth and timeline are passed as empty stringssrc/core/persistence/atom-maintenance.ts prepareManagedAtomMutation field METAsrc/core/persistence/atom-maintenance.ts readAtomOrigin field METAsrc/core/persistence/atom-retry.ts retryManagedAtomBatch field STREAMdiff --git a/src/cli/main.ts b/src/cli/main.tsindex 758b00a4a8..806e215a9a 100755--- a/src/cli/main.ts+++ b/src/cli/main.ts@@ -50,7 +50,7 @@ import type { Notice } from '../core/agent-output.ts';import { opError, opOwnsSource } from '../core/ops/contract.ts';import { PAGE_MAX_BYTES } from '../core/page-size-policy.ts';import { opParamValue } from './op-param-values.ts';-import { formatGetPage, readWholePageMarkdown, remoteErrorCode, wantsWholePage } from './page-render.ts';+import { SEGMENTED_STREAMED, formatGetPage, printPagedPage, remoteErrorCode, streamSegmentedGet, wantsWholePage } from './page-render.ts';import { parseGlobalFlags, setCliOptions, getCliOptions } from '../core/cli-options.ts';import { runCliPreflight } from '../core/cli-preflight.ts';import { isBooleanLiteral, isKnownOpFlag } from '../core/op-flag-tokens.ts';@@ -676,7 +676,10 @@ async function runSharedOperation(command: string, subArgs: string[], cliOpts: Cif (op.scope === 'read') {try {rawResult = await withTimeout(- op.handler(ctx, params),+ op.handler(ctx, params).catch(async (e: unknown) => { // large pages: a segmented page streams to stdout+ if (op.name === 'get_page' && await streamSegmentedGet(engine, params, e, writeStdoutFinal)) return SEGMENTED_STREAMED;+ throw e;+ }),wallclockMs,`gbrain ${command}`,);@@ -691,6 +694,7 @@ async function runSharedOperation(command: string, subArgs: string[], cliOpts: CrawResult = await op.handler(ctx, params);if (op.mutating) await captureCapacityNotices(engine); // #6696 (A4)}+ if (rawResult === SEGMENTED_STREAMED) return;// ENG-2 (renderer parity by data shape): JSON-round-trip the local-engine// path's return value so renderers see the same shape they'd see on the// routed path. Date → ISO string; bigint → string (postgres.js shape);@@ -797,8 +801,7 @@ async function runThinClientRouted(...(op.mutating ? { writeWaitMs: currentCliWriteWait().waitMs } : {}),}).catch(async (e: unknown) => { // large pages: a page too big for one response is paged to its end, verified, then printedif (op.name !== 'get_page' || remoteErrorCode(e) !== 'page_too_large_for_inline' || !wantsWholePage(params)) throw e;- const paged = await readWholePageMarkdown(async p => unpackToolResult(await callRemoteTool(cfg, 'get_page', p, { timeoutMs, signal: sigintController.signal })), params);- await writeStdoutFinal(params.json === true ? JSON.stringify({ slug: params.slug, revision: paged.revision, content: paged.markdown, windows: paged.windows }) + '\n' : paged.markdown);+ await printPagedPage(async p => unpackToolResult(await callRemoteTool(cfg, 'get_page', p, { timeoutMs, signal: sigintController.signal })), params, writeStdoutFinal);return null;});if (raw === null) return;diff --git a/src/cli/page-render.ts b/src/cli/page-render.tsindex dcb7abe975..34aa4b74db 100644--- a/src/cli/page-render.ts+++ b/src/cli/page-render.ts@@ -10,10 +10,25 @@* The thin client asks for the whole page. A host that cannot send it in one* response refuses with page_too_large_for_inline; the client then pages the* round-trip markdown (view: 'markdown') to its end, checks the total size and- * sha256 the host reported, and prints it, or fails without printing.+ * sha256 the host reported, and prints it window by window, or fails without+ * printing.+ *+ * A segmented page (Wave B) is never returned whole by get_page. Locally the+ * refusal is page_body_segmented and `gbrain get` streams the page instead:+ * the frontmatter head, the truth segments, TIMELINE_SEPARATOR and the+ * timeline segments, one segment at a time. `--json` puts the page in one+ * string, so above PAGE_MAX_BYTES it refuses, locally and over the thin+ * client, with a fix that drops `--json`.*/import { createHash } from 'node:crypto';+import type { BrainEngine } from '../core/engine.ts';import { serializeMarkdown } from '../core/markdown.ts';+import { opError } from '../core/ops/contract.ts';+import { readFix } from '../core/ops/op-fix.ts';+import { PAGE_MAX_BYTES } from '../core/page-size-policy.ts';+import { isSegmentedPage } from '../core/page-body/page-shape.ts';+import { openSegmentedBody } from '../core/page-body/read-range.ts';+import { markdownHead, segmentedMarkdownDocument } from '../core/page-window/segmented.ts';/** Window size the thin client asks for while paging a whole page. */export const REMOTE_PAGE_WINDOW_BYTES = 512 * 1024;@@ -73,15 +88,18 @@ export function wantsWholePage(params: Record<string, unknown>): boolean {/*** Page a whole page's round-trip markdown through windows. Restarts from the* top when the page changes mid-read; throws rather than return a short or- * unverified body.+ * unverified body. The windows are kept as they arrived (`parts`); `markdown`+ * joins them on demand.*/export async function readWholePageMarkdown(call: (params: Record<string, unknown>) => Promise<GetPageResult>,params: Record<string, unknown>,-): Promise<{ markdown: string; revision: string; windows: number }> {+): Promise<{ parts: Buffer[]; markdown: string; revision: string; windows: number }> {const base = { slug: params.slug, ...(params.source_id !== undefined ? { source_id: params.source_id } : {}), body: 'window', view: 'markdown' };for (let attempt = 0; attempt <= MAX_RESTARTS; attempt++) {const parts: Buffer[] = [];+ const hash = createHash('sha256');+ let bytes = 0;let r = await call({ ...base, max_bytes: REMOTE_PAGE_WINDOW_BYTES });const { revision, size } = r;let windows = 1;@@ -90,7 +108,10 @@ export async function readWholePageMarkdown(if (!r.window || typeof r.window.byte_start !== 'number' || !size || typeof size.sha256 !== 'string') {throw new Error(`get_page did not return a markdown window for ${String(params.slug)}; the page was not printed.`);}- parts.push(Buffer.from(r.window.text, 'utf8'));+ const part = Buffer.from(r.window.text, 'utf8');+ parts.push(part);+ hash.update(part);+ bytes += part.length;if (!r.next_cursor) break;try {r = await call({ ...base, cursor: r.next_cursor });@@ -103,11 +124,57 @@ export async function readWholePageMarkdown(windows++;}if (changed) continue;- const whole = Buffer.concat(parts);- if (whole.length !== size.total_bytes || createHash('sha256').update(whole).digest('hex') !== size.sha256) {+ if (bytes !== size.total_bytes || hash.digest('hex') !== size.sha256) {throw new Error(`The paged copy of ${String(params.slug)} does not match the size and sha256 the host reported; the page was not printed.`);}- return { markdown: whole.toString('utf8'), revision, windows };+ return { parts, get markdown() { return Buffer.concat(parts).toString('utf8'); }, revision, windows };}throw new Error(`${String(params.slug)} kept changing while it was being read (${MAX_RESTARTS + 1} attempts); the page was not printed. Try again.`);}++/** `--json` holds the whole page in one string: refused above PAGE_MAX_BYTES, with a fix that streams it instead. */+function jsonTooLargeError(slug: string, sourceId: string | undefined, bytes: number) {+ return opError('page_too_large_for_inline', `Page ${slug} is ${bytes} bytes, over the ${PAGE_MAX_BYTES}-byte limit of one --json document.`,+ 'Run gbrain get without --json: it prints the page whole, window by window or segment by segment.',+ { fix: readFix('Prints the page whole without holding it as one string.', { argv: ['gbrain', 'get', ...(sourceId ? ['--source', sourceId] : []), '--', slug] }) });+}++/** The thin client's whole-page read after a page_too_large_for_inline refusal: page, verify, then print each window (or one --json document). */+export async function printPagedPage(call: (params: Record<string, unknown>) => Promise<GetPageResult>, params: Record<string, unknown>,+ write: (text: string) => Promise<void>): Promise<void> {+ const json = params.json === true;+ const paged = await readWholePageMarkdown(async p => {+ const r = await call(p);+ if (json && r.size?.total_bytes > PAGE_MAX_BYTES) throw jsonTooLargeError(String(params.slug), params.source_id as string | undefined, r.size.total_bytes);+ return r;+ }, params);+ if (json) await write(JSON.stringify({ slug: params.slug, revision: paged.revision, content: paged.markdown, windows: paged.windows }) + '\n');+ else for (const part of paged.parts) await write(part.toString('utf8'));+}++/** What the local get_page call returns when `streamSegmentedGet` printed the page itself. */+export const SEGMENTED_STREAMED = Symbol('segmented page streamed');++/**+ * Local `gbrain get` of a segmented page, after get_page refused it whole (page_body_segmented, whose fix names the+ * resolved slug and source): stream the trusted markdown view to `write`, one segment at a time, as the inline+ * page would print. False when `error` is not that refusal of a whole-page read.+ */+export async function streamSegmentedGet(engine: BrainEngine, params: Record<string, unknown>, error: unknown, write: (text: string) => Promise<void>): Promise<boolean> {+ const ref = (error as { fix?: { mcp?: { arguments?: Record<string, unknown> } } } | null)?.fix?.mcp?.arguments;+ if (remoteErrorCode(error) !== 'page_body_segmented' || !wantsWholePage(params) || typeof ref?.slug !== 'string' || typeof ref.source_id !== 'string') return false;+ const snapshot = await engine.readPageSnapshot(ref.slug, { sourceId: ref.source_id, includeDeleted: params.include_deleted === true });+ if (!snapshot || !isSegmentedPage(snapshot.page)) return false;+ const { page, tags } = snapshot;+ const json = params.json === true;+ if (json && Number(page.body_bytes) > PAGE_MAX_BYTES) throw jsonTooLargeError(page.slug, page.source_id, Number(page.body_bytes));+ const body = await openSegmentedBody(engine, { pageId: page.id, ledger: { withdrawals: snapshot.withdrawals, ...(snapshot.globalPurges ? { globalPurges: snapshot.globalPurges } : {}) } });+ const doc = await segmentedMarkdownDocument(engine, body, markdownHead(page, tags), 'trusted');+ const parts: string[] = [];+ for await (const bytes of doc.stream()) {+ if (json) parts.push(bytes.toString('utf8'));+ else await write(bytes.toString('utf8'));+ }+ if (json) await write(JSON.stringify({ slug: page.slug, source_id: page.source_id, revision: snapshot.revision, content: parts.join('') }) + '\n');+ return true;+}diff --git a/src/core/deletion-inventory.ts b/src/core/deletion-inventory.tsindex a8c44a963c..bf2deeb003 100644--- a/src/core/deletion-inventory.ts+++ b/src/core/deletion-inventory.ts@@ -114,6 +114,7 @@ const ROWS: readonly Row[] = [['page_projection_jobs', 'out_of_scope', 'no_memory_text', 'slug reason'],['page_purges', 'out_of_scope', 'text_free_ledger', 'source_id content_hash slug'],['page_segment_texts', 'swept', 'segment_texts', 'source_id sha256 body', 'body'],+ ['page_view_digests', 'out_of_scope', 'no_memory_text', 'revision view audience sha256'],['page_versions', 'swept', 'page_versions', 'compiled_truth frontmatter timeline title type tags source_path write_principal_kind write_principal_id archived_principal_kind archived_principal_id trust_tier write_origin body_storage content_hash'],['page_write_guards', 'out_of_scope', 'no_memory_text', 'slug'],['pages', 'swept', 'page_body', 'source_id slug type page_kind title compiled_truth timeline frontmatter content_hash effective_date_source import_filename database_only_reason contextual_retrieval_mode corpus_generation search_vector source_path ingested_via source_uri source_kind embedding_signature revision_principal_kind revision_principal_id trust_tier write_origin body_storage body_flags truth_lead timeline_lead'],diff --git a/src/core/ops/get-page-body.ts b/src/core/ops/get-page-body.tsindex d80b6f38f4..c52548b370 100644--- a/src/core/ops/get-page-body.ts+++ b/src/core/ops/get-page-body.ts@@ -33,15 +33,19 @@ import type { OperationContext, ParamDef } from './contract.ts';import { opError, OperationError } from './contract.ts';import { invalidParam, readFix } from './op-fix.ts';import { serializePageToMarkdown } from '../markdown.ts';-import { isSegmentedPage } from '../page-body/page-shape.ts';+import { isSegmentedPage, pageBodyBytes } from '../page-body/page-shape.ts';import { deepResearchPageUrl, encodeDeepResearchId } from '../deep-research-id.ts';import { encodedFrameBytes, EGRESS_CAP_CONFIG_KEYS, egressTransport, FRAME_RESERVE_BYTES, resultByteCap } from '../egress-budget.ts';import { DEFAULT_INLINE_BODY_BYTES, chunkDocumentSpan, readPageDocument, spanHoldsChunk, type PageDocument } from '../page-window/document.ts';import {DEFAULT_CONTEXT_LINES, DEFAULT_OUTLINE_LIMIT, DEFAULT_WINDOW_BYTES, MAX_CONTEXT_LINES, MAX_OUTLINE_LIMIT, MAX_WINDOW_BYTES,decodeCursor, encodeCursor, pageOutline, sha256Hex, totalLines, windowAround, windowForBytes, windowForLines, windowFrom,- type WindowSlice, type WindowView,+ type PageOutline, type WindowSlice, type WindowView,} from '../page-window/window.ts';+import {+ markdownDigest, markdownHead, readViewLines, segmentedMarkdownDocument, segmentedOutline, segmentedReadDocument, tailDigest, type SegmentedDocument,+} from '../page-window/segmented.ts';+import { openSegmentedBody } from '../page-body/read-range.ts';import { renderTrustedText, type TrustFields } from '../eligibility/labels.ts';import type { QuarantinedView } from './get-page-projection.ts';import { chunkGenerationProbe } from '../search/safe-chunks.ts';@@ -208,6 +212,29 @@ export async function assertFullReadFits(ctx: OperationContext, page: Pick<Page,fix: sizeFix(page.slug, page.source_id, "Returns the page's size, revision and outline; each entry names the lines to read with body: 'window'.") });}+/**+ * A segmented page is never built whole (spec 7.2). Over a transport the refusal comes from body_bytes before any+ * body is read: page_too_large_for_inline, which the thin client answers by paging view: 'markdown'. A trusted local+ * read refuses with page_body_segmented, which `gbrain get` answers by streaming the page.+ */+export function segmentedFullReadError(ctx: OperationContext, page: Page, req: BodyRequest): OperationError {+ const total = pageBodyBytes(page);+ const windows = "Read it in windows: get_page body: 'outline' lists the sections, then body: 'window' with lines, bytes, around_chunk_id or next_cursor.";+ if (ctx.remote === false) {+ return opError('page_body_segmented', `get_page: page ${page.slug} (source ${page.source_id}) stores its ${total}-byte body in segments; it is not returned as one string.`,+ `${windows} gbrain get prints it whole, streamed.`,+ { fix: readFix('Prints the page whole, streamed segment by segment.', { argv: ['gbrain', 'get', '--source', page.source_id, '--', page.slug],+ mcp: { tool: 'get_page', arguments: { slug: page.slug, source_id: page.source_id, body: 'outline' } } }) });+ }+ const transport = egressTransport(ctx)!;+ return opError('page_too_large_for_inline', `Page ${page.slug} is stored in segments (${total} bytes) and is never returned whole on this connection.`,+ req.legacyThin+ ? 'This gbrain CLI is older than the host and reads pages whole. Upgrade it (gbrain upgrade) to page through large pages, or read windows over MCP with get_page body: \'window\'.'+ : `${windows} Edit with edit_page (revision from body: 'none').`,+ { legacy_error: 'invalid_params', detail: JSON.stringify({ total_bytes: total, body_storage: 'segmented', transport }),+ fix: sizeFix(page.slug, page.source_id, "Returns the page's size, revision and outline; each entry names the lines to read with body: 'window'.") });+}+/** The largest window this caller may receive: the request, the per-window ceiling and the egress cap minus metadata room. */async function windowBudget(ctx: OperationContext, requested: number | undefined, fallback: number): Promise<number> {const cap = await resultByteCap({ remote: ctx.remote, transport: ctx.transport, engine: ctx.engine, config: ctx.config });@@ -232,14 +259,18 @@ function envelopeText(text: string, quarantined: QuarantinedView | null, trust?:return quarantined?.body_enveloped && text ? renderTrustedText(text, { trust_tier: 'external_untrusted', origin: trust?.origin ?? 'quarantined' }) : text;}-/** Resolve a chunk-centered window: stored span first, then an unambiguous text match, else the chunk itself. */-async function aroundChunk(ctx: OperationContext, page: Page, doc: PageDocument, chunkId: number, contextLines: number, maxBytes: number, revision: string):+/**+ * Resolve a chunk-centered window: stored span first, then an unambiguous text match, else the chunk itself. A+ * segmented page has no text match: its chunk's occurrence must be live (else revision_changed) and its+ * segment-relative span must still hold the chunk.+ */+async function aroundChunk(ctx: OperationContext, page: Page, doc: WindowDocument, chunkId: number, contextLines: number, maxBytes: number, revision: string):Promise<{ window: WindowSlice | null; chunkText: string; anchor: 'stored_span' | 'located' | 'chunk_only'; span?: { byte_start: number; byte_end: number } }> {- const rows = await ctx.engine.executeRaw<{ chunk_text: string; chunk_source: string; projected_byte_start: unknown; projected_byte_end: unknown }>(- `SELECT chunk_text, chunk_source, projected_byte_start, projected_byte_end FROM content_chunks+ const rows = await ctx.engine.executeRaw<{ chunk_text: string; chunk_source: string; occurrence_id: unknown; projected_byte_start: unknown; projected_byte_end: unknown }>(+ `SELECT chunk_text, chunk_source, occurrence_id, projected_byte_start, projected_byte_end FROM content_chunksWHERE id = $1 AND page_id = $2 AND COALESCE(modality, 'text') = 'text' AND ${chunkGenerationProbe('content_chunks')}`, [chunkId, page.id]);const row = rows[0];- if (!row) {+ if (!row || (doc.segments && !doc.segments.body.rows.some(r => r.occurrenceId === Number(row.occurrence_id)))) {throw opError('revision_changed', `Chunk ${chunkId} is not part of page ${page.slug} at its current revision.`,"The page was re-chunked or edited since that search. Search again for a current chunk_id, or read the page's outline.",{ legacy_error: 'invalid_params', detail: JSON.stringify({ revision, chunk_id: chunkId }),@@ -248,34 +279,96 @@ async function aroundChunk(ctx: OperationContext, page: Page, doc: PageDocument,const chunk = { chunk_source: row.chunk_source,projected_byte_start: row.projected_byte_start == null ? null : Number(row.projected_byte_start),projected_byte_end: row.projected_byte_end == null ? null : Number(row.projected_byte_end) };- const stored = chunkDocumentSpan(doc, chunk);- if (stored && spanHoldsChunk(doc, stored, row.chunk_text)) {- return { window: windowAround(doc.bytes, stored, contextLines, maxBytes), chunkText: row.chunk_text, anchor: 'stored_span', span: { byte_start: stored.start, byte_end: stored.end } };+ if (doc.segments) {+ const found = await doc.segments.aroundChunk({ ...chunk, occurrence_id: Number(row.occurrence_id), chunk_text: row.chunk_text }, contextLines, maxBytes);+ return found+ ? { window: found.window, chunkText: row.chunk_text, anchor: 'stored_span', span: { byte_start: found.span.start, byte_end: found.span.end } }+ : { window: null, chunkText: row.chunk_text, anchor: 'chunk_only' };+ }+ const inline = doc.inline!;+ const stored = chunkDocumentSpan(inline, chunk);+ if (stored && spanHoldsChunk(inline, stored, row.chunk_text)) {+ return { window: windowAround(inline.bytes, stored, contextLines, maxBytes), chunkText: row.chunk_text, anchor: 'stored_span', span: { byte_start: stored.start, byte_end: stored.end } };}// No stored span (a chunk written before spans were recorded) or a stale one: accept a text match only when it is unique.const needle = Buffer.from(row.chunk_text.trim(), 'utf8');if (needle.length >= 16) {- const at = doc.bytes.indexOf(needle);- if (at !== -1 && doc.bytes.indexOf(needle, at + 1) === -1) {+ const at = inline.bytes.indexOf(needle);+ if (at !== -1 && inline.bytes.indexOf(needle, at + 1) === -1) {const span = { start: at, end: at + needle.length };- return { window: windowAround(doc.bytes, span, contextLines, maxBytes), chunkText: row.chunk_text, anchor: 'located', span: { byte_start: span.start, byte_end: span.end } };+ return { window: windowAround(inline.bytes, span, contextLines, maxBytes), chunkText: row.chunk_text, anchor: 'located', span: { byte_start: span.start, byte_end: span.end } };}}return { window: null, chunkText: row.chunk_text, anchor: 'chunk_only' };}+/** What a partial read cuts: an inline page's document bytes, or a segmented page's stored sums and segments. */+interface WindowDocument {+ total: number;+ segmented: boolean;+ outline(from: number, limit: number): Promise<PageOutline>;+ from(offset: number, maxBytes: number): Promise<WindowSlice>;+ lines(from: number, count: number, maxBytes: number): Promise<WindowSlice>;+ bytes(offset: number, length: number): Promise<WindowSlice>;+ /** around_chunk_id's text: the inline document, or the segmented read view. */+ inline?: PageDocument;+ segments?: SegmentedDocument;+}++function inlineDocument(doc: PageDocument): WindowDocument {+ return {+ total: doc.bytes.length, segmented: false, inline: doc,+ outline: async (from, limit) => pageOutline(doc.bytes, from, limit),+ from: async (offset, maxBytes) => windowFrom(doc.bytes, offset, maxBytes),+ lines: async (from, count, maxBytes) => windowForLines(doc.bytes, from, count, maxBytes),+ bytes: async (offset, length) => windowForBytes(doc.bytes, offset, length),+ };+}++/**+ * A segmented page's document and size (spec 7.2): read-view totals from the stored sums (the line count cached+ * per revision), the stored body size, and for `none` the tail digest; a markdown view's size is its cached digest.+ */+async function segmentedWindows(ctx: OperationContext, input: PartialReadInput, req: BodyRequest, mode: BodyMode): Promise<{ doc: WindowDocument; size: Record<string, unknown> }> {+ const { page, revision, tags } = input;+ const body = await openSegmentedBody(ctx.engine, { pageId: page.id });+ const audience = ctx.remote === false ? 'trusted' : 'remote';+ const stored = { body_bytes: body.bodyBytes, body_lines: body.bodyLines };+ let seg: SegmentedDocument;+ let size: Record<string, unknown>;+ if (req.view === 'markdown') {+ seg = await segmentedMarkdownDocument(ctx.engine, body, markdownHead(page, tags), audience);+ size = { ...await markdownDigest(seg, revision, audience), ...stored };+ } else {+ seg = await segmentedReadDocument(ctx.engine, body);+ size = { total_bytes: seg.total, total_lines: await readViewLines(seg, revision), ...(seg.timelineByte >= 0 ? { timeline_byte_start: seg.timelineByte } : {}),+ ...stored, ...(mode === 'none' ? await tailDigest(ctx.engine, body, ctx.remote !== false) : {}) };+ }+ return { size, doc: {+ total: seg.total, segmented: true, segments: seg,+ outline: (from, limit) => segmentedOutline(seg, from, limit, Number(size.total_lines)),+ from: (offset, maxBytes) => seg.from(offset, maxBytes),+ lines: (from, count, maxBytes) => seg.lines(from, count, maxBytes),+ bytes: (offset, length) => seg.bytes(offset, length),+ } };+}+/** next_cursor plus `next`, the exact call that reads on (the starter surface does not advertise `cursor`; dispatch accepts it). */function setNext(out: Record<string, unknown>, page: Page, cursor: string, markdown: boolean): void {out.next_cursor = cursor;out.next = { tool: 'get_page', arguments: { slug: page.slug, source_id: page.source_id, cursor, ...(markdown ? { view: 'markdown' } : {}) } };}-/** The `body: 'none'` response: `out` plus chunk and embedding counts, no text. */+/**+ * The `body: 'none'` response: `out` plus chunk and embedding counts, no text. A segmented page reports no counts:+ * counting its chunks is O(page), and its `none` stays O(1) in the page size (spec 7.2).+ */async function noneResult(ctx: OperationContext, page: Page, out: Record<string, unknown>, truncated: boolean): Promise<Record<string, unknown>> {+ const fm = (page.frontmatter ?? {}) as Record<string, unknown>;+ if (isSegmentedPage(page)) return { ...out, ...(fm.embed_skip ? { embed_skip: true } : {}), truncated };const [counts] = await ctx.engine.executeRaw<{ total: unknown; embedded: unknown }>(`SELECT count(*) AS total, count(*) FILTER (WHERE embedded_at IS NOT NULL) AS embedded FROM content_chunksWHERE page_id = $1 AND ${chunkGenerationProbe('content_chunks')}`, [page.id]);- const fm = (page.frontmatter ?? {}) as Record<string, unknown>;return { ...out, chunks: { total: Number(counts?.total ?? 0), embedded: Number(counts?.embedded ?? 0) },...(fm.embed_skip ? { embed_skip: true } : {}), truncated };}@@ -294,32 +387,34 @@ export async function readPartialBody(ctx: OperationContext, input: PartialReadIconst omitted = quarantined?.body_omitted === true;const mode = req.mode === 'auto' ? 'outline' : req.mode;if (omitted) return { ...base, body: mode, truncated: true, body_omitted: true };- // Wave B PR 1: a segmented body is never loaded; `none` reports its stored size (windows arrive with the segment reader).- if (mode === 'none' && isSegmentedPage(page)) {- return noneResult(ctx, page, { ...base, body: mode, view: req.view, body_storage: 'segmented', size: { body_bytes: Number(page.body_bytes ?? 0) } }, true);- }const markdown = req.view === 'markdown';- const doc: PageDocument = markdown- ? { bytes: Buffer.from(serializePageToMarkdown(input.visibleBody, tags), 'utf8'), timelineByte: -1 }- : await readPageDocument(ctx.engine, page);- const size: Record<string, unknown> = {- total_bytes: doc.bytes.length, total_lines: totalLines(doc.bytes),- ...(doc.timelineByte >= 0 ? { timeline_byte_start: doc.timelineByte } : {}),- ...(markdown ? { sha256: sha256Hex(doc.bytes) } : {}),- };- const out: Record<string, unknown> = { ...base, body: mode, view: req.view, size };+ let doc: WindowDocument;+ let size: Record<string, unknown>;+ if (isSegmentedPage(page)) ({ doc, size } = await segmentedWindows(ctx, input, req, mode));+ else {+ const whole: PageDocument = markdown+ ? { bytes: Buffer.from(serializePageToMarkdown(input.visibleBody, tags), 'utf8'), timelineByte: -1 }+ : await readPageDocument(ctx.engine, page);+ size = {+ total_bytes: whole.bytes.length, total_lines: totalLines(whole.bytes),+ ...(whole.timelineByte >= 0 ? { timeline_byte_start: whole.timelineByte } : {}),+ ...(markdown ? { sha256: sha256Hex(whole.bytes) } : {}),+ };+ doc = inlineDocument(whole);+ }+ const out: Record<string, unknown> = { ...base, body: mode, view: req.view, ...(doc.segmented ? { body_storage: 'segmented' } : {}), size };- if (mode === 'none') return noneResult(ctx, page, out, doc.bytes.length > 0);+ if (mode === 'none') return noneResult(ctx, page, out, doc.total > 0);if (mode === 'outline') {const limit = Math.min(MAX_OUTLINE_LIMIT, DEFAULT_OUTLINE_LIMIT);- out.outline = pageOutline(doc.bytes, req.outlineFrom, limit);+ out.outline = await doc.outline(req.outlineFrom, limit);if (req.mode === 'auto') {- const first = windowFrom(doc.bytes, 0, await windowBudget(ctx, req.maxBytes, AUTO_WINDOW_BYTES));+ const first = await doc.from(0, await windowBudget(ctx, req.maxBytes, AUTO_WINDOW_BYTES));out.window = { ...first, text: envelopeText(first.text, quarantined, trust) };out.truncated = true;- if (first.byte_end < doc.bytes.length) setNext(out, page, encodeCursor({ page_id: page.id, revision, view: 'read', offset: first.byte_end, max_bytes: req.maxBytes ?? DEFAULT_WINDOW_BYTES }), false);+ if (first.byte_end < doc.total) setNext(out, page, encodeCursor({ page_id: page.id, revision, view: 'read', offset: first.byte_end, max_bytes: req.maxBytes ?? DEFAULT_WINDOW_BYTES }), false);out.auto_reason = 'over_inline_bytes';return out;}@@ -330,9 +425,9 @@ export async function readPartialBody(ctx: OperationContext, input: PartialReadIconst sel = req.selector;let cursorMax = req.maxBytes ?? DEFAULT_WINDOW_BYTES;const select = async (maxBytes: number): Promise<WindowSlice | null> => {- if (!sel) return windowFrom(doc.bytes, 0, maxBytes);- if (sel.kind === 'lines') return windowForLines(doc.bytes, sel.from, sel.count, maxBytes);- if (sel.kind === 'bytes') return windowForBytes(doc.bytes, sel.offset, Math.min(sel.length, maxBytes));+ if (!sel) return doc.from(0, maxBytes);+ if (sel.kind === 'lines') return doc.lines(sel.from, sel.count, maxBytes);+ if (sel.kind === 'bytes') return doc.bytes(sel.offset, Math.min(sel.length, maxBytes));if (sel.kind === 'cursor') {const c = decodeCursor(sel.raw);if (!c || c.page_id !== page.id) {@@ -342,7 +437,7 @@ export async function readPartialBody(ctx: OperationContext, input: PartialReadIthrow invalidParam(ctx, 'get_page', 'view', `get_page: this cursor pages view '${c.view}'; pass view: '${c.view}' with it.`, { choices: ['read', 'markdown'], example: c.view });}if (c.revision !== revision) {- const position = Math.min(c.offset, doc.bytes.length);+ const position = Math.min(c.offset, doc.total);throw opError('revision_changed', `Page ${page.slug} changed since this cursor was issued (revision ${c.revision}, now ${revision}).`,`Continue from the same byte offset at the current revision (bytes: { offset: ${position}, length: ${c.max_bytes} }), or start over from the outline.`,{ legacy_error: 'invalid_params', detail: JSON.stringify({ revision, cursor_revision: c.revision, offset: position }),@@ -350,7 +445,7 @@ export async function readPartialBody(ctx: OperationContext, input: PartialReadImcp: { tool: 'get_page', arguments: { slug: page.slug, source_id: page.source_id, body: 'window', ...(markdown ? { view: 'markdown' } : {}), bytes: { offset: position, length: c.max_bytes } } } }) });}cursorMax = c.max_bytes;- return windowFrom(doc.bytes, c.offset, Math.min(c.max_bytes, maxBytes));+ return doc.from(c.offset, Math.min(c.max_bytes, maxBytes));}const around = await aroundChunk(ctx, page, doc, sel.chunkId, req.contextLines, maxBytes, revision);out.anchor = around.anchor;@@ -365,8 +460,8 @@ export async function readPartialBody(ctx: OperationContext, input: PartialReadIconst win = await select(maxBytes);if (!win) return { ...out, truncated: true };out.window = { ...win, text: envelopeText(win.text, quarantined, trust) };- out.truncated = win.byte_start > 0 || win.byte_end < doc.bytes.length;- if (win.byte_end < doc.bytes.length) setNext(out, page, encodeCursor({ page_id: page.id, revision, view: req.view, offset: win.byte_end, max_bytes: cursorMax }), markdown);+ out.truncated = win.byte_start > 0 || win.byte_end < doc.total;+ if (win.byte_end < doc.total) setNext(out, page, encodeCursor({ page_id: page.id, revision, view: req.view, offset: win.byte_end, max_bytes: cursorMax }), markdown);else { delete out.next_cursor; delete out.next; }if (!Number.isFinite(cap) || attempt >= 6) return out;const frame = encodedFrameBytes({ content: [{ type: 'text', text: JSON.stringify(out) }] }) + ENVELOPE_RESERVE_BYTES - FRAME_RESERVE_BYTES;diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.tsindex c5055cda8e..9e7eeed6d0 100644--- a/src/core/ops/pages.ts+++ b/src/core/ops/pages.ts@@ -19,7 +19,8 @@ import { PageSnapshotAmbiguousError, type PageSnapshot } from '../page-state/typimport { serializePageToMarkdown } from '../markdown.ts';import { pageTrustForRead, projectFetchText, projectGetPage, readQuarantined } from './get-page-projection.ts';import { assertLargePageAdmission } from '../persistence/large-page-guard.ts';-import { assertFullReadFits, bodyBytes, fetchWindowResult, GET_PAGE_BODY_PARAMS, inlineBodyBytes, parseBodyRequest, readPartialBody } from './get-page-body.ts';+import { assertFullReadFits, bodyBytes, fetchWindowResult, GET_PAGE_BODY_PARAMS, inlineBodyBytes, parseBodyRequest, readPartialBody, segmentedFullReadError } from './get-page-body.ts';+import { isSegmentedPage } from '../page-body/page-shape.ts';import { MIN_TRUST_PARAM } from '../eligibility/policy.ts';import { stampRowTrust } from '../eligibility/stamp.ts';import { isAutoLinkEnabled } from '../link-extraction.ts';@@ -220,14 +221,16 @@ const get_page: Operation = {const lineGrammar = p.grammar_diagnostics === true ? await (await import('../line-grammar-report.ts')).lineGrammarReport(ctx.engine, { slug: page.slug, sourceId: page.source_id, body: visibleBody.compiled_truth }) : undefined;const quarantined = readQuarantined(ctx, page, p.include_quarantined === true); // #6259const fileHeld = held ? { file_held: fileHeldField(held, isUntrustedReader) } : {};+ const segmented = isSegmentedPage(page);const whole = bodyRequest.mode === 'full'- || (bodyRequest.mode === 'auto' && bodyBytes(visibleBody) <= await inlineBodyBytes(ctx));+ || (bodyRequest.mode === 'auto' && !segmented && bodyBytes(visibleBody) <= await inlineBodyBytes(ctx));if (!whole) {const partial = await readPartialBody(ctx, { page, visibleBody, revision: snapshot!.revision, tags, quarantined, trust: readable.trust,extras: { ...(quarantined ? { quarantined } : {}), ...(timelineEntries ? { timeline_entries: timelineEntries } : {}), ...fileHeld,...(resolved_slug ? { resolved_slug } : {}), ...(content_flag ? { content_flag } : {}) } }, bodyRequest);return lineGrammar ? { ...partial, line_grammar: lineGrammar } : partial;}+ if (segmented) throw segmentedFullReadError(ctx, page, bodyRequest);const projected = projectGetPage(visibleBody, {revision: snapshot!.revision, tags, includeContent, contentOnly, resolved_slug, content_flag, quarantined, trust: readable.trust,...(timelineEntries ? { timeline_entries: timelineEntries } : {}),@@ -292,9 +295,10 @@ const fetch_page: Operation = {bumpLastRetrievedAt(ctx.engine, [page.id]);const tags = snapshot!.tags;// Same boundaries as get_page: untrusted readers never see takes or private facts fences, nor a quarantined body (#6259).- const visibleBody = ctx.remote === false ? page : stripPrivacyFencesForRemoteReader(page);+ const segmented = isSegmentedPage(page);+ const visibleBody = ctx.remote === false || segmented ? page : stripPrivacyFencesForRemoteReader(page);const quarantined = readQuarantined(ctx, page, p.include_quarantined === true);- if (ctx.remote !== false && !quarantined?.body_omitted && bodyBytes(visibleBody) > await inlineBodyBytes(ctx)) {+ if (!quarantined?.body_omitted && (segmented || (ctx.remote !== false && bodyBytes(visibleBody) > await inlineBodyBytes(ctx)))) {return fetchWindowResult(ctx, { page, visibleBody: visibleBody as Page, revision: snapshot!.revision, tags, quarantined, trust: readable.trust, extras: {} }, id, identity ? decodeDeepResearchAnchor(id) : null);}return {diff --git a/src/core/page-body/read-range.ts b/src/core/page-body/read-range.tsindex 5f2d0bbbc0..eb9e40e84b 100644--- a/src/core/page-body/read-range.ts+++ b/src/core/page-body/read-range.ts@@ -56,6 +56,7 @@ export interface BodyRow {byteStart: number;byteLen: number;lineStart: number;+ lineCount: number;staticProjBytes: number;staticProjLines: number;outlineCount: number;@@ -70,6 +71,7 @@ export interface SegmentedBody {slug: string;generation: number;bodyBytes: number;+ bodyLines: number;truthBytes: number;flags: JsonObject;rows: BodyRow[];@@ -125,28 +127,31 @@ export interface BodyRangePiece {const utf8 = new TextDecoder('utf-8', { fatal: true });const HEAVY_BATCH = 64;const toJson = (v: unknown) => typeof v === 'string' ? JSON.parse(v) as unknown : v;-const bytesOf = (v: unknown): Uint8Array => { const b = v as Uint8Array; return new Uint8Array(b.buffer, b.byteOffset, b.byteLength); };const newlines = (s: string) => { let n = 0; for (let i = s.indexOf('\n'); i !== -1; i = s.indexOf('\n', i + 1)) n++; return n; };export async function openSegmentedBody(engine: BrainEngine, opts: { pageId: number; generation?: number; ledger?: BodyLedger }): Promise<SegmentedBody> {- const [page] = await engine.executeRaw<Record<string, unknown>>(`SELECT id, source_id, slug, body_storage, body_generation, body_bytes, truth_bytes,+ const [page] = await engine.executeRaw<Record<string, unknown>>(`SELECT id, source_id, slug, body_storage, body_generation, body_bytes, body_lines, truth_bytes,body_flags, segmenter_version FROM pages WHERE id=$1`, [opts.pageId]);if (!page || page.body_storage !== 'segmented') throw new Error(`Page ${opts.pageId} is not a segmented page.`);const generation = opts.generation ?? Number(page.body_generation);- const rows = await engine.executeRaw<Record<string, unknown>>(`SELECT m.seq, m.occurrence_id, m.region, m.sha256, m.byte_start, m.byte_len,- m.line_start, m.static_proj_bytes, m.static_proj_lines, jsonb_array_length(m.outline) AS outline_count,- jsonb_array_length(m.facts_slots) > 0 AS has_facts, m.date_min IS NOT NULL AS has_date+ // One JSON row instead of one result row per segment: PGLite spends about 10 us per result row, and these sums are+ // all a body: 'none' read of a large page costs beyond a constant.+ const [listed] = await engine.executeRaw<{ rows: unknown }>(`SELECT coalesce(json_agg(json_build_object('seq', m.seq, 'occurrence_id', m.occurrence_id,+ 'region', m.region, 'sha256', encode(m.sha256, 'hex'), 'byte_start', m.byte_start, 'byte_len', m.byte_len, 'line_start', m.line_start,+ 'line_count', m.line_count, 'static_proj_bytes', m.static_proj_bytes, 'static_proj_lines', m.static_proj_lines, 'outline_count', jsonb_array_length(m.outline),+ 'has_facts', jsonb_array_length(m.facts_slots) > 0, 'has_date', m.date_min IS NOT NULL) ORDER BY m.seq), '[]') AS rowsFROM page_body_manifest m- WHERE m.page_id=$1 AND m.staging_id IS NULL AND m.gen_from<=$2 AND (m.gen_to IS NULL OR m.gen_to>$2) ORDER BY m.seq`, [opts.pageId, generation]);+ WHERE m.page_id=$1 AND m.staging_id IS NULL AND m.gen_from<=$2 AND (m.gen_to IS NULL OR m.gen_to>$2)`, [opts.pageId, generation]);+ const rows = toJson(listed?.rows ?? '[]') as Array<Record<string, unknown>>;const slug = String(page.slug);const sourceId = String(page.source_id);const ledger = opts.ledger ?? await readBodyLedger(engine, sourceId, slug);return {- pageId: opts.pageId, sourceId, slug, generation, bodyBytes: Number(page.body_bytes ?? 0), truthBytes: Number(page.truth_bytes ?? 0),+ pageId: opts.pageId, sourceId, slug, generation, bodyBytes: Number(page.body_bytes ?? 0), bodyLines: Number(page.body_lines ?? 0), truthBytes: Number(page.truth_bytes ?? 0),flags: (toJson(page.body_flags) ?? {}) as JsonObject, ledger, stale: Number(page.segmenter_version) !== SEGMENTER_VERSION,rows: rows.map(r => ({- seq: Number(r.seq), occurrenceId: Number(r.occurrence_id), region: r.region as BodyRegion, sha256: bytesOf(r.sha256),- byteStart: Number(r.byte_start), byteLen: Number(r.byte_len), lineStart: Number(r.line_start), staticProjBytes: Number(r.static_proj_bytes),+ seq: Number(r.seq), occurrenceId: Number(r.occurrence_id), region: r.region as BodyRegion, sha256: new Uint8Array(Buffer.from(String(r.sha256), 'hex')),+ byteStart: Number(r.byte_start), byteLen: Number(r.byte_len), lineStart: Number(r.line_start), lineCount: Number(r.line_count), staticProjBytes: Number(r.static_proj_bytes),staticProjLines: Number(r.static_proj_lines), outlineCount: Number(r.outline_count), hasFacts: r.has_facts === true, hasDate: r.has_date === true,})),};@@ -293,10 +298,11 @@ export async function projectedTotals(engine: BrainEngine, body: SegmentedBody):return { total_bytes: layout.totalBytes, total_lines: lines, timeline_byte_start: layout.timelineByte };}-type Unit = { kind: 'row'; index: number; start: number } | { kind: 'text'; text: string; start: number; storedStart: number; region: BodyRegion | null };+export type ProjectedUnit = { kind: 'row'; index: number; start: number } | { kind: 'text'; text: string; start: number; storedStart: number; region: BodyRegion | null };+type Unit = ProjectedUnit;/** The read projection's parts in document order: truth rows, the low-tier block, the separator, timeline rows. */-function units(body: SegmentedBody, layout: ProjectedLayout): Unit[] {+export function projectedUnits(body: SegmentedBody, layout: ProjectedLayout): Unit[] {const out: Unit[] = [];body.rows.forEach((row, i) => { if (row.region === 'truth') out.push({ kind: 'row', index: i, start: layout.rowStart[i]! }); });if (layout.lowTier) out.push({ kind: 'text', text: layout.lowTier, start: layout.lowTierStart, storedStart: body.truthBytes, region: 'truth' });@@ -352,7 +358,7 @@ function cutStored(piece: ProjectedPiece, base: number, start: number, end: numbasync function* projectedRange(engine: BrainEngine, body: SegmentedBody, req: BodyRangeRequest): AsyncIterable<BodyRangePiece> {const layout = await projectedLayout(engine, body);- const wanted = units(body, layout).filter(u => {+ const wanted = projectedUnits(body, layout).filter(u => {const region = u.kind === 'row' ? body.rows[u.index]!.region : u.region;return (!req.region || region === req.region) && u.start < req.end && u.start + unitBytes(u, layout) > req.start;});@@ -387,7 +393,7 @@ export async function projectedLineStart(engine: BrainEngine, body: SegmentedBodconst layout = await projectedLayout(engine, body);let want = line - 1;if (want <= 0) return 0;- for (const u of units(body, layout)) {+ for (const u of projectedUnits(body, layout)) {const count = u.kind === 'row' ? layout.rowNewlines[u.index]! : newlines(u.text);if (want > count) { want -= count; continue; }let text = '';diff --git a/src/core/page-window/segmented.ts b/src/core/page-window/segmented.tsnew file mode 100644index 0000000000..3a8f07b05c--- /dev/null+++ b/src/core/page-window/segmented.ts@@ -0,0 +1,465 @@+/**+ * Segmented pages (Wave B, spec 7.2 and 7.4): get_page windows, outlines and+ * markdown pages over a segmented body, cut from the stored sums plus the+ * segments a read touches. Nothing here holds the whole body.+ *+ * A document is a run of units in the coordinates an inline page uses (UTF-8+ * bytes, 1-based lines): one per segment's projection plus literal text (the+ * low-tier block, TIMELINE_SEPARATOR, a markdown frontmatter head and final+ * newline), each with its byte and newline count from the manifest sums.+ *+ * - The read view is the read projection (page-body/read-range.ts), what+ * windows, outlines and around_chunk_id address for every caller.+ * - The markdown view is serializeMarkdown's frame around the body the caller+ * may see: the remote read projection (fail closed: never looser than an+ * inline page's stripPrivacyFencesForRemoteReader) or, for a trusted local+ * caller, the stored body after the withdrawal overlay.+ *+ * A window reads a slab: from the start of the unit holding the selector's+ * earliest byte (minus its look-back) to its farthest byte plus EDGE. Wave A's+ * cutters (window.ts) run on the slab unchanged and slabWindow moves offsets+ * and lines by the slab's start and the newlines before it. The look-back and+ * look-ahead per selector keep every cutter from mistaking a slab edge for a+ * document edge, so each cut equals the whole-document cut.+ *+ * {total_bytes, total_lines, sha256} of a markdown view stream the view once+ * per (page, revision, audience), cached in page_view_digests with the read+ * view's line count, so paging a page to its end is linear. A cached row is+ * used only while its byte total matches the stored sums.+ */+import { createHash } from 'node:crypto';+import type { BrainEngine } from '../engine.ts';+import type { Page } from '../types.ts';+import { serializePageToMarkdown } from '../markdown.ts';+import { withoutBody } from '../page-body/page-shape.ts';+import { ledgerApplies } from '../page-body/segment-ledger.ts';+import { projectedLayout, projectedOutline, projectedUnits, readBodyRange, type SegmentedBody } from '../page-body/read-range.ts';+import { TIMELINE_SEPARATOR, spanHoldsChunk } from './document.ts';+import { DATE, sliceWindow, slabWindow, windowAround, windowForBytes, windowFrom, type DocumentSlab, type OutlineEntry, type PageOutline, type WindowSlice } from './window.ts';++export type ViewAudience = 'trusted' | 'remote';++/** Bytes past a window's farthest byte the cutters may test (the byte after maxEnd, a code point). */+const EDGE = 8;+/** Segment text one outline page reads for line numbers and dates (Wave A scans the whole page per call); later entries move to the next page. */+const OUTLINE_READ_BYTES = 4 * 1024 * 1024;+/** Raw bytes `tail_sha256` covers at the end of the last non-empty region. */+const TAIL_BYTES = 4096;+const NL = 0x0a;++export interface DocumentUnit {+ start: number;+ bytes: number;+ newlines: number;+ /** Index into body.rows; -1 for literal `text`. */+ row: number;+ text?: string;+}++type Reader = (start: number, end: number) => Promise<Buffer>;++function newlinesIn(b: Uint8Array): number {+ let n = 0;+ for (let i = b.indexOf(NL); i !== -1; i = b.indexOf(NL, i + 1)) n++;+ return n;+}++const textUnit = (start: number, text: string): DocumentUnit => {+ const bytes = Buffer.from(text, 'utf8');+ return { start, bytes: bytes.length, newlines: newlinesIn(bytes), row: -1, text };+};++/** The last unit starting at or before `b`; -1 when none. */+function unitAt(units: readonly DocumentUnit[], b: number): number {+ let lo = 0, hi = units.length - 1, at = -1;+ while (lo <= hi) {+ const mid = (lo + hi) >> 1;+ if (units[mid]!.start <= b) { at = mid; lo = mid + 1; } else hi = mid - 1;+ }+ return at;+}++export class SegmentedDocument {+ readonly newlines: number;+ private readonly before: number[];++ constructor(readonly engine: BrainEngine, readonly body: SegmentedBody, readonly total: number, readonly units: readonly DocumentUnit[],+ private readonly reader: Reader, readonly timelineByte = -1) {+ let n = 0;+ this.before = units.map(u => { const at = n; n += u.newlines; return at; });+ this.newlines = n;+ }++ unitAt(b: number): number { return unitAt(this.units, b); }++ readUnit(i: number): Promise<Buffer> {+ const u = this.units[i]!;+ return u.row < 0 ? Promise.resolve(Buffer.from(u.text!, 'utf8')) : this.reader(u.start, u.start + u.bytes);+ }++ /** Bytes [from, to) widened back to the start of the unit holding `from`, clipped to the document. */+ async slab(from: number, to: number): Promise<DocumentSlab> {+ const i = this.unitAt(Math.max(0, Math.min(from, this.total - 1)));+ if (i < 0) return { bytes: Buffer.alloc(0), start: 0, linesBefore: 0 };+ const start = this.units[i]!.start;+ const end = Math.min(this.total, Math.max(start, to));+ return { bytes: end > start ? await this.reader(start, end) : Buffer.alloc(0), start, linesBefore: this.before[i]! };+ }++ /** windowFrom: snapCodePoint looks back at most 3 bytes. */+ async from(offset: number, maxBytes: number): Promise<WindowSlice> {+ const s = await this.slab(offset - 4, offset + maxBytes + EDGE);+ return slabWindow(s, b => windowFrom(b, offset - s.start, maxBytes));+ }++ /** windowForBytes: the start moves back to its line start only within `length` bytes. */+ async bytes(offset: number, length: number): Promise<WindowSlice> {+ const at = Math.max(0, Math.min(offset, this.total));+ const s = await this.slab(at - length - 1, at + length + EDGE);+ return slabWindow(s, b => windowForBytes(b, at - s.start, length));+ }++ /** windowForLines, with both line offsets from the newline sums (one segment read each). */+ async lines(from: number, count: number, maxBytes: number): Promise<WindowSlice> {+ const start = await this.lineStart(from);+ if (start >= this.total) return this.from(this.total, maxBytes);+ const target = await this.lineStart(from + count);+ const whole = target - start <= maxBytes;+ const s = await this.slab(start, whole ? target : start + maxBytes + EDGE);+ return slabWindow(s, b => whole ? sliceWindow(b, start - s.start, target - s.start) : windowFrom(b, start - s.start, maxBytes));+ }++ /**+ * The window around a segmented chunk: its occurrence's place in the read view plus the segment-relative+ * projected span. Null when the chunk has no span or the span no longer holds its text (no text search).+ * windowAround looks back context lines and centers within maxBytes: a slab maxBytes wide on each side keeps+ * both decisions exact.+ */+ async aroundChunk(chunk: { occurrence_id: number; projected_byte_start: number | null; projected_byte_end: number | null; chunk_text: string },+ contextLines: number, maxBytes: number): Promise<{ window: WindowSlice; span: { start: number; end: number } } | null> {+ const unit = this.units.find(u => u.row >= 0 && this.body.rows[u.row]!.occurrenceId === chunk.occurrence_id);+ const s0 = chunk.projected_byte_start, e0 = chunk.projected_byte_end;+ if (!unit || s0 == null || e0 == null || !(e0 > s0) || s0 < 0 || e0 > unit.bytes) return null;+ const span = { start: unit.start + s0, end: unit.start + e0 };+ const s = await this.slab(span.start - maxBytes - 1, Math.max(span.end, span.start + maxBytes) + EDGE);+ const local = { start: span.start - s.start, end: span.end - s.start };+ if (!spanHoldsChunk({ bytes: s.bytes, timelineByte: -1 }, local, chunk.chunk_text)) return null;+ return { window: slabWindow(s, b => windowAround(b, local, contextLines, maxBytes)), span };+ }++ /** Byte where 1-based `line` starts (lineOffset): the newline sums find its unit, which is read. */+ async lineStart(line: number): Promise<number> {+ const want = line - 1;+ if (want <= 0) return 0;+ for (let i = 0; i < this.units.length; i++) {+ const u = this.units[i]!;+ if (this.before[i]! + u.newlines < want) continue;+ const buf = await this.readUnit(i);+ let at = -1;+ for (let k = want - this.before[i]!; k > 0; k--) {+ at = buf.indexOf(NL, at + 1);+ if (at === -1) return u.start + buf.length;+ }+ return u.start + at + 1;+ }+ return this.total;+ }++ /** 1-based line of byte `b`, from the newline sums and the text of the unit holding it. */+ lineAt(b: number, text: Buffer): number {+ const i = this.unitAt(b);+ return i < 0 ? 1 : 1 + this.before[i]! + newlinesIn(text.subarray(0, b - this.units[i]!.start));+ }++ linesBefore(i: number): number { return this.before[i] ?? this.newlines; }++ /** totalLines: the newline sums plus whether the last byte is a newline (reads the last unit). */+ async totalLines(): Promise<number> {+ if (this.total === 0) return 0;+ const last = await this.reader(this.total - 1, this.total);+ return this.newlines + (last[last.length - 1] === NL ? 0 : 1);+ }++ /** The whole document, a unit at a time. */+ async *stream(): AsyncIterable<Buffer> {+ for (let i = 0; i < this.units.length; i++) if (this.units[i]!.bytes > 0) yield await this.readUnit(i);+ }+}++async function projectedBytes(engine: BrainEngine, body: SegmentedBody, start: number, end: number): Promise<Buffer> {+ const parts: Buffer[] = [];+ for await (const piece of readBodyRange(engine, { pageId: body.pageId, space: 'projected', start, end, audience: 'remote', body })) parts.push(piece.bytes);+ return Buffer.concat(parts);+}++async function trustedBytes(engine: BrainEngine, body: SegmentedBody, start: number, end: number): Promise<Buffer> {+ const parts: Buffer[] = [];+ for await (const piece of readBodyRange(engine, { pageId: body.pageId, space: 'stored', start, end, audience: 'trusted', body })) parts.push(piece.bytes);+ return Buffer.concat(parts);+}++/** The read projection as a document: what windows, outlines and around_chunk_id cut, for every caller. */+export async function segmentedReadDocument(engine: BrainEngine, body: SegmentedBody): Promise<SegmentedDocument> {+ const layout = await projectedLayout(engine, body);+ const units = projectedUnits(body, layout).map(u => u.kind === 'row'+ ? { start: u.start, bytes: layout.rowBytes[u.index]!, newlines: layout.rowNewlines[u.index]!, row: u.index }+ : textUnit(u.start, u.text));+ return new SegmentedDocument(engine, body, layout.totalBytes, units, (start, end) => projectedBytes(engine, body, start, end), layout.timelineByte);+}++/** serializePageToMarkdown's frontmatter head: everything before the body. */+export function markdownHead(page: Page, tags: string[]): string {+ return serializePageToMarkdown({ ...withoutBody(page), compiled_truth: '', timeline: '' } as Page, tags).slice(0, -1);+}++/**+ * The markdown view: `head`, the body this audience may see, and serializeMarkdown's final newline. Remote: the read+ * projection. Trusted: the stored body after the withdrawal overlay (rows the overlay can rewrite, those with facts+ * regions, are measured when the page has a ledger), the timeline after TIMELINE_SEPARATOR when it has text.+ */+export async function segmentedMarkdownDocument(engine: BrainEngine, body: SegmentedBody, head: string, audience: ViewAudience): Promise<SegmentedDocument> {+ const units: DocumentUnit[] = [textUnit(0, head)];+ let pos = units[0]!.bytes;+ const push = (u: Omit<DocumentUnit, 'start'>) => { units.push({ ...u, start: pos }); pos += u.bytes; };+ let read: Reader;+ if (audience === 'remote') {+ const projected = await segmentedReadDocument(engine, body);+ const h = pos;+ for (const u of projected.units) push(u);+ read = async (start, end) => {+ const parts: Buffer[] = [Buffer.from(head, 'utf8').subarray(Math.min(start, h), Math.min(end, h))];+ if (end > h && start < h + projected.total) parts.push(await projectedBytes(engine, body, Math.max(0, start - h), Math.min(projected.total, end - h)));+ if (end > h + projected.total) parts.push(Buffer.from('\n'));+ return Buffer.concat(parts);+ };+ } else {+ const measured = new Map<number, { bytes: number; newlines: number }>();+ if (ledgerApplies(body.ledger)) {+ for (const [i, row] of body.rows.entries()) {+ if (!row.hasFacts) continue;+ const text = await trustedBytes(engine, body, row.byteStart, row.byteStart + row.byteLen);+ measured.set(i, { bytes: text.length, newlines: newlinesIn(text) });+ }+ }+ const rowUnits = body.rows.map((row, i) => ({ bytes: row.byteLen, newlines: row.lineCount, ...measured.get(i), row: i }));+ rowUnits.filter(u => body.rows[u.row]!.region === 'truth').forEach(push);+ const timeline = rowUnits.filter(u => body.rows[u.row]!.region === 'timeline');+ if (timeline.some(u => u.bytes > 0)) {+ push(textUnit(0, TIMELINE_SEPARATOR));+ timeline.forEach(push);+ }+ read = async (start, end) => {+ let i = unitAt(units, start);+ if (i < 0) return Buffer.alloc(0);+ const base = units[i]!.start;+ const parts: Buffer[] = [];+ while (i < units.length && units[i]!.start < end) {+ const u = units[i]!;+ if (u.row < 0) { parts.push(Buffer.from(u.text!, 'utf8')); i++; continue; }+ let j = i;+ while (j + 1 < units.length && units[j + 1]!.row >= 0 && units[j + 1]!.start < end) j++;+ const last = body.rows[units[j]!.row]!;+ parts.push(await trustedBytes(engine, body, body.rows[u.row]!.byteStart, last.byteStart + last.byteLen));+ i = j + 1;+ }+ return Buffer.concat(parts).subarray(start - base, end - base);+ };+ }+ push(textUnit(0, '\n'));+ return new SegmentedDocument(engine, body, pos, units, (start, end) => read(start, end));+}++interface Digest { total_bytes: number; total_lines: number; sha256: string | null }++async function readDigest(doc: SegmentedDocument, revision: string, view: 'read' | 'markdown', audience: ViewAudience): Promise<Digest | null> {+ const [row] = await doc.engine.executeRaw<{ total_bytes: unknown; total_lines: unknown; sha256: string | null }>(+ `SELECT total_bytes, total_lines, sha256 FROM page_view_digests WHERE page_id=$1 AND revision=$2 AND view=$3 AND audience=$4`,+ [doc.body.pageId, revision, view, audience]);+ if (!row || Number(row.total_bytes) !== doc.total) return null;+ return { total_bytes: Number(row.total_bytes), total_lines: Number(row.total_lines), sha256: row.sha256 };+}++/** Best effort: a reader that cannot write the cache recomputes next time. Rows of older revisions go. */+async function writeDigest(doc: SegmentedDocument, revision: string, view: 'read' | 'markdown', audience: ViewAudience, d: Digest): Promise<void> {+ try {+ await doc.engine.executeRaw('DELETE FROM page_view_digests WHERE page_id=$1 AND revision<>$2', [doc.body.pageId, revision]);+ await doc.engine.executeRaw(`INSERT INTO page_view_digests (page_id, revision, view, audience, total_bytes, total_lines, sha256) VALUES ($1, $2, $3, $4, $5, $6, $7)+ ON CONFLICT (page_id, revision, view, audience) DO UPDATE SET total_bytes=EXCLUDED.total_bytes, total_lines=EXCLUDED.total_lines, sha256=EXCLUDED.sha256, created_at=now()`,+ [doc.body.pageId, revision, view, audience, d.total_bytes, d.total_lines, d.sha256]);+ } catch { /* cache only */ }+}++/** {total_bytes, total_lines, sha256} of a markdown view: one streamed pass per (page, revision, audience). */+export async function markdownDigest(doc: SegmentedDocument, revision: string, audience: ViewAudience): Promise<{ total_bytes: number; total_lines: number; sha256: string }> {+ const cached = await readDigest(doc, revision, 'markdown', audience);+ if (cached?.sha256) return { total_bytes: cached.total_bytes, total_lines: cached.total_lines, sha256: cached.sha256 };+ const hash = createHash('sha256');+ let bytes = 0, lines = 0, last = -1;+ for await (const b of doc.stream()) {+ hash.update(b);+ bytes += b.length;+ lines += newlinesIn(b);+ last = b[b.length - 1]!;+ }+ const digest = { total_bytes: bytes, total_lines: bytes === 0 ? 0 : lines + (last === NL ? 0 : 1), sha256: hash.digest('hex') };+ await writeDigest(doc, revision, 'markdown', audience, digest);+ return digest;+}++/** The read view's line count, cached so a window does not read the last segment each call. */+export async function readViewLines(doc: SegmentedDocument, revision: string): Promise<number> {+ const cached = await readDigest(doc, revision, 'read', 'remote');+ if (cached) return cached.total_lines;+ const total_lines = await doc.totalLines();+ await writeDigest(doc, revision, 'read', 'remote', { total_bytes: doc.total, total_lines, sha256: null });+ return total_lines;+}++/**+ * sha256 of the raw last min(4096, region bytes) of the last non-empty region (the append precondition). A remote+ * caller gets it only when those rows hold no protected or facts region: a hash of hidden text is a guessing oracle.+ */+export async function tailDigest(engine: BrainEngine, body: SegmentedBody, remote: boolean): Promise<{ tail_sha256: string; tail_region: string } | Record<string, never>> {+ const region = body.rows.some(r => r.region === 'timeline' && r.byteLen > 0) ? 'timeline' : 'truth';+ const rows = body.rows.filter(r => r.region === region);+ const tail: typeof rows = [];+ for (let i = rows.length - 1, bytes = 0; i >= 0 && bytes < TAIL_BYTES; i--) { tail.unshift(rows[i]!); bytes += rows[i]!.byteLen; }+ if (!tail.length) return {};+ if (remote) {+ const [guarded] = await engine.executeRaw<{ n: unknown }>(`SELECT count(*) AS n FROM page_body_manifest WHERE page_id=$1 AND occurrence_id=ANY($2::bigint[])+ AND staging_id IS NULL AND gen_from<=$3 AND (gen_to IS NULL OR gen_to>$3) AND (protected_regions <> '[]'::jsonb OR facts_slots <> '[]'::jsonb)`,+ [body.pageId, tail.map(r => r.occurrenceId), body.generation]);+ if (Number(guarded?.n ?? 1) > 0) return {};+ }+ const texts = await engine.readSegmentTexts(body.sourceId, tail.map(r => r.sha256));+ const raw = Buffer.concat(tail.map(r => texts.get(Buffer.from(r.sha256).toString('hex')) ?? new Uint8Array()));+ return { tail_sha256: createHash('sha256').update(raw.subarray(Math.max(0, raw.length - TAIL_BYTES))).digest('hex'), tail_region: region };+}++/** Stored per-segment date ranges (static projection text), by row index. */+async function storedDates(doc: SegmentedDocument, rowIndexes: number[]): Promise<Map<number, { min: string; max: string }>> {+ const out = new Map<number, { min: string; max: string }>();+ const want = rowIndexes.filter(i => doc.body.rows[i]!.hasDate);+ if (!want.length) return out;+ const byOccurrence = new Map(want.map(i => [doc.body.rows[i]!.occurrenceId, i]));+ const rows = await doc.engine.executeRaw<{ occurrence_id: unknown; date_min: string | null; date_max: string | null }>(+ `SELECT occurrence_id, date_min::text AS date_min, date_max::text AS date_max FROM page_body_manifest WHERE page_id=$1 AND occurrence_id=ANY($2::bigint[])+ AND staging_id IS NULL AND gen_from<=$3 AND (gen_to IS NULL OR gen_to>$3)`, [doc.body.pageId, [...byOccurrence.keys()], doc.body.generation]);+ for (const r of rows) if (r.date_min && r.date_max) out.set(byOccurrence.get(Number(r.occurrence_id))!, { min: r.date_min, max: r.date_max });+ return out;+}++class DateRange {+ min?: string;+ max?: string;+ add(min: string, max = min): void {+ if (!this.min || min < this.min) this.min = min;+ if (!this.max || max > this.max) this.max = max;+ }+ scan(text: string): void { for (const m of text.matchAll(DATE)) this.add(m[0]); }+ fields(): { date_min?: string; date_max?: string } { return this.min ? { date_min: this.min, date_max: this.max } : {}; }+}++/**+ * pageOutline over the read view from the stored headings (paged by index through projectedOutline): headings when+ * the page stores at least two, with the text before the first as a leading entry when it is not blank; else one+ * block per segment. Heading entries read the segments holding their boundaries (at most OUTLINE_READ_BYTES per+ * page) for line numbers and dates; segments wholly inside an entry give their stored date range. Blocks read no+ * text: no first_line, stored dates, and line_end assumes the block ends with a newline (true at every cut but a+ * forced one).+ */+export async function segmentedOutline(doc: SegmentedDocument, from: number, limit: number, totalLines: number): Promise<PageOutline> {+ const { engine, body } = doc;+ const stored = await projectedOutline(engine, body, 0, 1);+ if (stored.total_entries < 2) return blocksOutline(doc, from, limit, totalLines);+ const lead = stored.entries[0]!.byte_start > 0 && !await blankBefore(doc, stored.entries[0]!.byte_start);+ const total = stored.total_entries + (lead ? 1 : 0);+ const n = Math.max(0, Math.min(limit, total - from));+ const headings = n ? (await projectedOutline(engine, body, Math.max(0, from - (lead ? 1 : 0)), n + 1)).entries : [];+ const bounds = [...(lead && from === 0 ? [{ start: 0, heading: null as string | null, level: 0 }] : []),+ ...headings.map(h => ({ start: h.byte_start, heading: h.heading as string | null, level: h.level }))].slice(0, n + 1);+ const boundary = (k: number) => bounds[k] ? [doc.unitAt(bounds[k]!.start)].filter(i => doc.units[i]!.row >= 0) : [];+ const reads = new Set<number>();+ let count = 0;+ for (let readBytes = 0; count < n; count++) {+ const want = [...new Set([...boundary(count), ...boundary(count + 1)])].filter(i => !reads.has(i));+ const more = want.reduce((sum, i) => sum + doc.units[i]!.bytes, 0);+ if (count > 0 && readBytes + more > OUTLINE_READ_BYTES) break;+ want.forEach(i => reads.add(i));+ readBytes += more;+ }+ const end = (k: number) => bounds[k + 1]?.start ?? doc.total;+ const interior: number[] = [];+ for (let k = 0; k < count; k++) {+ for (let i = doc.unitAt(bounds[k]!.start); i <= doc.unitAt(end(k) - 1); i++) {+ const row = doc.units[i]!.row;+ if (row < 0 || reads.has(i)) continue;+ if (body.rows[row]!.hasFacts) reads.add(i); else interior.push(row);+ }+ }+ const texts = new Map<number, Buffer>();+ for (const i of reads) texts.set(i, await doc.readUnit(i));+ const dates = await storedDates(doc, interior);+ const textOf = async (i: number) => texts.get(i) ?? await doc.readUnit(i);+ const lineAt = async (b: number) => doc.lineAt(b, await textOf(doc.unitAt(b)));+ const entries: OutlineEntry[] = [];+ for (let k = 0; k < count; k++) {+ const { start, heading, level } = bounds[k]!;+ const stop = end(k);+ const range = new DateRange();+ for (let i = doc.unitAt(start); i <= doc.unitAt(stop - 1); i++) {+ const u = doc.units[i]!;+ if (u.row >= 0 && !texts.has(i)) {+ const d = dates.get(u.row);+ if (d) range.add(d.min, d.max);+ continue;+ }+ const text = await textOf(i);+ range.scan(text.subarray(Math.max(start, u.start) - u.start, Math.min(stop, u.start + u.bytes) - u.start).toString('utf8'));+ }+ const lineStart = await lineAt(start);+ entries.push({+ heading, ...(level ? { level } : {}), line_start: lineStart,+ line_end: Math.min(bounds[k + 1] ? await lineAt(stop) - 1 : totalLines, totalLines), byte_start: start, byte_end: stop, ...range.fields(),+ });+ }+ return { kind: 'headings', entries, total_entries: total, from_index: from, ...(from + entries.length < total ? { next_from_index: from + entries.length } : {}) };+}++/** Whether the read view holds only whitespace before byte `b` (a large segment before it is taken as text after two reads). */+async function blankBefore(doc: SegmentedDocument, b: number): Promise<boolean> {+ const last = doc.unitAt(b);+ let reads = 0;+ for (let i = 0; i <= last; i++) {+ const u = doc.units[i]!;+ const upTo = Math.min(u.bytes, b - u.start);+ if (upTo <= 0) continue;+ if (u.row >= 0 && ++reads > 2) return false;+ if ((await doc.readUnit(i)).subarray(0, upTo).toString('utf8').trim()) return false;+ }+ return true;+}++async function blocksOutline(doc: SegmentedDocument, from: number, limit: number, totalLines: number): Promise<PageOutline> {+ const starts: number[] = [];+ for (const u of doc.units) if (u.row >= 0 && u.bytes > 0) starts.push(starts.length ? u.start : 0);+ if (!starts.length && doc.total > 0) starts.push(0);+ const page = starts.slice(from, from + limit);+ const rows = new Set<number>();+ const end = (k: number) => starts[from + k + 1] ?? doc.total;+ page.forEach((start, k) => { for (let i = doc.unitAt(start); i <= doc.unitAt(end(k) - 1); i++) if (doc.units[i]!.row >= 0) rows.add(doc.units[i]!.row); });+ const dates = await storedDates(doc, [...rows]);+ const entries: OutlineEntry[] = page.map((start, k) => {+ const stop = end(k);+ const range = new DateRange();+ for (let i = doc.unitAt(start); i <= doc.unitAt(stop - 1); i++) {+ const u = doc.units[i]!;+ if (u.row < 0) range.scan(u.text!);+ else { const d = dates.get(u.row); if (d) range.add(d.min, d.max); }+ }+ const lineStart = 1 + (start === 0 ? 0 : doc.linesBefore(doc.unitAt(start)));+ const lineEnd = stop === doc.total ? totalLines : Math.max(lineStart, doc.linesBefore(doc.unitAt(stop)));+ return { line_start: lineStart, line_end: Math.min(lineEnd, totalLines), byte_start: start, byte_end: stop, ...range.fields() };+ });+ return { kind: 'blocks', entries, total_entries: starts.length, from_index: from, ...(from + entries.length < starts.length ? { next_from_index: from + entries.length } : {}) };+}diff --git a/src/core/page-window/window.ts b/src/core/page-window/window.tsindex c47ca4d0a6..c07c568247 100644--- a/src/core/page-window/window.ts+++ b/src/core/page-window/window.ts@@ -113,6 +113,15 @@ export function sliceWindow(buf: Buffer, start: number, end: number, forced = fa};}+/** A stretch of a document too large to hold (a segmented page): its bytes from document byte `start`, and the newlines before it. */+export interface DocumentSlab { bytes: Buffer; start: number; linesBefore: number }++/** A window `cut` from the slab's bytes, in document offsets and line numbers. */+export function slabWindow(slab: DocumentSlab, cut: (buf: Buffer) => WindowSlice): WindowSlice {+ const w = cut(slab.bytes);+ return { ...w, byte_start: w.byte_start + slab.start, byte_end: w.byte_end + slab.start, line_start: w.line_start + slab.linesBefore, line_end: w.line_end + slab.linesBefore };+}+/** A window from a clean boundary (a cursor position or the document start). */export function windowFrom(buf: Buffer, offset: number, maxBytes: number): WindowSlice {const start = snapCodePoint(buf, offset);diff --git a/src/core/persistence/graduation-inventory.ts b/src/core/persistence/graduation-inventory.tsindex 39145907d2..a17d552da1 100644--- a/src/core/persistence/graduation-inventory.ts+++ b/src/core/persistence/graduation-inventory.ts@@ -188,6 +188,7 @@ export const GRADUATION_INVENTORY: Inventory = {entry('query_cache', 'rebuild', 'operational', 'Query result cache; regenerated on the target.'),entry('code_traversal_cache', 'rebuild', 'operational', 'Code traversal cache; regenerated on the target.'),+ entry('page_view_digests', 'rebuild', 'operational', 'get_page view sizes and sha256 of segmented pages per revision; recomputed by the next read on the target.'),entry('planner_stats_deltas', 'discard', 'operational', 'PGLite-only planner accounting.', { engines: { pglite: true, postgres: false } }),entry('planner_stats_state', 'discard', 'operational', 'PGLite-only planner accounting.', { engines: { pglite: true, postgres: false } }),diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.tsindex 1eee44e278..292dafef19 100644--- a/src/core/pglite-schema.generated.ts+++ b/src/core/pglite-schema.generated.ts@@ -1277,6 +1277,17 @@ CREATE TABLE IF NOT EXISTS page_extraction_state ();CREATE INDEX IF NOT EXISTS page_extraction_state_truncated_idxON page_extraction_state (pipeline, page_id) WHERE input_truncated IS NOT NULL;+CREATE TABLE IF NOT EXISTS page_view_digests (+ page_id INTEGER NOT NULL REFERENCES pages(id) ON DELETE CASCADE,+ revision TEXT NOT NULL,+ view TEXT NOT NULL CHECK (view IN ('read','markdown')),+ audience TEXT NOT NULL CHECK (audience IN ('trusted','remote')),+ total_bytes BIGINT NOT NULL CHECK (total_bytes >= 0),+ total_lines BIGINT NOT NULL CHECK (total_lines >= 0),+ sha256 TEXT,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ PRIMARY KEY (page_id, revision, view, audience)+);-- Wave B segmented page storage (migration v248): segment texts, the-- generation-ranged body manifest and body stagings (src/core/page-body/).-- Before the persistence region so the managed-writer guard covers them.diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.tsindex c4cac01d35..17a2481aab 100644--- a/src/core/schema-embedded.generated.ts+++ b/src/core/schema-embedded.generated.ts@@ -2008,6 +2008,19 @@ CREATE TABLE IF NOT EXISTS page_extraction_state ();CREATE INDEX IF NOT EXISTS page_extraction_state_truncated_idxON page_extraction_state (pipeline, page_id) WHERE input_truncated IS NOT NULL;+-- Wave B segmented pages (migration v250): get_page view sizes and digests per+-- page revision and audience (src/core/page-window/segmented.ts).+CREATE TABLE IF NOT EXISTS page_view_digests (+ page_id INTEGER NOT NULL REFERENCES pages(id) ON DELETE CASCADE,+ revision TEXT NOT NULL,+ view TEXT NOT NULL CHECK (view IN ('read','markdown')),+ audience TEXT NOT NULL CHECK (audience IN ('trusted','remote')),+ total_bytes BIGINT NOT NULL CHECK (total_bytes >= 0),+ total_lines BIGINT NOT NULL CHECK (total_lines >= 0),+ sha256 TEXT,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ PRIMARY KEY (page_id, revision, view, audience)+);-- Wave B segmented page storage (migration v248): segment texts, the-- generation-ranged body manifest and body stagings (src/core/page-body/).-- Before the persistence region so the managed-writer guard covers them.diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.tsindex 284286cf7d..a37b519c57 100644--- a/src/core/schema-migrations/latest.generated.ts+++ b/src/core/schema-migrations/latest.generated.ts@@ -4,4 +4,4 @@// The highest schema migration version (migrate.ts LATEST_VERSION), importable without// loading the migrations themselves.-export const LATEST_SCHEMA_VERSION = 248;+export const LATEST_SCHEMA_VERSION = 250;diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex 6c14de5c01..56d12ea40b 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -249,6 +249,7 @@ import { v245 } from './v245-page-search-vector-bounded-timeline.ts';import { v246 } from './v246-page-embedding-budget.ts';import { v247 } from './v247-page-extraction-state.ts';import { v248 } from './v248-segmented-page-storage.ts';+import { v250 } from './v250-page-view-digests.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -496,4 +497,5 @@ export const MIGRATIONS: Migration[] = [v246,v247,v248,+ v250,];diff --git a/src/core/schema-migrations/v250-page-view-digests.ts b/src/core/schema-migrations/v250-page-view-digests.tsnew file mode 100644index 0000000000..e75090e9bd--- /dev/null+++ b/src/core/schema-migrations/v250-page-view-digests.ts@@ -0,0 +1,31 @@+import type { Migration } from './types.ts';++// Applied by src/core/migrate.ts on the next initSchema(); the fresh-install+// copy in src/schema.sql carries the same table.+//+// Wave B segmented pages (src/core/page-window/segmented.ts): the size and+// sha256 of a get_page view of a segmented page, per page revision, view+// ('read' line count; 'markdown' total bytes, lines and sha256) and audience,+// so paging a large page's markdown to its end streams it once instead of+// once per window. Sizes and hashes only: no page text is stored. A row is a+// cache: it is used only while its byte total matches the page's stored sums,+// rows of older revisions are dropped when a new one is written, and rows go+// with their page (ON DELETE CASCADE). DDL only, nothing to backfill.+export const v250: Migration = {+ version: 250,+ name: 'page_view_digests',+ idempotent: true,+ sql: `+ CREATE TABLE IF NOT EXISTS page_view_digests (+ page_id INTEGER NOT NULL REFERENCES pages(id) ON DELETE CASCADE,+ revision TEXT NOT NULL,+ view TEXT NOT NULL CHECK (view IN ('read','markdown')),+ audience TEXT NOT NULL CHECK (audience IN ('trusted','remote')),+ total_bytes BIGINT NOT NULL CHECK (total_bytes >= 0),+ total_lines BIGINT NOT NULL CHECK (total_lines >= 0),+ sha256 TEXT,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ PRIMARY KEY (page_id, revision, view, audience)+ );+ `,+};diff --git a/src/schema.sql b/src/schema.sqlindex 8fdcf388f2..aa78810dff 100644--- a/src/schema.sql+++ b/src/schema.sql@@ -2004,6 +2004,19 @@ CREATE TABLE IF NOT EXISTS page_extraction_state ();CREATE INDEX IF NOT EXISTS page_extraction_state_truncated_idxON page_extraction_state (pipeline, page_id) WHERE input_truncated IS NOT NULL;+-- Wave B segmented pages (migration v250): get_page view sizes and digests per+-- page revision and audience (src/core/page-window/segmented.ts).+CREATE TABLE IF NOT EXISTS page_view_digests (+ page_id INTEGER NOT NULL REFERENCES pages(id) ON DELETE CASCADE,+ revision TEXT NOT NULL,+ view TEXT NOT NULL CHECK (view IN ('read','markdown')),+ audience TEXT NOT NULL CHECK (audience IN ('trusted','remote')),+ total_bytes BIGINT NOT NULL CHECK (total_bytes >= 0),+ total_lines BIGINT NOT NULL CHECK (total_lines >= 0),+ sha256 TEXT,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ PRIMARY KEY (page_id, revision, view, audience)+);-- Wave B segmented page storage (migration v248): segment texts, the-- generation-ranged body manifest and body stagings (src/core/page-body/).-- Before the persistence region so the managed-writer guard covers them.diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.jsonindex 82f1cbcc57..ee0ab23f4d 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json@@ -256,6 +256,12 @@"page_versions.page_versions_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_versions.page_versions_pkey": "p PRIMARY KEY (id)","page_versions.page_versions_trust_tier_check": "c CHECK (((trust_tier IS NULL) OR (trust_tier = ANY (ARRAY['user_confirmed'::text, 'operator_curated'::text, 'tool_observed'::text, 'agent_written'::text, 'unknown'::text, 'external_untrusted'::text]))))",+ "page_view_digests.page_view_digests_audience_check": "c CHECK ((audience = ANY (ARRAY['trusted'::text, 'remote'::text])))",+ "page_view_digests.page_view_digests_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",+ "page_view_digests.page_view_digests_pkey": "p PRIMARY KEY (page_id, revision, view, audience)",+ "page_view_digests.page_view_digests_total_bytes_check": "c CHECK ((total_bytes >= 0))",+ "page_view_digests.page_view_digests_total_lines_check": "c CHECK ((total_lines >= 0))",+ "page_view_digests.page_view_digests_view_check": "c CHECK ((view = ANY (ARRAY['read'::text, 'markdown'::text])))","page_write_guards.page_write_guards_pkey": "p PRIMARY KEY (source_incarnation, slug)","page_write_guards.page_write_guards_source_incarnation_fkey": "f FOREIGN KEY (source_incarnation) REFERENCES sources(incarnation) ON DELETE CASCADE","pages.pages_body_storage_chk": "c CHECK ((((body_storage = 'inline'::text) AND (compiled_truth IS NOT NULL) AND (timeline IS NOT NULL) AND (truth_lead IS NULL)) OR ((body_storage = 'segmented'::text) AND (compiled_truth IS NULL) AND (timeline IS NULL) AND (body_bytes IS NOT NULL))))",@@ -753,6 +759,9 @@"page_versions": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "page_view_digests": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"page_write_guards": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -1212,6 +1221,7 @@"page_retrievals_pkey": "CREATE UNIQUE INDEX page_retrievals_pkey ON public.page_retrievals USING btree (page_id)","page_segment_texts_pkey": "CREATE UNIQUE INDEX page_segment_texts_pkey ON public.page_segment_texts USING btree (source_id, sha256)","page_versions_pkey": "CREATE UNIQUE INDEX page_versions_pkey ON public.page_versions USING btree (id)",+ "page_view_digests_pkey": "CREATE UNIQUE INDEX page_view_digests_pkey ON public.page_view_digests USING btree (page_id, revision, view, audience)","page_write_guards_pkey": "CREATE UNIQUE INDEX page_write_guards_pkey ON public.page_write_guards USING btree (source_incarnation, slug)","pages_atom_source_hash_idx": "CREATE INDEX pages_atom_source_hash_idx ON public.pages USING btree (((frontmatter ->> 'source_hash'::text))) WHERE ((type = 'atom'::text) AND (deleted_at IS NULL))","pages_chunker_version_idx": "CREATE INDEX pages_chunker_version_idx ON public.pages USING btree (chunker_version) WHERE (page_kind = 'markdown'::text)",@@ -2793,6 +2803,19 @@],"flags": "relkind=r rls=false force_rls=false"},+ "page_view_digests": {+ "columns": [+ "1 page_id integer/int4 NOT NULL",+ "2 revision text/text NOT NULL",+ "3 view text/text NOT NULL",+ "4 audience text/text NOT NULL",+ "5 total_bytes bigint/int8 NOT NULL",+ "6 total_lines bigint/int8 NOT NULL",+ "7 sha256 text/text NULL",+ "8 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ ],+ "flags": "relkind=r rls=false force_rls=false"+ },"page_write_guards": {"columns": ["1 source_incarnation uuid/uuid NOT NULL",diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.jsonindex 7c88a44e13..0c35cd2c31 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json@@ -256,6 +256,12 @@"page_versions.page_versions_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_versions.page_versions_pkey": "p PRIMARY KEY (id)","page_versions.page_versions_trust_tier_check": "c CHECK (((trust_tier IS NULL) OR (trust_tier = ANY (ARRAY['user_confirmed'::text, 'operator_curated'::text, 'tool_observed'::text, 'agent_written'::text, 'unknown'::text, 'external_untrusted'::text]))))",+ "page_view_digests.page_view_digests_audience_check": "c CHECK ((audience = ANY (ARRAY['trusted'::text, 'remote'::text])))",+ "page_view_digests.page_view_digests_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",+ "page_view_digests.page_view_digests_pkey": "p PRIMARY KEY (page_id, revision, view, audience)",+ "page_view_digests.page_view_digests_total_bytes_check": "c CHECK ((total_bytes >= 0))",+ "page_view_digests.page_view_digests_total_lines_check": "c CHECK ((total_lines >= 0))",+ "page_view_digests.page_view_digests_view_check": "c CHECK ((view = ANY (ARRAY['read'::text, 'markdown'::text])))","page_write_guards.page_write_guards_pkey": "p PRIMARY KEY (source_incarnation, slug)","page_write_guards.page_write_guards_source_incarnation_fkey": "f FOREIGN KEY (source_incarnation) REFERENCES sources(incarnation) ON DELETE CASCADE","pages.pages_body_storage_chk": "c CHECK ((((body_storage = 'inline'::text) AND (compiled_truth IS NOT NULL) AND (timeline IS NOT NULL) AND (truth_lead IS NULL)) OR ((body_storage = 'segmented'::text) AND (compiled_truth IS NULL) AND (timeline IS NULL) AND (body_bytes IS NOT NULL))))",@@ -753,6 +759,9 @@"page_versions": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "page_view_digests": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"page_write_guards": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -1212,6 +1221,7 @@"page_retrievals_pkey": "CREATE UNIQUE INDEX page_retrievals_pkey ON public.page_retrievals USING btree (page_id)","page_segment_texts_pkey": "CREATE UNIQUE INDEX page_segment_texts_pkey ON public.page_segment_texts USING btree (source_id, sha256)","page_versions_pkey": "CREATE UNIQUE INDEX page_versions_pkey ON public.page_versions USING btree (id)",+ "page_view_digests_pkey": "CREATE UNIQUE INDEX page_view_digests_pkey ON public.page_view_digests USING btree (page_id, revision, view, audience)","page_write_guards_pkey": "CREATE UNIQUE INDEX page_write_guards_pkey ON public.page_write_guards USING btree (source_incarnation, slug)","pages_atom_source_hash_idx": "CREATE INDEX pages_atom_source_hash_idx ON public.pages USING btree (((frontmatter ->> 'source_hash'::text))) WHERE ((type = 'atom'::text) AND (deleted_at IS NULL))","pages_chunker_version_idx": "CREATE INDEX pages_chunker_version_idx ON public.pages USING btree (chunker_version) WHERE (page_kind = 'markdown'::text)",@@ -2793,6 +2803,19 @@],"flags": "relkind=r rls=false force_rls=false"},+ "page_view_digests": {+ "columns": [+ "1 page_id integer/int4 NOT NULL",+ "2 revision text/text NOT NULL",+ "3 view text/text NOT NULL",+ "4 audience text/text NOT NULL",+ "5 total_bytes bigint/int8 NOT NULL",+ "6 total_lines bigint/int8 NOT NULL",+ "7 sha256 text/text NULL",+ "8 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ ],+ "flags": "relkind=r rls=false force_rls=false"+ },"page_write_guards": {"columns": ["1 source_incarnation uuid/uuid NOT NULL",diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.jsonindex 603bf7eecf..1e0aa8753f 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json@@ -256,6 +256,12 @@"page_versions.page_versions_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_versions.page_versions_pkey": "p PRIMARY KEY (id)","page_versions.page_versions_trust_tier_check": "c CHECK (((trust_tier IS NULL) OR (trust_tier = ANY (ARRAY['user_confirmed'::text, 'operator_curated'::text, 'tool_observed'::text, 'agent_written'::text, 'unknown'::text, 'external_untrusted'::text]))))",+ "page_view_digests.page_view_digests_audience_check": "c CHECK ((audience = ANY (ARRAY['trusted'::text, 'remote'::text])))",+ "page_view_digests.page_view_digests_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",+ "page_view_digests.page_view_digests_pkey": "p PRIMARY KEY (page_id, revision, view, audience)",+ "page_view_digests.page_view_digests_total_bytes_check": "c CHECK ((total_bytes >= 0))",+ "page_view_digests.page_view_digests_total_lines_check": "c CHECK ((total_lines >= 0))",+ "page_view_digests.page_view_digests_view_check": "c CHECK ((view = ANY (ARRAY['read'::text, 'markdown'::text])))","page_write_guards.page_write_guards_pkey": "p PRIMARY KEY (source_incarnation, slug)","page_write_guards.page_write_guards_source_incarnation_fkey": "f FOREIGN KEY (source_incarnation) REFERENCES sources(incarnation) ON DELETE CASCADE","pages.pages_body_storage_chk": "c CHECK ((((body_storage = 'inline'::text) AND (compiled_truth IS NOT NULL) AND (timeline IS NOT NULL) AND (truth_lead IS NULL)) OR ((body_storage = 'segmented'::text) AND (compiled_truth IS NULL) AND (timeline IS NULL) AND (body_bytes IS NOT NULL))))",@@ -753,6 +759,9 @@"page_versions": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "page_view_digests": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"page_write_guards": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -1208,6 +1217,7 @@"page_retrievals_pkey": "CREATE UNIQUE INDEX page_retrievals_pkey ON public.page_retrievals USING btree (page_id)","page_segment_texts_pkey": "CREATE UNIQUE INDEX page_segment_texts_pkey ON public.page_segment_texts USING btree (source_id, sha256)","page_versions_pkey": "CREATE UNIQUE INDEX page_versions_pkey ON public.page_versions USING btree (id)",+ "page_view_digests_pkey": "CREATE UNIQUE INDEX page_view_digests_pkey ON public.page_view_digests USING btree (page_id, revision, view, audience)","page_write_guards_pkey": "CREATE UNIQUE INDEX page_write_guards_pkey ON public.page_write_guards USING btree (source_incarnation, slug)","pages_atom_source_hash_idx": "CREATE INDEX pages_atom_source_hash_idx ON public.pages USING btree (((frontmatter ->> 'source_hash'::text))) WHERE ((type = 'atom'::text) AND (deleted_at IS NULL))","pages_chunker_version_idx": "CREATE INDEX pages_chunker_version_idx ON public.pages USING btree (chunker_version) WHERE (page_kind = 'markdown'::text)",@@ -2789,6 +2799,19 @@],"flags": "relkind=r rls=false force_rls=false"},+ "page_view_digests": {+ "columns": [+ "1 page_id integer/int4 NOT NULL",+ "2 revision text/text NOT NULL",+ "3 view text/text NOT NULL",+ "4 audience text/text NOT NULL",+ "5 total_bytes bigint/int8 NOT NULL",+ "6 total_lines bigint/int8 NOT NULL",+ "7 sha256 text/text NULL",+ "8 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ ],+ "flags": "relkind=r rls=false force_rls=false"+ },"page_write_guards": {"columns": ["1 source_incarnation uuid/uuid NOT NULL",diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json b/test/fixtures/goldens/catalog/pglite-schema-blob-default.jsonindex 8d2632c7ad..83401c7a12 100644--- a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json@@ -182,6 +182,12 @@"page_segment_texts.page_segment_texts_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","page_versions.page_versions_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_versions.page_versions_pkey": "p PRIMARY KEY (id)",+ "page_view_digests.page_view_digests_audience_check": "c CHECK ((audience = ANY (ARRAY['trusted'::text, 'remote'::text])))",+ "page_view_digests.page_view_digests_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",+ "page_view_digests.page_view_digests_pkey": "p PRIMARY KEY (page_id, revision, view, audience)",+ "page_view_digests.page_view_digests_total_bytes_check": "c CHECK ((total_bytes >= 0))",+ "page_view_digests.page_view_digests_total_lines_check": "c CHECK ((total_lines >= 0))",+ "page_view_digests.page_view_digests_view_check": "c CHECK ((view = ANY (ARRAY['read'::text, 'markdown'::text])))","page_write_guards.page_write_guards_pkey": "p PRIMARY KEY (source_incarnation, slug)","page_write_guards.page_write_guards_source_incarnation_fkey": "f FOREIGN KEY (source_incarnation) REFERENCES sources(incarnation) ON DELETE CASCADE","pages.pages_page_kind_check": "c CHECK ((page_kind = ANY (ARRAY['markdown'::text, 'code'::text, 'image'::text])))",@@ -550,6 +556,9 @@"page_versions": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "page_view_digests": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"page_write_guards": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -880,6 +889,7 @@"page_retrievals_pkey": "CREATE UNIQUE INDEX page_retrievals_pkey ON public.page_retrievals USING btree (page_id)","page_segment_texts_pkey": "CREATE UNIQUE INDEX page_segment_texts_pkey ON public.page_segment_texts USING btree (source_id, sha256)","page_versions_pkey": "CREATE UNIQUE INDEX page_versions_pkey ON public.page_versions USING btree (id)",+ "page_view_digests_pkey": "CREATE UNIQUE INDEX page_view_digests_pkey ON public.page_view_digests USING btree (page_id, revision, view, audience)","page_write_guards_pkey": "CREATE UNIQUE INDEX page_write_guards_pkey ON public.page_write_guards USING btree (source_incarnation, slug)","pages_coalesce_date_idx": "CREATE INDEX pages_coalesce_date_idx ON public.pages USING btree (COALESCE(effective_date, updated_at))","pages_deleted_at_purge_idx": "CREATE INDEX pages_deleted_at_purge_idx ON public.pages USING btree (deleted_at) WHERE (deleted_at IS NOT NULL)",@@ -2061,6 +2071,19 @@],"flags": "relkind=r rls=false force_rls=false"},+ "page_view_digests": {+ "columns": [+ "1 page_id integer/int4 NOT NULL",+ "2 revision text/text NOT NULL",+ "3 view text/text NOT NULL",+ "4 audience text/text NOT NULL",+ "5 total_bytes bigint/int8 NOT NULL",+ "6 total_lines bigint/int8 NOT NULL",+ "7 sha256 text/text NULL",+ "8 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ ],+ "flags": "relkind=r rls=false force_rls=false"+ },"page_write_guards": {"columns": ["1 source_incarnation uuid/uuid NOT NULL",diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.jsonindex 72e67ec6f9..bcf77c9d5f 100644--- a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json@@ -182,6 +182,12 @@"page_segment_texts.page_segment_texts_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","page_versions.page_versions_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_versions.page_versions_pkey": "p PRIMARY KEY (id)",+ "page_view_digests.page_view_digests_audience_check": "c CHECK ((audience = ANY (ARRAY['trusted'::text, 'remote'::text])))",+ "page_view_digests.page_view_digests_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",+ "page_view_digests.page_view_digests_pkey": "p PRIMARY KEY (page_id, revision, view, audience)",+ "page_view_digests.page_view_digests_total_bytes_check": "c CHECK ((total_bytes >= 0))",+ "page_view_digests.page_view_digests_total_lines_check": "c CHECK ((total_lines >= 0))",+ "page_view_digests.page_view_digests_view_check": "c CHECK ((view = ANY (ARRAY['read'::text, 'markdown'::text])))","page_write_guards.page_write_guards_pkey": "p PRIMARY KEY (source_incarnation, slug)","page_write_guards.page_write_guards_source_incarnation_fkey": "f FOREIGN KEY (source_incarnation) REFERENCES sources(incarnation) ON DELETE CASCADE","pages.pages_page_kind_check": "c CHECK ((page_kind = ANY (ARRAY['markdown'::text, 'code'::text, 'image'::text])))",@@ -550,6 +556,9 @@"page_versions": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "page_view_digests": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"page_write_guards": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -880,6 +889,7 @@"page_retrievals_pkey": "CREATE UNIQUE INDEX page_retrievals_pkey ON public.page_retrievals USING btree (page_id)","page_segment_texts_pkey": "CREATE UNIQUE INDEX page_segment_texts_pkey ON public.page_segment_texts USING btree (source_id, sha256)","page_versions_pkey": "CREATE UNIQUE INDEX page_versions_pkey ON public.page_versions USING btree (id)",+ "page_view_digests_pkey": "CREATE UNIQUE INDEX page_view_digests_pkey ON public.page_view_digests USING btree (page_id, revision, view, audience)","page_write_guards_pkey": "CREATE UNIQUE INDEX page_write_guards_pkey ON public.page_write_guards USING btree (source_incarnation, slug)","pages_coalesce_date_idx": "CREATE INDEX pages_coalesce_date_idx ON public.pages USING btree (COALESCE(effective_date, updated_at))","pages_deleted_at_purge_idx": "CREATE INDEX pages_deleted_at_purge_idx ON public.pages USING btree (deleted_at) WHERE (deleted_at IS NOT NULL)",@@ -2061,6 +2071,19 @@],"flags": "relkind=r rls=false force_rls=false"},+ "page_view_digests": {+ "columns": [+ "1 page_id integer/int4 NOT NULL",+ "2 revision text/text NOT NULL",+ "3 view text/text NOT NULL",+ "4 audience text/text NOT NULL",+ "5 total_bytes bigint/int8 NOT NULL",+ "6 total_lines bigint/int8 NOT NULL",+ "7 sha256 text/text NULL",+ "8 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ ],+ "flags": "relkind=r rls=false force_rls=false"+ },"page_write_guards": {"columns": ["1 source_incarnation uuid/uuid NOT NULL",diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.jsonindex 2b6cef901e..29e0418b17 100644--- a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json@@ -182,6 +182,12 @@"page_segment_texts.page_segment_texts_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","page_versions.page_versions_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_versions.page_versions_pkey": "p PRIMARY KEY (id)",+ "page_view_digests.page_view_digests_audience_check": "c CHECK ((audience = ANY (ARRAY['trusted'::text, 'remote'::text])))",+ "page_view_digests.page_view_digests_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",+ "page_view_digests.page_view_digests_pkey": "p PRIMARY KEY (page_id, revision, view, audience)",+ "page_view_digests.page_view_digests_total_bytes_check": "c CHECK ((total_bytes >= 0))",+ "page_view_digests.page_view_digests_total_lines_check": "c CHECK ((total_lines >= 0))",+ "page_view_digests.page_view_digests_view_check": "c CHECK ((view = ANY (ARRAY['read'::text, 'markdown'::text])))","page_write_guards.page_write_guards_pkey": "p PRIMARY KEY (source_incarnation, slug)","page_write_guards.page_write_guards_source_incarnation_fkey": "f FOREIGN KEY (source_incarnation) REFERENCES sources(incarnation) ON DELETE CASCADE","pages.pages_page_kind_check": "c CHECK ((page_kind = ANY (ARRAY['markdown'::text, 'code'::text, 'image'::text])))",@@ -550,6 +556,9 @@"page_versions": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "page_view_digests": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"page_write_guards": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -879,6 +888,7 @@"page_retrievals_pkey": "CREATE UNIQUE INDEX page_retrievals_pkey ON public.page_retrievals USING btree (page_id)","page_segment_texts_pkey": "CREATE UNIQUE INDEX page_segment_texts_pkey ON public.page_segment_texts USING btree (source_id, sha256)","page_versions_pkey": "CREATE UNIQUE INDEX page_versions_pkey ON public.page_versions USING btree (id)",+ "page_view_digests_pkey": "CREATE UNIQUE INDEX page_view_digests_pkey ON public.page_view_digests USING btree (page_id, revision, view, audience)","page_write_guards_pkey": "CREATE UNIQUE INDEX page_write_guards_pkey ON public.page_write_guards USING btree (source_incarnation, slug)","pages_coalesce_date_idx": "CREATE INDEX pages_coalesce_date_idx ON public.pages USING btree (COALESCE(effective_date, updated_at))","pages_deleted_at_purge_idx": "CREATE INDEX pages_deleted_at_purge_idx ON public.pages USING btree (deleted_at) WHERE (deleted_at IS NOT NULL)",@@ -2060,6 +2070,19 @@],"flags": "relkind=r rls=false force_rls=false"},+ "page_view_digests": {+ "columns": [+ "1 page_id integer/int4 NOT NULL",+ "2 revision text/text NOT NULL",+ "3 view text/text NOT NULL",+ "4 audience text/text NOT NULL",+ "5 total_bytes bigint/int8 NOT NULL",+ "6 total_lines bigint/int8 NOT NULL",+ "7 sha256 text/text NULL",+ "8 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ ],+ "flags": "relkind=r rls=false force_rls=false"+ },"page_write_guards": {"columns": ["1 source_incarnation uuid/uuid NOT NULL",diff --git a/test/fixtures/goldens/catalog/postgres-db-initschema.json b/test/fixtures/goldens/catalog/postgres-db-initschema.jsonindex f01ff56d91..53dfba0d3c 100644--- a/test/fixtures/goldens/catalog/postgres-db-initschema.json+++ b/test/fixtures/goldens/catalog/postgres-db-initschema.json@@ -193,6 +193,12 @@"page_segment_texts.page_segment_texts_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","page_versions.page_versions_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_versions.page_versions_pkey": "p PRIMARY KEY (id)",+ "page_view_digests.page_view_digests_audience_check": "c CHECK ((audience = ANY (ARRAY['trusted'::text, 'remote'::text])))",+ "page_view_digests.page_view_digests_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",+ "page_view_digests.page_view_digests_pkey": "p PRIMARY KEY (page_id, revision, view, audience)",+ "page_view_digests.page_view_digests_total_bytes_check": "c CHECK ((total_bytes >= 0))",+ "page_view_digests.page_view_digests_total_lines_check": "c CHECK ((total_lines >= 0))",+ "page_view_digests.page_view_digests_view_check": "c CHECK ((view = ANY (ARRAY['read'::text, 'markdown'::text])))","page_write_guards.page_write_guards_pkey": "p PRIMARY KEY (source_incarnation, slug)","page_write_guards.page_write_guards_source_incarnation_fkey": "f FOREIGN KEY (source_incarnation) REFERENCES sources(incarnation) ON DELETE CASCADE","pages.pages_page_kind_check": "c CHECK ((page_kind = ANY (ARRAY['markdown'::text, 'code'::text, 'image'::text])))",@@ -567,6 +573,9 @@"page_versions": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "page_view_digests": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"page_write_guards": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -908,6 +917,7 @@"page_retrievals_pkey": "CREATE UNIQUE INDEX page_retrievals_pkey ON public.page_retrievals USING btree (page_id)","page_segment_texts_pkey": "CREATE UNIQUE INDEX page_segment_texts_pkey ON public.page_segment_texts USING btree (source_id, sha256)","page_versions_pkey": "CREATE UNIQUE INDEX page_versions_pkey ON public.page_versions USING btree (id)",+ "page_view_digests_pkey": "CREATE UNIQUE INDEX page_view_digests_pkey ON public.page_view_digests USING btree (page_id, revision, view, audience)","page_write_guards_pkey": "CREATE UNIQUE INDEX page_write_guards_pkey ON public.page_write_guards USING btree (source_incarnation, slug)","pages_coalesce_date_idx": "CREATE INDEX pages_coalesce_date_idx ON public.pages USING btree (COALESCE(effective_date, updated_at))","pages_deleted_at_purge_idx": "CREATE INDEX pages_deleted_at_purge_idx ON public.pages USING btree (deleted_at) WHERE (deleted_at IS NOT NULL)",@@ -2130,6 +2140,19 @@],"flags": "relkind=r rls=true force_rls=false"},+ "page_view_digests": {+ "columns": [+ "1 page_id integer/int4 NOT NULL",+ "2 revision text/text NOT NULL",+ "3 view text/text NOT NULL",+ "4 audience text/text NOT NULL",+ "5 total_bytes bigint/int8 NOT NULL",+ "6 total_lines bigint/int8 NOT NULL",+ "7 sha256 text/text NULL",+ "8 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ ],+ "flags": "relkind=r rls=false force_rls=false"+ },"page_write_guards": {"columns": ["1 source_incarnation uuid/uuid NOT NULL",diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.jsonindex 71cee22581..c5a9febfe5 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json@@ -260,6 +260,12 @@"page_versions.page_versions_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_versions.page_versions_pkey": "p PRIMARY KEY (id)","page_versions.page_versions_trust_tier_check": "c CHECK (((trust_tier IS NULL) OR (trust_tier = ANY (ARRAY['user_confirmed'::text, 'operator_curated'::text, 'tool_observed'::text, 'agent_written'::text, 'unknown'::text, 'external_untrusted'::text]))))",+ "page_view_digests.page_view_digests_audience_check": "c CHECK ((audience = ANY (ARRAY['trusted'::text, 'remote'::text])))",+ "page_view_digests.page_view_digests_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",+ "page_view_digests.page_view_digests_pkey": "p PRIMARY KEY (page_id, revision, view, audience)",+ "page_view_digests.page_view_digests_total_bytes_check": "c CHECK ((total_bytes >= 0))",+ "page_view_digests.page_view_digests_total_lines_check": "c CHECK ((total_lines >= 0))",+ "page_view_digests.page_view_digests_view_check": "c CHECK ((view = ANY (ARRAY['read'::text, 'markdown'::text])))","page_write_guards.page_write_guards_pkey": "p PRIMARY KEY (source_incarnation, slug)","page_write_guards.page_write_guards_source_incarnation_fkey": "f FOREIGN KEY (source_incarnation) REFERENCES sources(incarnation) ON DELETE CASCADE","pages.pages_body_storage_chk": "c CHECK ((((body_storage = 'inline'::text) AND (compiled_truth IS NOT NULL) AND (timeline IS NOT NULL) AND (truth_lead IS NULL)) OR ((body_storage = 'segmented'::text) AND (compiled_truth IS NULL) AND (timeline IS NULL) AND (body_bytes IS NOT NULL))))",@@ -760,6 +766,9 @@"page_versions": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "page_view_digests": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"page_write_guards": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -1216,6 +1225,7 @@"page_retrievals_pkey": "CREATE UNIQUE INDEX page_retrievals_pkey ON public.page_retrievals USING btree (page_id)","page_segment_texts_pkey": "CREATE UNIQUE INDEX page_segment_texts_pkey ON public.page_segment_texts USING btree (source_id, sha256)","page_versions_pkey": "CREATE UNIQUE INDEX page_versions_pkey ON public.page_versions USING btree (id)",+ "page_view_digests_pkey": "CREATE UNIQUE INDEX page_view_digests_pkey ON public.page_view_digests USING btree (page_id, revision, view, audience)","page_write_guards_pkey": "CREATE UNIQUE INDEX page_write_guards_pkey ON public.page_write_guards USING btree (source_incarnation, slug)","pages_atom_source_hash_idx": "CREATE INDEX pages_atom_source_hash_idx ON public.pages USING btree (((frontmatter ->> 'source_hash'::text))) WHERE ((type = 'atom'::text) AND (deleted_at IS NULL))","pages_chunker_version_idx": "CREATE INDEX pages_chunker_version_idx ON public.pages USING btree (chunker_version) WHERE (page_kind = 'markdown'::text)",@@ -2805,6 +2815,19 @@],"flags": "relkind=r rls=true force_rls=false"},+ "page_view_digests": {+ "columns": [+ "1 page_id integer/int4 NOT NULL",+ "2 revision text/text NOT NULL",+ "3 view text/text NOT NULL",+ "4 audience text/text NOT NULL",+ "5 total_bytes bigint/int8 NOT NULL",+ "6 total_lines bigint/int8 NOT NULL",+ "7 sha256 text/text NULL",+ "8 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ ],+ "flags": "relkind=r rls=true force_rls=false"+ },"page_write_guards": {"columns": ["1 source_incarnation uuid/uuid NOT NULL",diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.jsonindex 8a70a15c5f..c30910fc21 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json@@ -260,6 +260,12 @@"page_versions.page_versions_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_versions.page_versions_pkey": "p PRIMARY KEY (id)","page_versions.page_versions_trust_tier_check": "c CHECK (((trust_tier IS NULL) OR (trust_tier = ANY (ARRAY['user_confirmed'::text, 'operator_curated'::text, 'tool_observed'::text, 'agent_written'::text, 'unknown'::text, 'external_untrusted'::text]))))",+ "page_view_digests.page_view_digests_audience_check": "c CHECK ((audience = ANY (ARRAY['trusted'::text, 'remote'::text])))",+ "page_view_digests.page_view_digests_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",+ "page_view_digests.page_view_digests_pkey": "p PRIMARY KEY (page_id, revision, view, audience)",+ "page_view_digests.page_view_digests_total_bytes_check": "c CHECK ((total_bytes >= 0))",+ "page_view_digests.page_view_digests_total_lines_check": "c CHECK ((total_lines >= 0))",+ "page_view_digests.page_view_digests_view_check": "c CHECK ((view = ANY (ARRAY['read'::text, 'markdown'::text])))","page_write_guards.page_write_guards_pkey": "p PRIMARY KEY (source_incarnation, slug)","page_write_guards.page_write_guards_source_incarnation_fkey": "f FOREIGN KEY (source_incarnation) REFERENCES sources(incarnation) ON DELETE CASCADE","pages.pages_body_storage_chk": "c CHECK ((((body_storage = 'inline'::text) AND (compiled_truth IS NOT NULL) AND (timeline IS NOT NULL) AND (truth_lead IS NULL)) OR ((body_storage = 'segmented'::text) AND (compiled_truth IS NULL) AND (timeline IS NULL) AND (body_bytes IS NOT NULL))))",@@ -760,6 +766,9 @@"page_versions": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "page_view_digests": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"page_write_guards": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -1216,6 +1225,7 @@"page_retrievals_pkey": "CREATE UNIQUE INDEX page_retrievals_pkey ON public.page_retrievals USING btree (page_id)","page_segment_texts_pkey": "CREATE UNIQUE INDEX page_segment_texts_pkey ON public.page_segment_texts USING btree (source_id, sha256)","page_versions_pkey": "CREATE UNIQUE INDEX page_versions_pkey ON public.page_versions USING btree (id)",+ "page_view_digests_pkey": "CREATE UNIQUE INDEX page_view_digests_pkey ON public.page_view_digests USING btree (page_id, revision, view, audience)","page_write_guards_pkey": "CREATE UNIQUE INDEX page_write_guards_pkey ON public.page_write_guards USING btree (source_incarnation, slug)","pages_atom_source_hash_idx": "CREATE INDEX pages_atom_source_hash_idx ON public.pages USING btree (((frontmatter ->> 'source_hash'::text))) WHERE ((type = 'atom'::text) AND (deleted_at IS NULL))","pages_chunker_version_idx": "CREATE INDEX pages_chunker_version_idx ON public.pages USING btree (chunker_version) WHERE (page_kind = 'markdown'::text)",@@ -2805,6 +2815,19 @@],"flags": "relkind=r rls=true force_rls=false"},+ "page_view_digests": {+ "columns": [+ "1 page_id integer/int4 NOT NULL",+ "2 revision text/text NOT NULL",+ "3 view text/text NOT NULL",+ "4 audience text/text NOT NULL",+ "5 total_bytes bigint/int8 NOT NULL",+ "6 total_lines bigint/int8 NOT NULL",+ "7 sha256 text/text NULL",+ "8 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ ],+ "flags": "relkind=r rls=true force_rls=false"+ },"page_write_guards": {"columns": ["1 source_incarnation uuid/uuid NOT NULL",diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.jsonindex ad3d22f791..d0c1a50014 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json@@ -260,6 +260,12 @@"page_versions.page_versions_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_versions.page_versions_pkey": "p PRIMARY KEY (id)","page_versions.page_versions_trust_tier_check": "c CHECK (((trust_tier IS NULL) OR (trust_tier = ANY (ARRAY['user_confirmed'::text, 'operator_curated'::text, 'tool_observed'::text, 'agent_written'::text, 'unknown'::text, 'external_untrusted'::text]))))",+ "page_view_digests.page_view_digests_audience_check": "c CHECK ((audience = ANY (ARRAY['trusted'::text, 'remote'::text])))",+ "page_view_digests.page_view_digests_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",+ "page_view_digests.page_view_digests_pkey": "p PRIMARY KEY (page_id, revision, view, audience)",+ "page_view_digests.page_view_digests_total_bytes_check": "c CHECK ((total_bytes >= 0))",+ "page_view_digests.page_view_digests_total_lines_check": "c CHECK ((total_lines >= 0))",+ "page_view_digests.page_view_digests_view_check": "c CHECK ((view = ANY (ARRAY['read'::text, 'markdown'::text])))","page_write_guards.page_write_guards_pkey": "p PRIMARY KEY (source_incarnation, slug)","page_write_guards.page_write_guards_source_incarnation_fkey": "f FOREIGN KEY (source_incarnation) REFERENCES sources(incarnation) ON DELETE CASCADE","pages.pages_body_storage_chk": "c CHECK ((((body_storage = 'inline'::text) AND (compiled_truth IS NOT NULL) AND (timeline IS NOT NULL) AND (truth_lead IS NULL)) OR ((body_storage = 'segmented'::text) AND (compiled_truth IS NULL) AND (timeline IS NULL) AND (body_bytes IS NOT NULL))))",@@ -760,6 +766,9 @@"page_versions": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "page_view_digests": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"page_write_guards": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -1212,6 +1221,7 @@"page_retrievals_pkey": "CREATE UNIQUE INDEX page_retrievals_pkey ON public.page_retrievals USING btree (page_id)","page_segment_texts_pkey": "CREATE UNIQUE INDEX page_segment_texts_pkey ON public.page_segment_texts USING btree (source_id, sha256)","page_versions_pkey": "CREATE UNIQUE INDEX page_versions_pkey ON public.page_versions USING btree (id)",+ "page_view_digests_pkey": "CREATE UNIQUE INDEX page_view_digests_pkey ON public.page_view_digests USING btree (page_id, revision, view, audience)","page_write_guards_pkey": "CREATE UNIQUE INDEX page_write_guards_pkey ON public.page_write_guards USING btree (source_incarnation, slug)","pages_atom_source_hash_idx": "CREATE INDEX pages_atom_source_hash_idx ON public.pages USING btree (((frontmatter ->> 'source_hash'::text))) WHERE ((type = 'atom'::text) AND (deleted_at IS NULL))","pages_chunker_version_idx": "CREATE INDEX pages_chunker_version_idx ON public.pages USING btree (chunker_version) WHERE (page_kind = 'markdown'::text)",@@ -2801,6 +2811,19 @@],"flags": "relkind=r rls=true force_rls=false"},+ "page_view_digests": {+ "columns": [+ "1 page_id integer/int4 NOT NULL",+ "2 revision text/text NOT NULL",+ "3 view text/text NOT NULL",+ "4 audience text/text NOT NULL",+ "5 total_bytes bigint/int8 NOT NULL",+ "6 total_lines bigint/int8 NOT NULL",+ "7 sha256 text/text NULL",+ "8 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ ],+ "flags": "relkind=r rls=true force_rls=false"+ },"page_write_guards": {"columns": ["1 source_incarnation uuid/uuid NOT NULL",diff --git a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json b/test/fixtures/goldens/doctor/hot-checks-pglite-json.jsonindex d5176bd7dd..dd4b38e1d9 100644--- a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json+++ b/test/fixtures/goldens/doctor/hot-checks-pglite-json.json@@ -931,7 +931,7 @@{"category": "meta","elapsed_ms": "<volatile>",- "message": "1191 column(s) verified against live schema",+ "message": "1199 column(s) verified against live schema","name": "schema_columns","status": "ok"},@@ -4638,7 +4638,7 @@{"category": "meta","elapsed_ms": "<volatile>",- "message": "1191 column(s) verified against live schema",+ "message": "1199 column(s) verified against live schema","name": "schema_columns","status": "ok"},diff --git a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json b/test/fixtures/goldens/doctor/hot-checks-postgres-json.jsonindex 8863d5a053..4643bd3003 100644--- a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json+++ b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json@@ -913,7 +913,7 @@{"category": "ops","elapsed_ms": "<volatile>",- "message": "RLS enabled on 140/140 public tables",+ "message": "RLS enabled on 141/141 public tables","name": "rls","status": "ok"},@@ -927,7 +927,7 @@{"category": "meta","elapsed_ms": "<volatile>",- "message": "1197 column(s) verified against live schema",+ "message": "1205 column(s) verified against live schema","name": "schema_columns","status": "ok"},@@ -4615,7 +4615,7 @@{"category": "ops","elapsed_ms": "<volatile>",- "message": "RLS enabled on 140/140 public tables",+ "message": "RLS enabled on 141/141 public tables","name": "rls","status": "ok"},@@ -4629,7 +4629,7 @@{"category": "meta","elapsed_ms": "<volatile>",- "message": "1197 column(s) verified against live schema",+ "message": "1205 column(s) verified against live schema","name": "schema_columns","status": "ok"},diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex 86996c12c2..80f54eba1b 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -838,7 +838,7 @@{"category": "meta","elapsed_ms": "<volatile>",- "message": "1191 column(s) verified against live schema",+ "message": "1199 column(s) verified against live schema","name": "schema_columns","status": "ok"},diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex d3c1e9055b..d16882dd72 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -885,7 +885,7 @@{"category": "meta","elapsed_ms": "<volatile>",- "message": "1191 column(s) verified against live schema",+ "message": "1199 column(s) verified against live schema","name": "schema_columns","status": "ok"},diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.jsonindex daf18eb2f1..7d0b4d939d 100644--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json@@ -867,7 +867,7 @@{"category": "ops","elapsed_ms": "<volatile>",- "message": "RLS enabled on 140/140 public tables",+ "message": "RLS enabled on 141/141 public tables","name": "rls","status": "ok"},@@ -881,7 +881,7 @@{"category": "meta","elapsed_ms": "<volatile>",- "message": "1197 column(s) verified against live schema",+ "message": "1205 column(s) verified against live schema","name": "schema_columns","status": "ok"},diff --git a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.jsonindex 9e979ffa19..e2fbc3b86e 100644--- a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json+++ b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json@@ -256,6 +256,12 @@"page_versions.page_versions_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_versions.page_versions_pkey": "p PRIMARY KEY (id)","page_versions.page_versions_trust_tier_check": "c CHECK (((trust_tier IS NULL) OR (trust_tier = ANY (ARRAY['user_confirmed'::text, 'operator_curated'::text, 'tool_observed'::text, 'agent_written'::text, 'unknown'::text, 'external_untrusted'::text]))))",+ "page_view_digests.page_view_digests_audience_check": "c CHECK ((audience = ANY (ARRAY['trusted'::text, 'remote'::text])))",+ "page_view_digests.page_view_digests_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",+ "page_view_digests.page_view_digests_pkey": "p PRIMARY KEY (page_id, revision, view, audience)",+ "page_view_digests.page_view_digests_total_bytes_check": "c CHECK ((total_bytes >= 0))",+ "page_view_digests.page_view_digests_total_lines_check": "c CHECK ((total_lines >= 0))",+ "page_view_digests.page_view_digests_view_check": "c CHECK ((view = ANY (ARRAY['read'::text, 'markdown'::text])))","page_write_guards.page_write_guards_pkey": "p PRIMARY KEY (source_incarnation, slug)","page_write_guards.page_write_guards_source_incarnation_fkey": "f FOREIGN KEY (source_incarnation) REFERENCES sources(incarnation) ON DELETE CASCADE","pages.pages_body_storage_chk": "c CHECK ((((body_storage = 'inline'::text) AND (compiled_truth IS NOT NULL) AND (timeline IS NOT NULL) AND (truth_lead IS NULL)) OR ((body_storage = 'segmented'::text) AND (compiled_truth IS NULL) AND (timeline IS NULL) AND (body_bytes IS NOT NULL))))",@@ -753,6 +759,9 @@"page_versions": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "page_view_digests": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"page_write_guards": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -1212,6 +1221,7 @@"page_retrievals_pkey": "CREATE UNIQUE INDEX page_retrievals_pkey ON public.page_retrievals USING btree (page_id)","page_segment_texts_pkey": "CREATE UNIQUE INDEX page_segment_texts_pkey ON public.page_segment_texts USING btree (source_id, sha256)","page_versions_pkey": "CREATE UNIQUE INDEX page_versions_pkey ON public.page_versions USING btree (id)",+ "page_view_digests_pkey": "CREATE UNIQUE INDEX page_view_digests_pkey ON public.page_view_digests USING btree (page_id, revision, view, audience)","page_write_guards_pkey": "CREATE UNIQUE INDEX page_write_guards_pkey ON public.page_write_guards USING btree (source_incarnation, slug)","pages_atom_source_hash_idx": "CREATE INDEX pages_atom_source_hash_idx ON public.pages USING btree (((frontmatter ->> 'source_hash'::text))) WHERE ((type = 'atom'::text) AND (deleted_at IS NULL))","pages_chunker_version_idx": "CREATE INDEX pages_chunker_version_idx ON public.pages USING btree (chunker_version) WHERE (page_kind = 'markdown'::text)",@@ -2793,6 +2803,19 @@],"flags": "relkind=r rls=false force_rls=false"},+ "page_view_digests": {+ "columns": [+ "1 page_id integer/int4 NOT NULL",+ "2 revision text/text NOT NULL",+ "3 view text/text NOT NULL",+ "4 audience text/text NOT NULL",+ "5 total_bytes bigint/int8 NOT NULL",+ "6 total_lines bigint/int8 NOT NULL",+ "7 sha256 text/text NULL",+ "8 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ ],+ "flags": "relkind=r rls=false force_rls=false"+ },"page_write_guards": {"columns": ["1 source_incarnation uuid/uuid NOT NULL",diff --git a/test/graduation-inventory.test.ts b/test/graduation-inventory.test.tsindex 9c65c39233..22807e6afe 100644--- a/test/graduation-inventory.test.ts+++ b/test/graduation-inventory.test.ts@@ -60,7 +60,7 @@ describe('graduation inventory', () => {expect(new Set(names).size).toBe(names.length);const counts: Record<string, number> = {};for (const e of GRADUATION_INVENTORY.entries) counts[e.class] = (counts[e.class] ?? 0) + 1;- expect(counts).toEqual({ carry: 128, rebind: 2, rebuild: 2, discard: 7, schema_owned: 4 });+ expect(counts).toEqual({ carry: 128, rebind: 2, rebuild: 3, discard: 7, schema_owned: 4 });for (const e of GRADUATION_INVENTORY.entries) {expect({ relation: e.relation, reason: e.reason.length > 5, present: e.engines.pglite || e.engines.postgres }).toEqual({ relation: e.relation, reason: true, present: true });diff --git a/test/large-pages/read-cost.test.ts b/test/large-pages/read-cost.test.tsnew file mode 100644index 0000000000..be7cc48dab--- /dev/null+++ b/test/large-pages/read-cost.test.ts@@ -0,0 +1,129 @@+/**+ * Wave B PR 2 (spec 7.2, 13 "PR 2" tests): a get_page read of a segmented page+ * costs the size of what it returns, not the size of the page.+ *+ * 1. Protects: body: 'none', the first outline page and a 40 KB window in the+ * middle of a 10 MB and a 40 MB page take about the same CPU (median ratio+ * of best-of-runs below 1.3; Wave A's whole-document path is about 4x), and+ * a window reads at most the window plus two segments of segment text.+ * 2. Fails when: a read materializes or projects the whole body (Wave A's+ * readPageDocument / pageOutline over the full text), the line count reads+ * every segment, or a window loads segments it does not cut from.+ * 3. PGLite only: PGLite runs its SQL on the calling thread, so thread CPU+ * counts the database work too.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { operations, type OperationContext } from '../../src/core/operations.ts';+import type { GBrainConfig } from '../../src/core/config.ts';+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { importFromFile } from '../../src/core/import-file.ts';+import { readPageBodyPolicy } from '../../src/core/page-body/limits.ts';+import { cpuMsAsync } from '../helpers/cpu-time.ts';++const getPage = operations.find(o => o.name === 'get_page')!;+const WINDOW = 40_000;+const REPEAT = 20;+let engine: PGLiteEngine;+let dir: string;++/** About `bytes` of a conversation log: a dated heading every ~16 KB, then lines. */+function log(bytes: number): string {+ const parts: string[] = ['---\ntitle: Read cost\ntype: note\n---\n'];+ let size = 0;+ for (let day = 0; size < bytes; day++) {+ const head = `## Day ${day} 2024-${String(1 + (day % 12)).padStart(2, '0')}-${String(1 + (day % 28)).padStart(2, '0')}\n\n`;+ parts.push(head);+ size += head.length;+ for (let i = 0; i < 160; i++) {+ const line = `- ${day}.${i} alice-example asked acme-example about the widget plan and the shipping date\n`;+ parts.push(line);+ size += line.length;+ }+ }+ return parts.join('');+}++const remote = (): OperationContext => ({ engine, config: {} as GBrainConfig, logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote: true,+ transport: 'http', sourceId: 'default', auth: { token: 'fixture', clientId: 'read-cost', principal: { kind: 'oauth_client', id: 'read-cost' }, scopes: ['read'],+ sourceId: 'default', allowedSources: ['default'] } } as unknown as OperationContext);+const get = async (params: Record<string, unknown>) => await getPage.handler(remote(), params) as Record<string, any>;++/** cpuScalingRatio for async spans: median over rounds of best-of-runs large / best-of-runs small, after a warm-up of each. */+async function asyncScalingRatio(small: () => Promise<unknown>, large: () => Promise<unknown>, rounds = 5, runs = 3): Promise<number> {+ await small();+ await large();+ const best = async (fn: () => Promise<unknown>) => {+ let ms = Infinity;+ for (let k = 0; k < runs; k++) ms = Math.min(ms, await cpuMsAsync(fn));+ return ms;+ };+ const ratios: number[] = [];+ for (let r = 0; r < rounds; r++) ratios.push(await best(large) / await best(small));+ return ratios.sort((a, b) => a - b)[Math.floor(rounds / 2)]!;+}++describe('segmented get_page read cost', () => {+ const pages = { small: { slug: 'logs/read-cost-10mb', bytes: 10_000_000, size: 0 }, large: { slug: 'logs/read-cost-40mb', bytes: 40_000_000, size: 0 } };++ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await engine.setConfig('pages.segmented_storage', 'on');+ dir = mkdtempSync(join(tmpdir(), 'gb-read-cost-'));+ for (const page of Object.values(pages)) {+ // The 40 MB page is over the single-string ceiling: it streams in from a file.+ const file = join(dir, 'page.md');+ writeFileSync(file, log(page.bytes));+ expect((await importFromFile(engine, file, `${page.slug}.md`, { noEmbed: true, bodyPolicy: await readPageBodyPolicy(engine) })).status).toBe('imported');+ const none = await get({ slug: page.slug, body: 'none' });+ expect(none.body_storage).toBe('segmented');+ page.size = none.size.total_bytes;+ }+ }, 600_000);++ afterAll(async () => {+ await engine.disconnect();+ rmSync(dir, { recursive: true, force: true });+ });++ const reads: Array<[string, (slug: string, size: number) => Record<string, unknown>]> = [+ ['body none', () => ({ body: 'none' })],+ ['the first outline page', () => ({ body: 'outline' })],+ ['a window in the middle', (_slug, size) => ({ body: 'window', bytes: { offset: Math.floor(size / 2), length: WINDOW } })],+ ];+ for (const [name, params] of reads) {+ test(`${name}: 40 MB costs about what 10 MB costs`, async () => {+ // Thread CPU ticks at a few ms, so one sample is REPEAT reads.+ const read = (page: typeof pages.small) => async () => { for (let i = 0; i < REPEAT; i++) await get({ slug: page.slug, ...params(page.slug, page.size) }); };+ const ratio = await asyncScalingRatio(read(pages.small), read(pages.large));+ expect(ratio).toBeLessThan(1.3);+ }, 300_000);+ }++ test('a window reads at most the window plus two segments of segment text', async () => {+ const [largest] = await engine.executeRaw<{ n: unknown }>(`SELECT max(m.byte_len) AS n FROM page_body_manifest m JOIN pages p ON p.id = m.page_id WHERE p.slug = $1`, [pages.large.slug]);+ const segment = Number(largest!.n);+ const original = engine.readSegmentTexts.bind(engine);+ let bytes = 0;+ engine.readSegmentTexts = async (sourceId, hashes) => {+ const texts = await original(sourceId, hashes);+ for (const text of texts.values()) bytes += text.byteLength;+ return texts;+ };+ try {+ for (const at of [0.1, 0.5, 0.97]) {+ await get({ slug: pages.large.slug, body: 'none' });+ bytes = 0;+ const r = await get({ slug: pages.large.slug, body: 'window', bytes: { offset: Math.floor(pages.large.size * at), length: WINDOW } });+ expect(Buffer.byteLength(r.window.text)).toBeGreaterThan(WINDOW / 2);+ expect(bytes).toBeLessThanOrEqual(WINDOW + 2 * segment);+ }+ } finally {+ engine.readSegmentTexts = original;+ }+ }, 120_000);+});diff --git a/test/large-pages/remote-get-page-privacy.test.ts b/test/large-pages/remote-get-page-privacy.test.tsnew file mode 100644index 0000000000..fb2c3525ce--- /dev/null+++ b/test/large-pages/remote-get-page-privacy.test.ts@@ -0,0 +1,123 @@+/**+ * Wave B PR 2 (spec 7.2, read-privacy 1): get_page over a segmented page shows a+ * remote caller nothing the whole-body read projection hides.+ *+ * 1. Protects: every remote get_page shape of a segmented page (body none, auto,+ * every outline page, windows by bytes and lines, a cursor walk to the end,+ * view: 'markdown' paged to its end) over pages seeded with takes, private+ * facts rows, private keys, ledger rows and a takes block left open to EOF.+ * The paged markdown view must hash to the advertised size.sha256, and the+ * remote tail digest is withheld when the tail rows hold a protected region.+ * 2. Fails when: a segmented window, outline or markdown page is cut from the+ * stored body instead of the read projection, the markdown digest hashes+ * trusted text, or tail_sha256 hashes hidden text. PUBLIC tokens must still+ * appear.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { createHash } from 'node:crypto';+import type { BrainEngine } from '../../src/core/engine.ts';+import type { GBrainConfig } from '../../src/core/config.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { operations, type OperationContext } from '../../src/core/operations.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { testBackends } from '../helpers/test-backends.ts';+import { mulberry32 } from '../helpers/seeded-random.ts';+import { PRIVATE, PUBLIC, crossingFacts, importSegmented, pageContent, privacyText, privateTokensIn, seedLedger } from '../helpers/segmented-privacy-fixture.ts';++const getPage = operations.find(o => o.name === 'get_page')!;+let engine: BrainEngine;++const ctx = (remote: boolean): OperationContext => ({ engine, config: {} as GBrainConfig, logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote,+ sourceId: 'default', ...(remote ? { transport: 'http', auth: { token: 'fixture', clientId: 'privacy-client', principal: { kind: 'oauth_client', id: 'privacy-client' },+ scopes: ['read'], sourceId: 'default', allowedSources: ['default'] } } : {}) } as unknown as OperationContext);+const get = async (params: Record<string, unknown>, remote = true) => await getPage.handler(ctx(remote), params) as Record<string, any>;++/** Every remote get_page shape of `slug`: none may hold a private token, and the windows together show every public one. */+async function expectNoLeak(slug: string, ledger = false): Promise<Record<string, any>> {+ const responses: Array<Record<string, any>> = [];+ const windowTexts: string[] = [];+ const none = await get({ slug, body: 'none' });+ expect(none.body_storage).toBe('segmented');+ responses.push(none, await get({ slug }));+ for (let from: number | undefined = 0; from !== undefined;) {+ const r = await get({ slug, body: 'outline', outline_from: from });+ responses.push(r);+ from = r.outline.next_from_index;+ }+ const total = Number(none.size.total_bytes);+ for (const at of [0, 0.13, 0.5, 0.77, 0.99]) responses.push(await get({ slug, body: 'window', bytes: { offset: Math.floor(total * at), length: 30_000 } }));+ for (const from of [1, 2_000, 9_000, 20_000]) responses.push(await get({ slug, body: 'window', lines: { from, count: 300 } }));+ for (const view of ['read', 'markdown'] as const) {+ let r = await get({ slug, body: 'window', view, max_bytes: 250_000 });+ const parts: string[] = [r.window.text];+ responses.push(r);+ while (r.next_cursor) {+ r = await get({ slug, view, cursor: r.next_cursor });+ parts.push(r.window.text);+ responses.push(r);+ }+ const whole = parts.join('');+ windowTexts.push(whole);+ if (view === 'markdown') {+ expect(Buffer.byteLength(whole)).toBe(r.size.total_bytes);+ expect(createHash('sha256').update(whole).digest('hex')).toBe(r.size.sha256);+ } else {+ expect(Buffer.byteLength(whole)).toBe(total);+ }+ }+ for (const [i, r] of responses.entries()) expect({ i, leaked: privateTokensIn(JSON.stringify(r), { ledger }) }).toEqual({ i, leaked: [] });+ for (const text of windowTexts) for (const token of Object.values(PUBLIC)) expect(text).toContain(token);+ return none;+}++for (const kind of testBackends()) {+ describe(`remote get_page of a segmented page (${kind})`, () => {+ let close: () => Promise<void>;++ beforeAll(async () => {+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ close = () => engine.disconnect();+ }+ }, 120_000);++ afterAll(async () => { await close(); });++ beforeEach(async () => {+ for (const table of ['pages', 'fact_withdrawals', 'fact_purges', 'write_gate_holds']) await engine.executeRaw(`DELETE FROM ${table}`);+ });++ test('none, auto, outline pages, windows and the markdown view show nothing private', async () => {+ const r = mulberry32(201);+ const slug = 'notes/get-windows';+ await importSegmented(engine, slug, pageContent(privacyText(r, 1_600_000) + crossingFacts(), privacyText(r, 300_000)));+ const none = await expectNoLeak(slug);+ expect(none.size.body_bytes).toBeGreaterThan(1_900_000);+ }, 300_000);++ test('withdrawn, purged and held rows stay hidden once the ledger records them', async () => {+ const r = mulberry32(203);+ const slug = 'notes/get-ledger';+ await importSegmented(engine, slug, pageContent(privacyText(r, 1_400_000), privacyText(r, 200_000)));+ const before = await get({ slug, body: 'window', view: 'markdown', max_bytes: 2_000_000 });+ expect(before.window.text).toContain(PRIVATE.withdrawn);+ await seedLedger(engine, slug);+ await expectNoLeak(slug, true);+ }, 300_000);++ test('a takes block left open to the end hides the tail and withholds its digest from a remote caller', async () => {+ const r = mulberry32(207);+ const slug = 'notes/get-tail';+ const tail = `<!--- gbrain:takes:begin -->\n${privacyText(r, 1_200_000, { keys: false }).replaceAll('zzpublic', `${PRIVATE.tail} `)}\n${PRIVATE.tail} last words\n`;+ await importSegmented(engine, slug, pageContent(privacyText(r, 1_200_000) + tail));+ const none = await expectNoLeak(slug);+ expect(none.size.tail_sha256).toBeUndefined();+ const local = await get({ slug, body: 'none' }, false);+ expect(local.size.tail_sha256).toMatch(/^[0-9a-f]{64}$/);+ expect(local.size.tail_region).toBe('truth');+ }, 300_000);+ });+}diff --git a/test/large-pages/segmented-get-cli.test.ts b/test/large-pages/segmented-get-cli.test.tsnew file mode 100644index 0000000000..43f7fced4a--- /dev/null+++ b/test/large-pages/segmented-get-cli.test.ts@@ -0,0 +1,145 @@+/**+ * Wave B PR 2 (spec 7.2, 7.4): around_chunk_id on a segmented page and both+ * `gbrain get` paths of one.+ *+ * 1. Protects: around_chunk_id resolves a segmented chunk from its occurrence+ * and segment-relative span (anchor stored_span, chunk_span holding the+ * chunk), and a chunk whose occurrence an edit retired is revision_changed+ * rather than a guess. The local `gbrain get` streams a segmented page+ * segment by segment, byte-identical to the same page stored inline; the+ * thin client pages it, verifies size + sha256, and prints window by window.+ * 2. Fails when: around_chunk_id falls back to the page offset or a text match,+ * a retired chunk resolves, the local stream holds more than a segment per+ * write or differs from the inline print, or the thin client prints an+ * unverified copy.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../../src/core/engine.ts';+import type { GBrainConfig } from '../../src/core/config.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { operations, type OperationContext } from '../../src/core/operations.ts';+import { OperationError } from '../../src/core/ops/contract.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { SEGMENT_MAX_BYTES } from '../../src/core/page-body/limits.ts';+import { formatGetPage, printPagedPage, streamSegmentedGet } from '../../src/cli/page-render.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { testBackends } from '../helpers/test-backends.ts';+import { importSegmented } from '../helpers/segmented-privacy-fixture.ts';++const getPage = operations.find(o => o.name === 'get_page')!;+let engine: BrainEngine;++const ctx = (remote: boolean, thinClient = false): OperationContext => ({ engine, config: {} as GBrainConfig, logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote,+ sourceId: 'default', ...(remote ? { transport: 'http', thinClient, auth: { token: 'fixture', clientId: 'cli-client', principal: { kind: 'oauth_client', id: 'cli-client' },+ scopes: ['read'], sourceId: 'default', allowedSources: ['default'] } } : {}) } as unknown as OperationContext);+const get = async (params: Record<string, unknown>, remote = false, thin = false) => await getPage.handler(ctx(remote, thin), params) as Record<string, any>;+async function refusal(p: Promise<unknown>): Promise<OperationError> {+ try { await p; } catch (e) { if (e instanceof OperationError) return e; throw e; }+ throw new Error('expected a refusal');+}++function content(edit = ''): string {+ const day = (d: number) => [`## Day ${d}`, '', ...Array.from({ length: 120 }, (_, i) => `- ${d}.${i} alice-example asked acme-example about the widget plan${d === 300 ? edit : ''}`), ''].join('\n');+ const truth = Array.from({ length: 700 }, (_, d) => day(d)).join('\n');+ const timeline = Array.from({ length: 4_000 }, (_, i) => `- 2024-01-${String(1 + (i % 28)).padStart(2, '0')}: entry ${i} with acme-example`).join('\n');+ return `---\ntitle: Widget log\ntype: note\ntags: [log]\n---\n${truth}\n\n<!-- timeline -->\n\n${timeline}\n`;+}++const SLUG = 'logs/cli-segmented';+const TWIN = 'logs/cli-inline';++for (const kind of testBackends()) {+ describe(`gbrain get and around_chunk_id on a segmented page (${kind})`, () => {+ let close: () => Promise<void>;++ beforeAll(async () => {+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ close = () => engine.disconnect();+ }+ await importSegmented(engine, SLUG, content());+ await engine.setConfig('pages.segmented_storage', 'off');+ await importFromContent(engine, TWIN, content(), { sourceId: 'default', noEmbed: true });+ const [twin] = await engine.executeRaw<{ body_storage: string }>('SELECT body_storage FROM pages WHERE slug=$1', [TWIN]);+ expect(twin?.body_storage).toBe('inline');+ }, 300_000);++ afterAll(async () => { await close(); });++ test('around_chunk_id anchors on the chunk\'s occurrence and segment-relative span, locally and remotely', async () => {+ const chunks = await engine.executeRaw<{ id: unknown; chunk_text: string }>(`SELECT c.id, c.chunk_text FROM content_chunks c JOIN pages p ON p.id = c.page_id+ WHERE p.slug = $1 AND c.occurrence_id IS NOT NULL ORDER BY c.id`, [SLUG]);+ expect(chunks.length).toBeGreaterThan(20);+ const picks = [chunks[1]!, chunks[Math.floor(chunks.length / 2)]!, chunks[chunks.length - 2]!];+ for (const remote of [false, true]) {+ for (const chunk of picks) {+ const r = await get({ slug: SLUG, body: 'window', around_chunk_id: Number(chunk.id), context_lines: 3 }, remote);+ expect(r.anchor).toBe('stored_span');+ expect(r.window.text.replace(/\s+/g, '')).toContain(chunk.chunk_text.replace(/\s+/g, ''));+ const { byte_start: start, byte_end: end } = r.chunk_span;+ const around = (await get({ slug: SLUG, body: 'window', bytes: { offset: start, length: end - start + 4_000 } }, remote)).window;+ expect(around.byte_start).toBeLessThanOrEqual(start);+ const text = Buffer.from(around.text).subarray(start - around.byte_start, end - around.byte_start).toString('utf8');+ expect(text.replace(/\s+/g, '')).toBe(chunk.chunk_text.replace(/\s+/g, ''));+ }+ }+ }, 120_000);++ test('a chunk whose occurrence an edit retired is revision_changed, and a live one still resolves', async () => {+ const slug = 'logs/cli-retired';+ await importSegmented(engine, slug, content());+ const before = await engine.executeRaw<{ id: unknown; occurrence_id: unknown; chunk_text: string }>(`SELECT c.id, c.occurrence_id, c.chunk_text FROM content_chunks c+ JOIN pages p ON p.id = c.page_id WHERE p.slug = $1 AND c.chunk_text LIKE '%- 300.5 %'`, [slug]);+ expect(before.length).toBe(1);+ const [{ row: stale }] = await engine.executeRaw<{ row: Record<string, unknown> }>('SELECT row_to_json(c) AS row FROM content_chunks c WHERE id=$1', [before[0]!.id]) as any;+ await importSegmented(engine, slug, content(' (edited)'));+ const live = await engine.executeRaw<{ n: unknown }>(`SELECT count(*) AS n FROM page_body_manifest m JOIN pages p ON p.id = m.page_id+ WHERE p.slug = $1 AND m.occurrence_id = $2 AND m.gen_to IS NULL`, [slug, before[0]!.occurrence_id]);+ expect(Number(live[0]!.n)).toBe(0);+ const e = await refusal(get({ slug, body: 'window', around_chunk_id: Number(before[0]!.id) }, true));+ expect(e.code === 'revision_changed' || (e as any).canonical === 'revision_changed').toBe(true);+ // A chunk row that outlives its occurrence (the chunk index behind the manifest) is refused the same way, not+ // resolved by offset or text.+ await engine.executeRaw(`INSERT INTO content_chunks SELECT * FROM json_populate_record(NULL::content_chunks, ($1::text)::json)`, [JSON.stringify({ ...stale, retired_generation: null })]);+ const lagging = await refusal(get({ slug, body: 'window', around_chunk_id: Number(before[0]!.id) }, true));+ expect(lagging.code === 'revision_changed' || (lagging as any).canonical === 'revision_changed').toBe(true);+ const [current] = await engine.executeRaw<{ id: unknown }>(`SELECT c.id FROM content_chunks c JOIN pages p ON p.id = c.page_id+ WHERE p.slug = $1 AND c.chunk_text LIKE '%- 300.5 % (edited)%'`, [slug]);+ expect((await get({ slug, body: 'window', around_chunk_id: Number(current!.id) }, true)).anchor).toBe('stored_span');+ }, 300_000);++ test('local gbrain get streams the page segment by segment, byte-identical to the inline print', async () => {+ const e = await refusal(get({ slug: SLUG }));+ expect(e.code).toBe('page_body_segmented');+ const writes: string[] = [];+ expect(await streamSegmentedGet(engine, { slug: SLUG }, e, async t => { writes.push(t); })).toBe(true);+ expect(writes.length).toBeGreaterThan(4);+ expect(Math.max(...writes.map(w => Buffer.byteLength(w)))).toBeLessThanOrEqual(SEGMENT_MAX_BYTES);+ const inline = formatGetPage(await get({ slug: TWIN }));+ expect(writes.join('') === inline).toBe(true);+ const json: string[] = [];+ await streamSegmentedGet(engine, { slug: SLUG, json: true }, e, async t => { json.push(t); });+ expect(JSON.parse(json.join('')).content === inline).toBe(true);+ }, 120_000);++ test('the thin client pages the page, verifies size and sha256, and prints it window by window', async () => {+ const e = await refusal(get({ slug: SLUG }, true, true));+ expect((e as any).canonical ?? e.code).toBe('page_too_large_for_inline');+ const writes: string[] = [];+ await printPagedPage(p => get(p, true, true), { slug: SLUG }, async t => { writes.push(t); });+ expect(writes.length).toBeGreaterThan(3);+ expect(writes.join('') === formatGetPage(await get({ slug: TWIN }))).toBe(true);+ let calls = 0;+ const bad: string[] = [];+ await expect(printPagedPage(async p => {+ const r = await get(p, true, true);+ if (++calls === 2) r.window.text = r.window.text.replace('widget', 'WIDGET');+ return r;+ }, { slug: SLUG }, async t => { bad.push(t); })).rejects.toThrow(/does not match/);+ expect(bad).toEqual([]);+ }, 120_000);+ });+}diff --git a/test/large-pages/segmented-get-over-ceiling.test.ts b/test/large-pages/segmented-get-over-ceiling.test.tsnew file mode 100644index 0000000000..8dbb65c77e--- /dev/null+++ b/test/large-pages/segmented-get-over-ceiling.test.ts@@ -0,0 +1,115 @@+/**+ * Wave B PR 2 (spec 7.4): `gbrain get` of a segmented page over PAGE_MAX_BYTES.+ *+ * 1. Protects: the local `gbrain get` streams a 26 MB page in writes no larger+ * than a segment, and the stream hashes to the trusted markdown view's+ * size.sha256; the thin client pages the page to its end, verified, and+ * prints it window by window. `--json` would hold the page in one string,+ * so it is refused on both paths with a fix that drops `--json`.+ * 2. Fails when: either path joins the page into one string above the ceiling,+ * or `--json` builds the document anyway.+ * 3. PGLite only, under the memory-heavy budget: one 26 MB import.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { createHash } from 'node:crypto';+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 { operations, type OperationContext } from '../../src/core/operations.ts';+import type { GBrainConfig } from '../../src/core/config.ts';+import { OperationError } from '../../src/core/ops/contract.ts';+import { importFromFile } from '../../src/core/import-file.ts';+import { readPageBodyPolicy, SEGMENT_MAX_BYTES } from '../../src/core/page-body/limits.ts';+import { PAGE_MAX_BYTES } from '../../src/core/page-size-policy.ts';+import { printPagedPage, REMOTE_PAGE_WINDOW_BYTES, streamSegmentedGet } from '../../src/cli/page-render.ts';++const getPage = operations.find(o => o.name === 'get_page')!;+const SLUG = 'logs/over-ceiling';+let engine: PGLiteEngine;+let dir: string;++const ctx = (remote: boolean): OperationContext => ({ engine, config: {} as GBrainConfig, logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote,+ sourceId: 'default', ...(remote ? { transport: 'http', thinClient: true, auth: { token: 'fixture', clientId: 'ceiling-client', principal: { kind: 'oauth_client', id: 'ceiling-client' },+ scopes: ['read'], sourceId: 'default', allowedSources: ['default'] } } : {}) } as unknown as OperationContext);+const get = async (params: Record<string, unknown>, remote = false) => await getPage.handler(ctx(remote), params) as Record<string, any>;+async function refusal(p: Promise<unknown>): Promise<OperationError> {+ try { await p; } catch (e) { if (e instanceof OperationError) return e; throw e; }+ throw new Error('expected a refusal');+}+const codeOf = (e: OperationError) => (e as any).canonical ?? e.code;++describe('gbrain get of a segmented page over PAGE_MAX_BYTES', () => {+ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await engine.setConfig('pages.segmented_storage', 'on');+ dir = mkdtempSync(join(tmpdir(), 'gb-over-ceiling-'));+ const lines: string[] = ['---\ntitle: Over the ceiling\ntype: note\n---\n'];+ for (let day = 0, size = 0; size < PAGE_MAX_BYTES + 1_000_000; day++) {+ const block = [`## Day ${day}`, '', ...Array.from({ length: 160 }, (_, i) => `- ${day}.${i} alice-example asked acme-example about the widget plan`), ''].join('\n') + '\n';+ lines.push(block);+ size += block.length;+ }+ const file = join(dir, 'page.md');+ writeFileSync(file, lines.join(''));+ expect((await importFromFile(engine, file, `${SLUG}.md`, { noEmbed: true, bodyPolicy: await readPageBodyPolicy(engine) })).status).toBe('imported');+ expect((await get({ slug: SLUG, body: 'none' })).size.body_bytes).toBeGreaterThan(PAGE_MAX_BYTES);+ }, 600_000);++ afterAll(async () => {+ await engine.disconnect();+ rmSync(dir, { recursive: true, force: true });+ });++ test('locally, the page streams in segment-sized writes that hash to the markdown view', async () => {+ const e = await refusal(get({ slug: SLUG }));+ expect(e.code).toBe('page_body_segmented');+ const hash = createHash('sha256');+ let bytes = 0, writes = 0, largest = 0;+ expect(await streamSegmentedGet(engine, { slug: SLUG }, e, async t => {+ const n = Buffer.byteLength(t);+ hash.update(t);+ bytes += n;+ writes++;+ largest = Math.max(largest, n);+ })).toBe(true);+ const view = await get({ slug: SLUG, body: 'window', view: 'markdown', max_bytes: 1_000 });+ expect(bytes).toBe(view.size.total_bytes);+ expect(hash.digest('hex')).toBe(view.size.sha256);+ expect(writes).toBeGreaterThan(PAGE_MAX_BYTES / SEGMENT_MAX_BYTES);+ expect(largest).toBeLessThanOrEqual(SEGMENT_MAX_BYTES);+ }, 300_000);++ test('locally, --json is refused with a fix that drops it, and nothing is written', async () => {+ const e = await refusal(get({ slug: SLUG }));+ const writes: string[] = [];+ const json = await refusal(streamSegmentedGet(engine, { slug: SLUG, json: true }, e, async t => { writes.push(t); }));+ expect(codeOf(json)).toBe('page_too_large_for_inline');+ expect(json.fix?.argv).toEqual(['gbrain', 'get', '--source', 'default', '--', SLUG]);+ expect(writes).toEqual([]);+ }, 60_000);++ test('the thin client pages, verifies and prints window by window; --json is refused', async () => {+ expect(codeOf(await refusal(get({ slug: SLUG }, true)))).toBe('page_too_large_for_inline');+ const hash = createHash('sha256');+ let bytes = 0, writes = 0, largest = 0, total = 0;+ await printPagedPage(async p => { const r = await get(p, true); total = r.size.total_bytes; return r; }, { slug: SLUG }, async t => {+ const n = Buffer.byteLength(t);+ hash.update(t);+ bytes += n;+ writes++;+ largest = Math.max(largest, n);+ });+ expect(bytes).toBe(total);+ expect(writes).toBeGreaterThan(PAGE_MAX_BYTES / REMOTE_PAGE_WINDOW_BYTES);+ expect(largest).toBeLessThanOrEqual(REMOTE_PAGE_WINDOW_BYTES);+ expect(hash.digest('hex')).toBe((await get({ slug: SLUG, body: 'window', view: 'markdown', max_bytes: 1_000 }, true)).size.sha256);+ const writesJson: string[] = [];+ const json = await refusal(printPagedPage(p => get(p, true), { slug: SLUG, json: true }, async t => { writesJson.push(t); }));+ expect(codeOf(json)).toBe('page_too_large_for_inline');+ expect(json.fix?.argv).toEqual(['gbrain', 'get', '--', SLUG]);+ expect(writesJson).toEqual([]);+ }, 600_000);+});diff --git a/test/large-pages/segmented-get-page-parity.test.ts b/test/large-pages/segmented-get-page-parity.test.tsnew file mode 100644index 0000000000..495f9f16ea--- /dev/null+++ b/test/large-pages/segmented-get-page-parity.test.ts@@ -0,0 +1,162 @@+/**+ * Wave B PR 2 (spec 7.2): get_page over a segmented page answers what it+ * answers over the same page stored inline.+ *+ * 1. Protects: for a page that fits both ways (a 2 MB body, several segments), the+ * body: 'none', outline (every page), window (no selector, lines, bytes,+ * a cursor walk to the end) and view: 'markdown' (paged to its end)+ * responses of a segmented copy equal the inline copy's, for a local and a+ * remote caller, apart from the segmented-only fields (body_storage,+ * size.body_bytes / body_lines / tail_*), the chunk count (the segmented+ * chunker cuts per segment, spec 4.1), the revision and the cursor's page+ * id and revision. Coordinates are projected bytes on both.+ * 2. Fails when: a segmented window, line number, outline entry (line range,+ * byte range, dates, the leading entry) or markdown byte differs from the+ * whole-document cut, or a cursor walk skips or repeats bytes.+ * 3. PGLite always; PostgreSQL when DATABASE_URL is set (test/postgres-unit-arms.txt).+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../../src/core/engine.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { operations, type OperationContext } from '../../src/core/operations.ts';+import type { GBrainConfig } from '../../src/core/config.ts';+import { decodeCursor } from '../../src/core/page-window/window.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { testBackends } from '../helpers/test-backends.ts';++const getPage = operations.find(o => o.name === 'get_page')!;+const SLUG = 'notes/parity-example';+const noopLogger = { info: () => {}, warn: () => {}, error: () => {} };++/** Headings every ~30 KB, dates, fenced code holding a heading, multi-byte text, one line longer than a window, and a timeline. */+function content(): string {+ const truth: string[] = ['Preamble about acme-example before any heading.', ''];+ for (let s = 0; s < 100; s++) {+ truth.push(`## Section ${s} — 2024-${String(1 + (s % 12)).padStart(2, '0')}-1${s % 10} café`, '');+ if (s % 7 === 3) truth.push('```md', '# not a heading inside a fence', '```', '');+ if (s === 40) truth.push(`long line ${'λ'.repeat(30_000)} end`, '');+ for (let p = 0; p < 300; p++) truth.push(`- ${s}.${p} alice-example noted the widget plan on 2023-0${1 + (p % 9)}-0${1 + (p % 9)} ✓`);+ truth.push('');+ }+ const timeline = Array.from({ length: 400 }, (_, i) => `- **2025-0${1 + (i % 9)}-1${i % 10}** | entry ${i} about acme-example`).join('\n');+ return `---\ntitle: Parity example\ntype: note\ntags: [log]\n---\n${truth.join('\n')}\n\n<!-- timeline -->\n\n${timeline}\n`;+}++/** The response without what only a segmented page reports, its revision, and the cursor's page id and revision. */+function comparable(r: Record<string, any>): Record<string, any> {+ const out = JSON.parse(JSON.stringify(r)) as Record<string, any>;+ delete out.revision;+ delete out.body_storage;+ delete out.chunks;+ if (out.size) for (const k of ['body_bytes', 'body_lines', 'tail_sha256', 'tail_region']) delete out.size[k];+ if (out.next_cursor) {+ const c = decodeCursor(out.next_cursor)!;+ out.next_cursor = { view: c.view, offset: c.offset, max_bytes: c.max_bytes };+ out.next.arguments.cursor = out.next_cursor;+ }+ return out;+}++for (const kind of testBackends()) {+ describe(`get_page parity, segmented vs inline (${kind})`, () => {+ const engines: Record<'inline' | 'segmented', BrainEngine> = {} as never;+ const closers: Array<() => Promise<void>> = [];++ beforeAll(async () => {+ for (const storage of ['inline', 'segmented'] as const) {+ let engine: BrainEngine;+ if (kind === 'postgres') {+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ engine = pg.engine;+ closers.push(pg.close);+ } else {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ closers.push(() => engine.disconnect());+ }+ await engine.setConfig('pages.segmented_storage', storage === 'segmented' ? 'on' : 'off');+ await importFromContent(engine, SLUG, content(), { sourceId: 'default', noEmbed: true });+ const [row] = await engine.executeRaw<{ body_storage: string }>('SELECT body_storage FROM pages WHERE slug=$1', [SLUG]);+ expect(row?.body_storage).toBe(storage);+ engines[storage] = engine;+ }+ const [rows] = await engines.segmented.executeRaw<{ n: unknown }>('SELECT count(*) AS n FROM page_body_manifest');+ expect(Number(rows!.n)).toBeGreaterThanOrEqual(3);+ }, 300_000);++ afterAll(async () => { for (const close of closers) await close(); });++ const ctx = (engine: BrainEngine, remote: boolean): OperationContext => ({ engine, config: {} as GBrainConfig, logger: noopLogger, dryRun: false, remote,+ sourceId: 'default', ...(remote ? { transport: 'http', auth: { token: 'fixture', clientId: 'parity-client', principal: { kind: 'oauth_client', id: 'parity-client' },+ scopes: ['read'], sourceId: 'default', allowedSources: ['default'] } } : {}) } as unknown as OperationContext);+ const both = async (remote: boolean, params: Record<string, unknown>) => {+ const [inline, segmented] = await Promise.all((['inline', 'segmented'] as const).map(async s =>+ await getPage.handler(ctx(engines[s], remote), { slug: SLUG, ...params }) as Record<string, any>));+ return { inline: inline!, segmented: segmented! };+ };+ const expectSame = async (remote: boolean, params: Record<string, unknown>) => {+ const { inline, segmented } = await both(remote, params);+ expect(segmented.body_storage).toBe('segmented');+ expect(comparable(segmented)).toEqual(comparable(inline));+ return { inline, segmented };+ };++ for (const remote of [false, true]) {+ const who = remote ? 'remote' : 'local';++ test(`${who}: body none, auto and every outline page agree`, async () => {+ const none = await expectSame(remote, { body: 'none' });+ expect(none.segmented.size.body_bytes).toBeGreaterThan(1_900_000);+ if (remote) await expectSame(remote, {});+ let from = 0;+ let pages = 0;+ for (;;) {+ const { inline } = await expectSame(remote, { body: 'outline', outline_from: from });+ pages++;+ if (inline.outline.next_from_index === undefined) break;+ from = inline.outline.next_from_index;+ }+ expect(pages).toBeGreaterThanOrEqual(1);+ }, 120_000);++ test(`${who}: windows by lines, bytes and a cursor walk to the end agree`, async () => {+ await expectSame(remote, { body: 'window' });+ for (const lines of [{ from: 1, count: 50 }, { from: 9_000, count: 400 }, { from: 12_041, count: 3 }, { from: 24_300, count: 2_000 }, { from: 99_999, count: 5 }]) {+ await expectSame(remote, { body: 'window', lines });+ }+ for (const bytes of [{ offset: 0, length: 4_000 }, { offset: 1_048_570, length: 40_000 }, { offset: 1_300_001, length: 9_000 }, { offset: 1_999_999, length: 70_000 }]) {+ await expectSame(remote, { body: 'window', bytes });+ }+ let { inline, segmented } = await expectSame(remote, { body: 'window', max_bytes: 300_000 });+ let windows = 1;+ while (inline.next_cursor) {+ const [i, s] = await Promise.all([+ getPage.handler(ctx(engines.inline, remote), { slug: SLUG, cursor: inline.next_cursor }),+ getPage.handler(ctx(engines.segmented, remote), { slug: SLUG, cursor: segmented.next_cursor }),+ ]) as Array<Record<string, any>>;+ inline = i!;+ segmented = s!;+ expect(comparable(segmented)).toEqual(comparable(inline));+ windows++;+ }+ expect(windows).toBeGreaterThan(5);+ }, 180_000);++ test(`${who}: view markdown paged to its end agrees, sha256 included`, async () => {+ let { inline, segmented } = await expectSame(remote, { body: 'window', view: 'markdown', max_bytes: 400_000 });+ expect(segmented.size.sha256).toMatch(/^[0-9a-f]{64}$/);+ while (inline.next_cursor) {+ const [i, s] = await Promise.all([+ getPage.handler(ctx(engines.inline, remote), { slug: SLUG, view: 'markdown', cursor: inline.next_cursor }),+ getPage.handler(ctx(engines.segmented, remote), { slug: SLUG, view: 'markdown', cursor: segmented.next_cursor }),+ ]) as Array<Record<string, any>>;+ inline = i!;+ segmented = s!;+ expect(comparable(segmented)).toEqual(comparable(inline));+ }+ }, 180_000);+ }+ });+}diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex a80539f95c..d399cf0233 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -67,6 +67,7 @@ test/large-pages/chunk-visibility.test.tstest/large-pages/managed-streamed-import.test.tstest/large-pages/managed-sync-segmented-rename.test.tstest/large-pages/projection-parity.test.ts+test/large-pages/remote-get-page-privacy.test.tstest/large-pages/remote-window-privacy.test.tstest/large-pages/sealed-segmented-search.test.tstest/large-pages/segment-vector-reuse.test.ts@@ -74,6 +75,8 @@ test/large-pages/segmented-body-unreachable.test.tstest/large-pages/segmented-derived-work.test.tstest/large-pages/segmented-embedding-paths.test.tstest/large-pages/segmented-embedding.test.ts+test/large-pages/segmented-get-cli.test.ts+test/large-pages/segmented-get-page-parity.test.tstest/large-pages/segmented-shrink-below-ceiling.test.tstest/large-pages/segmented-versions.test.tstest/link-cross-source.test.ts