Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Large pages PR 2 lane 2b: segment-aware evidence, bounded leads and search dedup
garrytanfdb6d26ae768
diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.mdindex 92ca18fc62..14ac3d27df 100644--- a/docs/architecture/KEY_FILES.md+++ b/docs/architecture/KEY_FILES.md@@ -57,7 +57,7 @@ link it here rather than raising the cap.| [Core Services (1/3)](key-files/core-services-1.md) | `src/core/advisor/{types,run,render,recommended-set,history,apply,collect-*}.ts` through `src/core/connectors/` || [Core Services (1/3, continued)](key-files/core-services-1-continued.md) | `src/core/context/` through `src/core/context/ipc-path.ts` || [Core Services (2/3)](key-files/core-services-2.md) | `src/core/conversation-parser/` through `src/core/ops/sources.ts`, except `src/core/persistence/` |-| [Core Services (2/3, continued)](key-files/core-services-2-continued.md) | `page-state/`, `page-body/page-shape.ts`, `progressive-batch/` |+| [Core Services (2/3, continued)](key-files/core-services-2-continued.md) | `page-state/`, `page-{body,window}/`, `progressive-batch/` || [Core Services (3/3)](key-files/core-services-3.md) | `src/core/think/index.ts` through `src/core/verbs/usage-log.ts` || [Core Utilities (1/2)](key-files/core-utilities-1.md) | `src/core/archive-crawler-config.ts` through `src/core/remediation-checkpoint.ts`; [`cycle.ts`](key-files/core-cycle-primitive.md) || [Core Utilities (2/2)](key-files/core-utilities-2.md) | `src/core/repair/` through `src/core/verbs.ts` |diff --git a/docs/architecture/key-files/core-search-1.md b/docs/architecture/key-files/core-search-1.mdindex 3d5107ef55..4290a2deba 100644--- a/docs/architecture/key-files/core-search-1.md+++ b/docs/architecture/key-files/core-search-1.md@@ -18,7 +18,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/date-labels.ts` — row-date honesty for `search` / `query`. `effectiveDateLabel(source)` maps `effective_date_source` to a document date (`date`, `published`, `filename`), an event date (`event_date`) or a fallback (`created`, `fallback`: when the page was created or imported); `dateLabelLine(rows)` is the one model-visible `[gbrain dates]` line `src/mcp/dispatch.ts` appends when rows carry dates, naming only the sources present and saying the date is never a contract's effective or validity date. Lean rows (`lean-rows.ts`) keep `effective_date_source` for it. Test: `test/search-date-labels.test.ts`.-- `src/core/search/dedup.ts` — 4-layer result dedup + compiled-truth guarantee: (1) top 3 chunks per page by score, (2) drop chunks >0.85 Jaccard-similar to already-kept chunks of the SAME page (cross-page near-dups survive — two legitimately similar pages both return), (3) no page type exceeds 60% of results — applied only when the candidate set actually contains multiple page types; a homogeneous set passes through unchanged because dropping (for example) one of three distinct LongMemEval `note` sessions cannot introduce diversity and destroys multi-session recall (pinned by the homogeneous-set case in `test/dedup.test.ts`), (4) max 2 chunks per page (default; the two-pass structural expansion in `hybrid.ts` widens it), (5) ensure at least 1 compiled_truth chunk per page — the page's best compiled_truth chunk is APPENDED (never swapped over a kept chunk, so matching evidence survives) and the final output is re-sorted by score, because slice / token budget / evidence consumers assume score order. Page identity is the composite `pageKey()` (source_id, slug) — the one canonical key helper every layer uses, so slug collisions across sources can't collapse recall.+- `src/core/search/dedup.ts` — 4-layer result dedup + compiled-truth guarantee: (1) top 3 chunks per page by score, (2) drop chunks >0.85 Jaccard-similar to already-kept chunks of the SAME page (cross-page near-dups both survive), (3) no page type exceeds 60% of results — only when the candidates span several page types; a homogeneous set passes unchanged, since dropping one of three distinct LongMemEval `note` sessions only loses multi-session recall (pinned in `test/dedup.test.ts`), (4) max 2 chunks per page (default; `hybrid.ts`'s two-pass structural expansion widens it; with `regions` (`segmentRegions`: one query, only when a page has over 2 results; passed by `hybrid.ts` and both keyword-only paths) a segmented page applies (1) and (4) per occurrence cluster (gaps over 1 MiB split) and keeps at most `MAX_PER_SEGMENTED_PAGE` 6), (5) at least 1 compiled_truth chunk per page — the best one is APPENDED (never swapped over a kept chunk, so matching evidence survives) and the output re-sorted by score, which slice / token budget / evidence consumers assume. Every layer keys pages by `pageKey()` (source_id, slug), so slug collisions across sources can't collapse recall.- `src/core/search/diverse-pool.ts` — the session-diverse candidate pool before the reranker, `search.diverse_pool_depth` (integer 0..100, `off` = 0; 0 in every bundle, so off by default). With N > 0: every retrieval arm fetches at least N candidates (`hybrid/request.ts` passes `max(PRE_FUSION_POOL_FLOOR, N)` as the `perArmPoolLimit` floor; still capped at `MAX_SEARCH_LIMIT` unless an eval pool depth is set), `capPerSession` keeps the first row of each session in the deduped pool (`hybrid/rank.ts` `capSessionPool`, called on `dedupResults`' output; a session is `sessionPrefix(slug)` from `graph-signals.ts`, else the page, keyed with the source id) and `rerankAndPin` raises the reranker's `topNIn` to at least N. The keyword-only paths have no reranker and are unchanged. `normalizeDiversePoolDepth` is the one range contract (mode.ts config parse and the `gbrain config set` refusal through `search/config-values.ts`); the mode field folds into `knobsHash` as an append-only `dpd=` part only when on. Motivation and measurement: BEAM-1M S1 in gbrain-evals (`docs/benchmarks/2026-10-12-beam-1m-s1-fixes.md`): at depth 100 on BEAM-1M dev (voyage-4, balanced reranker) strict recall at 10 rose 76 → 83 of 198 (+3.5 points, 95% interval [0, +6.6]) and at 5 was flat (55 → 56), with search p50 latency 340 → 455 ms and about 4x the rerank tokens per query; the preregistered flip rule needed an interval above zero, so every bundle keeps 0. Tests: `test/search/diverse-pool.test.ts`, `test/search/diverse-pool-hybrid.serial.test.ts`.- `src/core/search/embedding-column.ts` — single source of truth for "which `content_chunks.*` column does this query rank against?" Pure functions, no engine I/O: `loadRegistry(cfg)` walks the `embedding_columns` config (DB plane, JSON map keyed by column name with `{provider, dimensions, type}` entries), seeds the OpenAI `embedding` builtin when unset, validates everything before it lands (column-name regex, type ∈ `vector | halfvec`, dims in [1, 8192], provider format) using `Object.create(null)` + `Object.hasOwn` so a key like `constructor` rejects instead of resolving to `Object.prototype.constructor`. `resolveColumn(registry, override?, cfg)` is the boundary call: returns a frozen `ResolvedColumn` descriptor (`{name, provider, dimensions, type}`) honoring per-call override → `search_embedding_column` config → `'embedding'` default; throws `UnknownEmbeddingColumnError` with the list of registered names on miss. `isCacheSafe(resolved, cfg)` compares the full embedding SPACE (provider + dimensions + name) against cfg's default so a repointed `embedding` builtin doesn't serve OpenAI-shaped cache rows. `validateResolvedColumn(descriptor)` re-validates hand-rolled descriptors that bypass the registry (internal-SDK passthrough) so the SQL-injection escape hatch through the descriptor field is closed. Consumed by `hybridSearch`, `gateway.embedQuery(text, {embeddingModel, dimensions})`, `cosineReScore`, and the `query` MCP op (per-call `embedding_column` param). Engine column routing is covered by `test/e2e/embedding-column-pglite.test.ts`, `test/e2e/embedding-column-postgres.test.ts` and `test/cosine-rescore-column.test.ts`. Write side: `resolveWriteColumnFromConfigRows({searchEmbeddingColumn, embeddingColumnsJson})` resolves upsertChunks's active write target from the raw DB-plane config rows through the same registry/validation chain (legacy `embedding` descriptor when neither row routes elsewhere; `embedding_image` falls back to the legacy text column since image vectors travel in their own INSERT column; malformed registry JSON is forgiven like loadConfigWithEngine; unregistered names throw the paste-ready error), and `vectorCastSuffix(resolved)` is the placeholder-free `'::vector' | '::halfvec(N)'` cast shared by the read fragment builder and the write path so the two casts can't drift. Pinned by `test/e2e/upsert-chunks-registry-column.test.ts`.diff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.mdindex d431d7e4c7..bd3e5ef299 100644--- a/docs/architecture/key-files/core-search-2.md+++ b/docs/architecture/key-files/core-search-2.md@@ -9,7 +9,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/rrf-page-fusion.ts` — `accumulateRrf(lists)`, the one accumulation step behind `rrfFusion` / `rrfFusionWeighted` in `hybrid.ts`. Votes are keyed on the PAGE `(source_id, slug)`: each list adds `weight / (k + rank)` to a page once, at its best rank, chunks stay distinct rows keyed `(source_id, slug, chunk_id)` with their own vote (`own`) and an OR-propagated `keyword_hit` (`keyword_relaxed` only if every holding list was relaxed), and each page's lead chunk (largest `own`, first-seen on ties — a vector arm in `composeFusionLists` order) scores the page's summed vote while its other chunks score their own vote. Pure. Pinned by `test/search/rrf-page-grain.test.ts`.-- `src/core/search/evidence-delivery.ts` — the `return_unit` evidence assembler (default `auto`: conversation pages by type or `chat/`/`conversations/` slug come back whole under `search.return_budget_conversation` (24,000), every other hit is its unchanged chunk; `effectivePlan` skips the stage when an implied `auto` sees no conversation hit, so that path and `chunk` stay byte-identical). `resolveEvidencePlan` validates `return_unit` / `return_window` (invalid_params naming the allowed values and an example), reads `search.return_unit` / `think.return_unit`, `search.return_window`, `search.return_budget_default` (6,000), `search.return_budget_conversation` (24,000) and clamps remote budgets to `search.return_budget_max_remote` (32,000, reported). Snippet precedence: explicit `snippet_chars` > explicit `return_unit` > subagent default cap > config unit. `deliverEvidence` groups hits by page_id (one block per page at its best rank), makes ONE `engine.getChunkWindows` call (re-authorizes every page; unauthorized pages are dropped, never served from hit text), builds the page text from the stored body sanitized whole and passed through `credentialSafeProjection` before slicing (`pageEvidenceText`: compiled truth + serializer timeline sentinel + timeline; frontmatter excluded; private-key spans become newline-padded `<REDACTED:private_key_pem>` tokens, the same text the chunkers cut from), locates the hit chunks in it (`locateChunks`: exact, then whitespace-insensitive, since the chunker trims and folds whitespace), cuts `window` / `section` (ATX headings outside code fences, or conversation rounds detected structurally, never by page type) / `page` / `auto` (fenced-code hits are placed by their code minus the chunker's synthesized header), counts tokens as the sum of per-line cl100k counts, reserves each page's matching span before enriching by rank, caps blocks at 60,000 characters, redacts secrets before final accounting, and returns NEW rows with `delivered` plus a `delivery` meta. The plan records `budgetExplicit` (the caller passed the budget) and the resolved `packing` (`search.auto_packing` or the library override); `capEngaged` (unit `auto`, explicit budget, packing not `off`) routes allocation to `allocateCapped`: global rank one first (cut with `EVIDENCE_CUT_MARKER` when it alone exceeds the budget), the rank-order prefix of other non-conversation chunks that fits (rest `budget_note`), then conversations by `cap_only` (floors, then enrichment), `breadth_capped` (longest prefix whose title + floor + `return_window` target window fits; rest `breadth_cap`) or `depth_first` (each session grown in turn); nothing spills. `capEvidenceToBudget` recounts title + `chunk_text` at the final boundary (after redaction and `capDeliveredSnippets`, whose marker is paid from the row's own allocation) and rewrites `budget_used`. Without an explicit budget none of this runs and the bytes are the pre-cap path's. Fetch failure/timeout (5 s) falls back to the hit chunk only for live hits. `assembleEvidenceForHits` / op `assemble_evidence` deliver the exact evidence `query` returns for a frozen `(source_id, slug, chunk_id)` list, `effective_date` included (`applyEffectiveDate`, the live rows' normalizer); `evidenceFingerprint` hashes it (gbrain-evals E1/E3 parity). With `search.evidence_date_header` on (`plan.dateHeader`), each block (including `auto` passthrough chunks) starts with its one-line date header from `evidence-date.ts`, reserved in the block floor like the title, counted in `delivered.tokens`, with spans shifted past it and `delivery.date_header: true`; a failed date read renders `unknown` and adds `date_header_unavailable`. `search.long_page_unit` (F2, default `off`): `withLongPagePolicy` (called only by the `search`/`query` caller, so recall, think and `assemble_evidence` never carry it) sets `plan.longPage` (unit plus `search.long_page_min_chars`, default 20,000) under an implied `auto` with no explicit budget (`snippet_chars` does not turn it off; `capDeliveredSnippets` skips `reason: long_page` rows and cuts every other row); `selectLongPages` runs one character/byte-count preflight under the read scope (long = stored body at least `minChars` characters, confirmed on the rendered `pageEvidenceText` at delivery; at most `LONG_PAGE_MAX_PAGES` 5 and `LONG_PAGE_MAX_INPUT_BYTES` 1,000,000, whole pages only; `LONG_PAGE_DEADLINE_MS` 2,000 for preflight plus fetch) and returns exactly `effectivePlan` when no page is long; `deliverEvidence` fetches the selected pages in their own bounded `getChunkWindows` call, delivers them in the unit with `reason: long_page`, and returns any it cannot deliver (limits, deadline, fetch failure, over budget) as their ranked chunk with `reason: long_page_chunk` and a `long_page_*` fallback. Normative spec: `docs/evidence-delivery.md`. Tests: `test/evidence-delivery.test.ts`, `test/evidence-delivery-golden.test.ts`, `test/e2e/evidence-delivery-leak.test.ts`, `test/e2e/evidence-delivery-parity.test.ts`; bench `scripts/bench-evidence-delivery.ts`. Large pages: a `page` (or auto→page) unit over 256 KB is delivered as a window with `fallback_reason: page_over_inline_bytes`; above 1 MiB, hits are located only by stored spans (`locateChunksByStoredSpans`) and the anchor fallback never whitespace-folds the whole text.+- `src/core/search/evidence-delivery.ts` — the `return_unit` evidence assembler (default `auto`: conversation pages by type or `chat/`/`conversations/` slug come back whole under `search.return_budget_conversation` (24,000), every other hit is its unchanged chunk; `effectivePlan` skips the stage when an implied `auto` sees no conversation hit, so that path and `chunk` stay byte-identical). `resolveEvidencePlan` validates `return_unit` / `return_window` (invalid_params naming the allowed values and an example), reads `search.return_unit` / `think.return_unit`, `search.return_window`, `search.return_budget_default` (6,000), `search.return_budget_conversation` (24,000) and clamps remote budgets to `search.return_budget_max_remote` (32,000, reported). Snippet precedence: explicit `snippet_chars` > explicit `return_unit` > subagent default cap > config unit. `deliverEvidence` groups hits by page_id (one block per page at its best rank), makes ONE `engine.getChunkWindows` call (re-authorizes every page; unauthorized pages are dropped, never served from hit text), builds the page text from the stored body sanitized whole and passed through `credentialSafeProjection` before slicing (`pageEvidenceText`: compiled truth + serializer timeline sentinel + timeline; frontmatter excluded; private-key spans become newline-padded `<REDACTED:private_key_pem>` tokens, the same text the chunkers cut from), locates the hit chunks in it (`locateChunks`: exact, then whitespace-insensitive, since the chunker trims and folds whitespace), cuts `window` / `section` (ATX headings outside code fences, or conversation rounds detected structurally, never by page type) / `page` / `auto` (fenced-code hits are placed by their code minus the chunker's synthesized header), counts tokens as the sum of per-line cl100k counts, reserves each page's matching span before enriching by rank, caps blocks at 60,000 characters, redacts secrets before final accounting, and returns NEW rows with `delivered` plus a `delivery` meta. The plan records `budgetExplicit` (the caller passed the budget) and the resolved `packing` (`search.auto_packing` or the library override); `capEngaged` (unit `auto`, explicit budget, packing not `off`) routes allocation to `allocateCapped`: global rank one first (cut with `EVIDENCE_CUT_MARKER` when it alone exceeds the budget), the rank-order prefix of other non-conversation chunks that fits (rest `budget_note`), then conversations by `cap_only` (floors, then enrichment), `breadth_capped` (longest prefix whose title + floor + `return_window` target window fits; rest `breadth_cap`) or `depth_first` (each session grown in turn); nothing spills. `capEvidenceToBudget` recounts title + `chunk_text` at the final boundary (after redaction and `capDeliveredSnippets`, whose marker is paid from the row's own allocation) and rewrites `budget_used`. Without an explicit budget none of this runs and the bytes are the pre-cap path's. Fetch failure/timeout (5 s) falls back to the hit chunk only for live hits. `assembleEvidenceForHits` / op `assemble_evidence` deliver the exact evidence `query` returns for a frozen `(source_id, slug, chunk_id)` list, `effective_date` included (`applyEffectiveDate`, the live rows' normalizer); `evidenceFingerprint` hashes it (gbrain-evals E1/E3 parity). With `search.evidence_date_header` on (`plan.dateHeader`), each block (including `auto` passthrough chunks) starts with its one-line date header from `evidence-date.ts`, reserved in the block floor like the title, counted in `delivered.tokens`, with spans shifted past it and `delivery.date_header: true`; a failed date read renders `unknown` and adds `date_header_unavailable`. `search.long_page_unit` (F2, default `off`): `withLongPagePolicy` (called only by the `search`/`query` caller, so recall, think and `assemble_evidence` never carry it) sets `plan.longPage` (unit plus `search.long_page_min_chars`, default 20,000) under an implied `auto` with no explicit budget (`snippet_chars` does not turn it off; `capDeliveredSnippets` skips `reason: long_page` rows and cuts every other row); `selectLongPages` runs one character/byte-count preflight under the read scope (long = stored body at least `minChars` characters, confirmed on the rendered `pageEvidenceText` at delivery; at most `LONG_PAGE_MAX_PAGES` 5 and `LONG_PAGE_MAX_INPUT_BYTES` 1,000,000, whole pages only; `LONG_PAGE_DEADLINE_MS` 2,000 for preflight plus fetch) and returns exactly `effectivePlan` when no page is long; `deliverEvidence` fetches the selected pages in their own bounded `getChunkWindows` call, delivers them in the unit with `reason: long_page`, and returns any it cannot deliver (limits, deadline, fetch failure, over budget) as their ranked chunk with `reason: long_page_chunk` and a `long_page_*` fallback. Normative spec: `docs/evidence-delivery.md`. Tests: `test/evidence-delivery.test.ts`, `test/evidence-delivery-golden.test.ts`, `test/e2e/evidence-delivery-leak.test.ts`, `test/e2e/evidence-delivery-parity.test.ts`; bench `scripts/bench-evidence-delivery.ts`. Large pages: a `page` (or auto→page) unit over 256 KB is delivered as a window with `fallback_reason: page_over_inline_bytes`; above 1 MiB, hits are located only by stored spans (`locateChunksByStoredSpans`) and the anchor fallback never whitespace-folds the whole text. A segmented page (Wave B PR 2) is planned by `planSegmentedBlock` from the windows `segmented-evidence.ts` reads around its hits, one run per window (emission marks the gap between runs, a section never crosses one); no page text, whole-page projection or `locateChunks` runs for it, and a failed segment read falls back to the hit chunk (`segment_read_failed`, live hits only).- `src/core/search/page-rank-cut.ts` — W5 page-unit ranking cut (on by default; `search.page_rank_cut off` disables it): with `return_unit: page` and a caller budget, `resolveEvidencePlan` stores `rankCut` (`{mode, factor, caller_budget}`, factor from `search.page_rank_cut_factor`, default 1.5) on the plan; `search`/`query`/`recall` pass it as `HybridSearchOpts.pageRankCut`, and `liftModeCut` drops the mode's chunk-token `tokenBudget` in both the inner request and the cache resolver (`tb=` is in the knobs hash). Delivery applies the cut: `cutWholePages` (this file, pure) keeps rank-order pages while their whole delivered cost (evidence-delivery.ts `wholeCost`: floor plus every enrichment piece within the block char cap) fits `factor × the shared budget`, keeps the crossing page only when its floor fits what is left, and drops the rest as `rank_cut`. `delivery.page_rank_cut` reports mode, factor, caller budget, target, applied cost, candidates and kept. Tests: `test/search/page-rank-cut.test.ts` (both engines).- `src/core/search/evidence-date.ts` — C1 dated evidence blocks: the fixed header grammar (`[observed YYYY-MM-DD|unknown]` for page blocks; `[observed unknown; valid FROM to UNTIL]` for `recall` facts), `pageObservationDate` (effective-date precedence with `event_date` removed and no row-timestamp fallback; mirrors #6020's `resolveObservationDate`, the seam to swap once it lands), `formatBrainDay` from `effective-date.ts` (midnight UTC renders as written, other instants in `brain.timezone`; the one function think's `<page date>` also renders through, while the header's `observed` stays when the text was said, never the content date), `loadPageDateHeaders` (one `pages` read per delivery; only the derived day leaves it) and `evidenceDateHeaderEnabled` (`search.evidence_date_header`, default off). Tests: `test/evidence-date-header.test.ts`.@@ -19,7 +19,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/query-arms.ts` — `applyQueryArms`: the `query` op's post-retrieval arms in order (entity anchoring, then the facts arm), each behind its own key (entity anchoring default off, the facts arm default on); a temporal-cue query with a token budget takes the temporal fact reserve instead of the facts arm when `search.temporal_fact_reserve` is on; with all off it returns the rows untouched.- `src/core/search/image-vector-presence.ts` — `brainHasImageVectors` (one `EXISTS embedding_image IS NOT NULL` probe per engine, cached 60 s, fail-open to true). `hybrid/arms.ts` uses it so an inferred image/both modality on a brain with no image embeddings stays text: no multimodal embed, keyword arm kept, no `vector_arm_failed`; the opt-in LLM modality tie-break still runs, and an image or both answer is demoted to text. An explicit `crossModal` is honored. Tests: `test/search-image-arm-text-only.test.ts`, `test/cross-modal-hybrid-integration.serial.test.ts`.-- `src/core/search/chunk-windows.ts` — request/response shapes and the row mapper for `BrainEngine.getChunkWindows`. The SQL lives once in `src/core/engine-sql/chunks.ts` (`getChunkWindows`): page rows (authorization + seal + max chunk index + raw body columns) and chunk rows (inside the requested chunk_index ranges, text modality, requested chunk sources, row cap) come back in one UNION so the row cap never hides a page's authorization; the predicate is the search legs' (source scope, deleted, current text projection, archived source, quarantine, private pages, safe chunks). Postgres runs it inside the scoped read transaction. Chunk rows carry `projected_byte_start/end` when recorded.+- `src/core/search/chunk-windows.ts` — request/response shapes and the row mapper for `BrainEngine.getChunkWindows`. The SQL lives once in `src/core/engine-sql/chunks.ts` (`getChunkWindows`): page rows (authorization + seal + max chunk index + raw body columns; a segmented page's row says `segmented` and carries no body) and chunk rows (inside the requested chunk_index ranges, text modality, requested chunk sources, row cap) come back in one UNION so the row cap never hides a page's authorization; the predicate is the search legs' (source scope, deleted, current text projection, archived source, quarantine, private pages, safe chunks). Postgres runs it inside the scoped read transaction. Chunk rows carry `projected_byte_start/end` when recorded, and on a segmented page their `occurrence_id` (the span is relative to that occurrence's projection), the references `search/segmented-evidence.ts` reads windows around.+- `src/core/search/segmented-evidence.ts` — Wave B PR 2 (spec 7.4): the windows an evidence block of a segmented page is cut from. `readSegmentedWindows` opens the body (`page-body/read-range.ts`), places each hit from its chunk's occurrence and segment-relative projected span through the projected layout (a span is trusted only while it still holds the chunk's text; a hit whose chunk has no span is placed by a unique exact match inside its own segment, else positionally), and reads with `readBodyRange` (projected space, the remote read projection with the per-segment withdrawal and fence overlays) only the hits' neighbor chunks (`window`), the hit's segment (`section`) or the whole text while within the inline read size (`page`), widened to whole lines and merged where they meet. Returns the runs in document order with chunk spans in UTF-16; `evidence-delivery.ts` `planSegmentedBlock` joins them. Never builds a page text or calls `locateChunks`. Tests: `test/large-pages/segmented-evidence.test.ts` (privacy, projection parity, separate windows), `test/large-pages/segmented-evidence-read-cost.test.ts` (40 MiB page: at most two segment texts loaded per hit).- `src/core/search/explain-target.ts` — `explain_target` diagnosis. A `TargetTrace` (HybridSearchOpts.explainTarget) records the target page's presence and 1-based rank at each pipeline stage: every arm instance (`arm:<label>`, plus `arm:keyword_raw`/`arm:title_raw` before relaxed-row demotion), `fused`, `deduped`, `reranked`, `return_pool`, `limit_slice`, `token_budget`. `diagnoseTrace` returns one state (`retrieved` / `dropped` / `reinjected` / `not_retrieved` / `not_recorded`) naming the first stage that lost the page; boost stages are never reported as drops (they only re-order). `probeTarget` + `diagnoseProbe` run one read under the caller's read policy and separate not-indexed / stale projection / unsealed safe chunks / ambiguous slug; an unreadable page and an absent page return the same `target_not_found_or_not_visible`. Every diagnosis carries an Action-contract fix the `search`/`query` ops emit as a notice. Pinned by `test/search/explain.test.ts`.- `src/core/search/output-redaction.ts` — copies retrieval results and metadata before output sanitation, sharing the canonical `secret-scan.ts` plan and echo dictionary. Keyword, hybrid, image, exact and CRAG paths sanitize after internal grading/capture and before snippet truncation; CLI search/query JSON, explain and human rendering repeat the defense-in-depth pass. Every field is planned with `highEntropy: true`, so `KEY=value` assignments redact alongside the named shapes. Identity fields (`id`, `slug`, `source_id`, `page_id`, `chunk_id`, `message_id`, `thread_id`, `graph_session_prefix`, relational seed/path, `superseded_by`, `fact_id`, `entity_slug`) remain byte-identical: never put secrets in IDs. By default each field is capped at 64 Ki UTF-16 characters, the response at 1 Mi characters/8192 text fields, and nesting at 24 levels; oversized/unscannable text becomes `<REDACTED:output_limit>`. `RetrievalRedactionOpts.uncapped` scans every field whole (no `output_limit` replacement; one echo dictionary, every field planned before any write; the depth cap stays) and `verbatim` copies the named keys of each top-level result unscanned. `withOutputRedaction(op)` is the registration-time wrapper behind `Operation.outputRedaction` (`src/core/ops/contract.ts`): `operations.ts` wraps every `'retrieval'` op's handler once, so the CLI, stdio and HTTP MCP, subagent tools and `gbrain call` all pass the whole response (early returns included) through the uncapped redactor, linear in output size; `{ retrieval: { localVerbatim } }` leaves the named keys raw only when `ctx.remote === false`. The memory verbs: `recall`, `context_pack` and `delta` redact their presentation sets with one echo dictionary before packing, so budgets, `budget_used` and the delta cursor follow the delivered text, and their rendered `text` is never replaced by `output_limit`; facts (`fact`, `context`, `source`) are `localVerbatim`, so a remembered credential is readable raw only by the trusted local CLI on the brain host (stdio MCP and thin clients are remote). Handlers that clip or summarize stored text (transcript summaries, entity-card and compiled-context excerpts) redact the whole field before clipping. THREAT MODEL: this defends against accidental exposure of stored credentials into agent context and transcripts through retrieval ops. It does not cover the raw-read exemptions (`get_page`, `fetch`, `get_chunks`, `get_raw_data`, `get_versions`, the skill catalog, admin job ops), stored content (unchanged), or configured providers (embeddings at ingest, the hosted reranker, synthesis/think generation still receive unredacted text, except private keys, which the credential-safe projection keeps out of chunks). Unknown formats and short fragments can escape detection. This is output hygiene, not authorization or provider/eval no-egress. Tests: `test/search/output-redaction.serial.test.ts`, `test/search/output-redaction.test.ts`, `test/retrieval-op-redaction.test.ts` (every `'retrieval'` and `'no_stored_text'` op run through MCP dispatch with `remote = true` against a planted secret, plus the registration wrapper), `test/transcripts-redaction.test.ts`.@@ -67,9 +68,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/hub-dampening.ts` — `hubWeight(degree, H)` = 1 / (1 + ((max(n,1) − 1) / H)²), `'off'` → 1; `dampenBoost`, `normalizeHubDampening`. Pure; callers pass the caller-visible degree.-- `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/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..ee36bb1b0b 100644--- a/docs/architecture/key-files/core-services-2-continued.md+++ b/docs/architecture/key-files/core-services-2-continued.md@@ -18,3 +18,6 @@ The page-state concurrency foundation under `src/core/page-state/` and the share- `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-window/bounded-lead.ts` — leads, snippets and synopses read a bounded prefix, never the whole body: fan-out SQL selects `boundedBodyPrefixSql(alias)` (`left(coalesce(alias.compiled_truth, alias.truth_lead), 65536)`: a segmented page's NULL body falls back to its stored lead; the one COALESCE of body and lead the page body reader ratchet allows by name), `boundedRawPrefix` cuts a body at 64 KiB on a code point, and `overlaidBoundedRows` / `overlaidBoundedPrefix` replace a prefix holding a `gbrain:facts:begin` marker with the prefix of the withdrawal-overlaid body (one batched `readPageSnapshotsBatch` read; a page it no longer returns, or a failed read, gets an empty lead). A segmented page's row carries its stored `truth_lead`; when that lead holds a facts fence it is overlaid alone with the withdrawal ledger the snapshot read returns (`overlayCanonicalBodies`, then the same 64 KiB cut), never by reading segments. `pageLeadSource` gives getPage callers (exact-slug and alias snippets) a page's compiled truth, or a segmented page's `truth_lead` without touching its throwing body getters. `projectedLead` is that prefix through `boundedProjectedPrefix` (`document.ts`). Consumers: the exact-slug tier (`exact-lookup.ts`) and alias injection (`alias-hop.ts`) snippets, relational hydrate, the reflex pointer synopsis (`retrieval-reflex.ts` `safeSynopsis`: world-only reads take the projected prefix, the trusted entity-card widening the raw prefix through its own fence strip), the entity card's hit row and `entity names` leads, and think's anchor and window-floor rows (`think/gather.ts`: the raw overlaid prefix for the trusted local CLI, the projected prefix otherwise). Small pages render as before. Pinned by `test/bounded-lead.test.ts` and `test/large-pages/segmented-leads.test.ts`.+- `src/core/page-window/document.ts` — the one read projection every remote window, outline and lead slices: `projectPageText` (fence overlay split, `sanitizeRemoteBody` + `credentialSafeProjection`, timeline after `TIMELINE_SEPARATOR`), `pageDocument` / `readPageDocument` (UTF-8 bytes + timeline byte offset, with the page's fence overlay), `chunkDocumentSpan` + `spanHoldsChunk` (a chunk's stored `projected_byte_*` span mapped into the document and verified), `boundedProjectedPrefix`, `locateChunksByStoredSpans` (byte spans to string offsets in one pass), `DEFAULT_INLINE_BODY_BYTES` (256 KB).+- `src/core/page-window/window.ts` — byte/line window arithmetic on a UTF-8 buffer: windows snap to code points and line starts (`windowFrom`, `windowForLines`, `windowForBytes`, `windowAround`; a lone line longer than the window is cut on a code point as `forced_cut`), `pageOutline` (single pass: ATX headings outside code fences, or 64 KiB blocks for pages with fewer than two headings, with date ranges, paged by `from`/`limit`), and the opaque revision-bound cursor (`gpw1.`).diff --git a/docs/evidence-delivery.md b/docs/evidence-delivery.mdindex 44c3dcdff8..71cd5df9fa 100644--- a/docs/evidence-delivery.md+++ b/docs/evidence-delivery.md@@ -431,6 +431,7 @@ delivered text and each result gains `delivered`.| `no_section_structure` | `section` found no headings or speaker turns. | A `window` block (`delivered.unit: "window"`). || `no_text_chunks` / `anchor_not_located` | No hit could be placed in the page text: no text chunk was in reach and the hit text itself was not found, or none of the located chunks overlap a hit. | The hit chunk (a code chunk without its synthesized header line), `fallback_reason` set. || `page_missing` | A hit carried no page id (cannot be re-authorized by id). | The hit chunk (live hits only), `fallback_reason` set. |+| `segment_read_failed` | A page stored in segments could not be read around its hits (its stored projection metadata was unusable, or a segment read failed). | The hit chunk (live hits only; cached hits are dropped as `not_readable`), `fallback_reason` set. || `redaction_unmapped` | Secret redaction changed a block. | Redacted block; its spans move to `unmapped_chunk_ids`. || `image_query_unsupported` | `query` with `image`: image hits are never expanded. | Plain image results; meta says so. || `snippet_cap` | An explicit `snippet_chars` cut a block. | Capped block, `truncated: true`. |diff --git a/docs/guides/windowed-reads.md b/docs/guides/windowed-reads.mdindex ca5fbdbffd..071daca30f 100644--- a/docs/guides/windowed-reads.md+++ b/docs/guides/windowed-reads.md@@ -68,6 +68,14 @@ window around the hits, with `delivered.fallback_reason: "page_over_inline_bytesA truncated search snippet past the first chunk points at`get_page <slug> around_chunk_id=<id>`.+On a page stored in segments, an evidence block is read around its hits only:+each hit's window (its neighbor chunks, or its segment for `section`) comes+from the same per-segment read projection as a `get_page` window, so it costs+the windows, not the page. Hits far apart come back as one block of separate+windows joined by `[…]`. Search keeps up to two hits per region of such a page+(hits more than 1 MiB apart are separate regions) and at most six per page; an+inline page keeps two.+## PrivacyWindows, outlines and snippets for remote callers are slices of the readdiff --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..02e0f3b982 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -44,6 +44,6 @@ src/core/ops/pages.ts 707 ratchet crossed the unlisted 1500 cap in the fix wave: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.ts-src/core/search/evidence-delivery.ts 1673 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136)+src/core/search/evidence-delivery.ts 1712 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented pagesrc/commands/config.ts 1508 ratchet new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts)src/commands/mcp-expose.ts 1512 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts)diff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsvindex 2e3fdf947c..4dc3a043c9 100644--- a/scripts/page-body-readers-baseline.tsv+++ b/scripts/page-body-readers-baseline.tsv@@ -174,7 +174,7 @@ src/core/embed-stale-images.ts embedStaleImages sql INLINEsrc/core/embedding-migration-worst-case.ts REPROJECTED_PAGE sql METAsrc/core/embedding-readiness.ts countArchivedEmbeddingWork sql METAsrc/core/engine-sql/chunks.ts chunklessPagesWhere sql META lane 1e file: body <> '' predicate-src/core/engine-sql/chunks.ts getChunkWindows sql STREAM lane 1e file: ships whole bodies per hit; NULL for segmented (chunk windows by stored spans in PR 2)+src/core/engine-sql/chunks.ts getChunkWindows sql STREAM lane 1e file: ships whole bodies per hit for inline pages; a segmented page ships none (NULL) and its chunks carry occurrence_id + span, read by search/segmented-evidence.tssrc/core/engine-sql/chunks.ts listChunklessPagesWithContent field STREAM lane 1e filesrc/core/engine-sql/chunks.ts listChunklessPagesWithContent sql STREAM lane 1e filesrc/core/engine-sql/chunks.ts listEmbeddingStateRows sql META lane 1e file: octet_length metadata@@ -347,7 +347,8 @@ src/core/page-state/snapshot.ts readSnapshotStatement sql STREAM p.* feeds rowTosrc/core/page-state/versions.ts createPageVersion field SEGW lane 1e file: segmented versions reference a generationsrc/core/page-state/versions.ts createPageVersion sql SEGW lane 1e file: segmented versions reference a generationsrc/core/page-window/bounded-lead.ts overlaidBoundedPrefix field LEAD see overlaidBoundedRows-src/core/page-window/bounded-lead.ts overlaidBoundedRows field LEAD rows carry boundedBodyPrefixSql (truth_lead for segmented); a segmented page whose lead holds a facts fence gets an empty lead (fail closed)+src/core/page-window/bounded-lead.ts overlaidBoundedRows field LEAD rows carry boundedBodyPrefixSql (truth_lead for segmented); a segmented lead that holds a facts fence is overlaid alone with the ledger the snapshot read returns (no body read)+src/core/page-window/bounded-lead.ts pageLeadSource field LEAD getPage callers (exact-slug, alias snippets): compiled truth of an inline page; a segmented page reads its stored truth_leadsrc/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@@ -486,12 +487,10 @@ src/core/schema-pack/page-to-link.ts runPageToLinkCore field LEADsrc/core/schema-pack/page-to-link.ts runPageToLinkCore sql LEADsrc/core/search-vector-backfill.ts backfillPageVectors field LEADsrc/core/search-vector-backfill.ts backfillPageVectors sql LEAD-src/core/search/alias-hop.ts aliasInjectedRow field LEAD projectedLead over getPage: segmented page: getter throws page_body_segmented (lead source in PR 2)src/core/search/chunk-windows.ts mapChunkWindowRows field STREAMsrc/core/search/entity-anchor.ts entityAnchoredPages sql STREAM-src/core/search/evidence-delivery.ts deliverEvidence field STREAM+src/core/search/evidence-delivery.ts deliverEvidence field STREAM inline pages: the fence overlay over the whole body; a segmented page (no body) skips it and is planned from windows (search/segmented-evidence.ts)src/core/search/evidence-delivery.ts selectLongPages sql META sizes a segmented page from its NULL body (0), so it is never selected as a long page; moves to body_bytes-src/core/search/exact-lookup.ts structuralExactLookup field LEAD projectedLead over getPage: segmented page: getter throws page_body_segmented (lead source in PR 2)src/core/search/provenance-demotion.ts applyGeneratedDemotion field LEADsrc/core/search/provenance-demotion.ts applyGeneratedDemotion sql LEADsrc/core/search/read-enrichment.ts readAliases sql NONE not the page body: SELECT * FROM pages used for identity columnsdiff --git a/src/core/engine-sql/chunks.ts b/src/core/engine-sql/chunks.tsindex 901e94570e..68736fe864 100644--- a/src/core/engine-sql/chunks.ts+++ b/src/core/engine-sql/chunks.ts@@ -1029,9 +1029,12 @@ export async function getEmbeddingsByChunkIds(exec: LegacyUnscopedRead, ids: num* page_id. Every requested page is re-authorized with the search legs'* visibility predicate (source scope, deleted, current text projection,* archived source, quarantine, private pages, safe chunks); pages that fail- * are absent. Page rows carry the raw body columns (the assembler sanitizes- * them whole before slicing); chunk rows (sealed pages only) anchor the hits- * in that text. Page rows and chunk+ * are absent. Page rows of inline pages carry the raw body columns (the+ * assembler sanitizes them whole before slicing); a segmented page's row says+ * `segmented` and carries no body, and its chunk rows carry their occurrence+ * and segment-relative projected span, the references the assembler reads+ * windows around (page-body/read-range.ts). Chunk rows (sealed pages only)+ * anchor the hits. Page rows and chunk* rows come back in one UNION so the row cap never hides a page's* authorization.*/@@ -1049,7 +1052,7 @@ export async function getChunkWindows(exec: ScopedRead, requests: ChunkWindowReq${requests.map(r => r.to_index)}::int[], ${requests.map(r => r.priority)}::int[]) AS r(page_id, lo, hi, prio)), auth AS (SELECT p.id, p.slug, p.source_id, p.type, p.knowledge_revision::text AS revision, p.compiled_truth, p.timeline, p.body_generation,- (COALESCE(p.chunker_version, 0) >= ${SAFE_FENCE_CHUNKER_VERSION}) AS sealed,+ p.body_storage = 'segmented' AS segmented, (COALESCE(p.chunker_version, 0) >= ${SAFE_FENCE_CHUNKER_VERSION}) AS sealed,(SELECT MIN(req.prio) FROM req WHERE req.page_id = p.id) AS prioFROM pages pJOIN sources s ON s.id = p.source_id@@ -1057,7 +1060,7 @@ export async function getChunkWindows(exec: ScopedRead, requests: ChunkWindowReqAND p.deleted_at IS NULL AND ${trustedSql(currentTextProjectionFilter('p'))} AND NOT s.archivedAND ${trustedSql(QUARANTINE_FILTER_FRAGMENT)} ${privateSql} ${safeSql}), chunk_rows AS (- SELECT cc.page_id, cc.id AS chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.projected_byte_start, cc.projected_byte_end, a.prio+ SELECT cc.page_id, cc.id AS chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.projected_byte_start, cc.projected_byte_end, cc.occurrence_id, a.prioFROM auth aJOIN content_chunks cc ON cc.page_id = a.idWHERE a.sealed AND ${trustedSql(chunkGenerationFilter('a', 'cc'))}@@ -1067,15 +1070,15 @@ export async function getChunkWindows(exec: ScopedRead, requests: ChunkWindowReqORDER BY a.prio, cc.page_id, cc.chunk_indexLIMIT ${maxRows + 1})- SELECT 'page' AS kind, a.id AS page_id, a.slug, a.source_id, a.type, a.revision, a.sealed, a.prio,+ SELECT 'page' AS kind, a.id AS page_id, a.slug, a.source_id, a.type, a.revision, a.sealed, a.segmented, a.prio,(SELECT MAX(c2.chunk_index) FROM content_chunks c2 WHERE c2.page_id = a.id AND ${trustedSql(chunkGenerationFilter('a', 'c2'))}) AS max_chunk_index,a.compiled_truth, a.timeline,NULL::int AS chunk_id, NULL::int AS chunk_index, NULL::text AS chunk_text, NULL::text AS chunk_source,- NULL::bigint AS projected_byte_start, NULL::bigint AS projected_byte_end+ NULL::bigint AS projected_byte_start, NULL::bigint AS projected_byte_end, NULL::bigint AS occurrence_idFROM auth aUNION ALL- SELECT 'chunk' AS kind, c.page_id, NULL, NULL, NULL, NULL, NULL, c.prio,- NULL, NULL, NULL, c.chunk_id, c.chunk_index, c.chunk_text, c.chunk_source, c.projected_byte_start, c.projected_byte_end+ SELECT 'chunk' AS kind, c.page_id, NULL, NULL, NULL, NULL, NULL, NULL, c.prio,+ NULL, NULL, NULL, c.chunk_id, c.chunk_index, c.chunk_text, c.chunk_source, c.projected_byte_start, c.projected_byte_end, c.occurrence_idFROM chunk_rows c`);return mapChunkWindowRows(rows, maxRows);diff --git a/src/core/page-window/bounded-lead.ts b/src/core/page-window/bounded-lead.tsindex 4f5bf6bca4..2e738f4384 100644--- a/src/core/page-window/bounded-lead.ts+++ b/src/core/page-window/bounded-lead.ts@@ -14,13 +14,17 @@* snapshot read (the same overlay readPageSnapshot applies), so a withdrawn* world fact never shows in a lead. A page the snapshot read no longer* returns, or a snapshot read that fails, gets an empty lead (fail closed:- * a lead is decoration, so the row stays and only its text is withheld). So- * does a segmented page whose lead holds a facts fence: its overlay applies- * per window (segment reader), not to a snapshot body.+ * a lead is decoration, so the row stays and only its text is withheld).+ * A segmented page has no snapshot body: its row carries the stored+ * `truth_lead` (the same raw prefix), and a lead that holds a facts fence is+ * overlaid alone with the page's withdrawal ledger (the snapshot read returns+ * the ledger and no body), never by reading the page's segments.*/import type { BrainEngine } from '../engine.ts';+import type { Page } from '../types.ts';import { isSegmentedPage } from '../page-body/page-shape.ts';import { pageSnapshotKey } from '../page-snapshot-batch.ts';+import { overlayCanonicalBodies } from '../page-state/snapshot.ts';import { safeSplitIndex } from '../text-safe.ts';import { BOUNDED_PREFIX_BYTES, boundedProjectedPrefix } from './document.ts';@@ -54,23 +58,28 @@ export function prefixNeedsOverlay(prefix: string | null | undefined): boolean {/*** Bounds each row's `compiled_truth` to the raw prefix and, for rows whose* prefix holds a facts fence, replaces it with the prefix of the- * withdrawal-overlaid body (one batched snapshot read for all of them).+ * withdrawal-overlaid body (one batched snapshot read for all of them; a+ * segmented page's lead is overlaid alone with its ledger).* Returns new row objects; the input rows are not mutated.*/export async function overlaidBoundedRows<T extends { slug: string; source_id: string; compiled_truth: string | null }>(- engine: Pick<BrainEngine, 'readPageSnapshotsBatch'>,+ engine: Pick<BrainEngine, 'readPageSnapshotsBatch' | 'executeRaw'>,rows: readonly T[],): Promise<T[]> {const bounded = rows.map(row => ({ ...row, compiled_truth: row.compiled_truth == null ? null : boundedRawPrefix(row.compiled_truth) }));+ const leads = new Map(bounded.filter(row => prefixNeedsOverlay(row.compiled_truth)).map(row => [pageSnapshotKey(row.source_id, row.slug), row.compiled_truth!]));const pending = [...new Map(bounded.filter(row => prefixNeedsOverlay(row.compiled_truth)).map(row => [pageSnapshotKey(row.source_id, row.slug), { slug: row.slug, sourceId: row.source_id }])).values()];if (pending.length === 0) return bounded;const overlaid = new Map<string, string>();+ const query = <R>(sql: string, params?: unknown[]) => engine.executeRaw<R>(sql, params);try {for (let rest = pending; rest.length > 0;) {const batch = await engine.readPageSnapshotsBatch(rest);for (const [key, snapshot] of batch.snapshots) {if (!isSegmentedPage(snapshot.page)) overlaid.set(key, boundedRawPrefix(snapshot.page.compiled_truth));+ else overlaid.set(key, boundedRawPrefix((await overlayCanonicalBodies(query, leads.get(key)!, '', snapshot.withdrawals,+ { sourceId: snapshot.page.source_id, marker: snapshot.globalPurges })).compiled_truth));}rest = rest.slice(Math.max(1, batch.covered));}@@ -84,7 +93,7 @@ export async function overlaidBoundedRows<T extends { slug: string; source_id: s/** One page's overlaid raw prefix: the snapshot body when the raw prefix holds a facts fence, else the raw prefix. */export async function overlaidBoundedPrefix(- engine: Pick<BrainEngine, 'readPageSnapshotsBatch'>,+ engine: Pick<BrainEngine, 'readPageSnapshotsBatch' | 'executeRaw'>,page: { slug: string; source_id: string; compiled_truth: string | null },): Promise<string> {const [row] = await overlaidBoundedRows(engine, [page]);@@ -93,8 +102,15 @@ export async function overlaidBoundedPrefix(/** One page's sanitized, credential-projected lead text: the bounded overlaid prefix through boundedProjectedPrefix. */export async function projectedLead(- engine: Pick<BrainEngine, 'readPageSnapshotsBatch'>,+ engine: Pick<BrainEngine, 'readPageSnapshotsBatch' | 'executeRaw'>,page: { slug: string; source_id: string; compiled_truth: string | null },): Promise<string> {return boundedProjectedPrefix(await overlaidBoundedPrefix(engine, page));}++/** The raw lead source of a page read whole (getPage): its compiled truth, or a segmented page's stored `truth_lead` (its body fields throw). */+export async function pageLeadSource(engine: Pick<BrainEngine, 'executeRaw'>, page: Pick<Page, 'id' | 'body_storage' | 'compiled_truth'>): Promise<string | null> {+ if (!isSegmentedPage(page)) return page.compiled_truth;+ const [row] = await engine.executeRaw<{ truth_lead: string | null }>('SELECT truth_lead FROM pages WHERE id = $1', [page.id]);+ return row?.truth_lead ?? null;+}diff --git a/src/core/search/alias-hop.ts b/src/core/search/alias-hop.tsindex a3b382d32f..6555007e76 100644--- a/src/core/search/alias-hop.ts+++ b/src/core/search/alias-hop.ts@@ -5,7 +5,7 @@*/import type { SearchResult } from '../types.ts';-import { projectedLead } from '../page-window/bounded-lead.ts';+import { pageLeadSource, projectedLead } from '../page-window/bounded-lead.ts';import { isIdentityEntity } from '../entities/resolve.ts';import { normalizeAlias } from './alias-normalize.ts';import { isPrivatePage } from './private-visibility.ts';@@ -235,7 +235,7 @@ async function aliasInjectedRow(engine: import('../engine.ts').BrainEngine, pagetype: page.type,source_id: page.source_id ?? ref.source_id,// Large pages: a bounded, withdrawal-overlaid prefix is sanitized, never the whole body.- chunk_text: (await projectedLead(engine, { slug: page.slug, source_id: page.source_id ?? ref.source_id, compiled_truth: page.compiled_truth })).slice(0, 200),+ chunk_text: (await projectedLead(engine, { slug: page.slug, source_id: page.source_id ?? ref.source_id, compiled_truth: await pageLeadSource(engine, page) })).slice(0, 200),chunk_index: 0,chunk_id: 0,score,diff --git a/src/core/search/chunk-windows.ts b/src/core/search/chunk-windows.tsindex b8bc2d502b..1a57ef2ca3 100644--- a/src/core/search/chunk-windows.ts+++ b/src/core/search/chunk-windows.ts@@ -7,9 +7,11 @@* Every requested page is re-authorized under the caller's CURRENT read* scope with the same predicate the search legs use (source scope, deleted,* text projection, archived source, quarantine, private pages, safe chunks);- * a page that fails is simply absent from the result. Page rows carry the- * raw body (the assembler sanitizes it whole); chunk rows are read only for- * sealed pages and anchor the hits in that text.+ * a page that fails is simply absent from the result. Inline page rows carry+ * the raw body (the assembler sanitizes it whole); a segmented page carries+ * none, and its chunks' occurrence and segment-relative projected span are+ * the references the assembler reads windows around. Chunk rows are read+ * only for sealed pages and anchor the hits.*/import type { PageReadScope } from '../types.ts';import type { FenceChunkOverlay } from '../eligibility/fence-overlay.ts';@@ -28,9 +30,11 @@ export interface ChunkWindowChunk {chunk_index: number;chunk_text: string;chunk_source: string;- /** Large pages: the chunk's UTF-8 byte span in its source's read projection, when recorded. */+ /** Large pages: the chunk's UTF-8 byte span in its source's read projection, when recorded (on a segmented page, in its occurrence's projection). */projected_byte_start?: number | null;projected_byte_end?: number | null;+ /** Segmented pages: the manifest occurrence the chunk was cut from. */+ occurrence_id?: number;}export interface ChunkWindowPage {@@ -42,6 +46,8 @@ export interface ChunkWindowPage {revision: string;/** False when the page's chunks predate the protected-body index. */sealed: boolean;+ /** A segmented page: no body columns (''); its chunks carry occurrence references. */+ segmented?: true;/** The stored body columns (raw; the assembler sanitizes them whole). */compiled_truth: string;timeline: string;@@ -68,7 +74,8 @@ export function mapChunkWindowRows(rows: Record<string, unknown>[], maxRows: numconst chunkRows = rows.filter(r => r.kind === 'chunk').map(r => ({ page_id: Number(r.page_id), id: Number(r.chunk_id), chunk_index: Number(r.chunk_index), chunk_text: String(r.chunk_text ?? ''), chunk_source: String(r.chunk_source), prio: Number(r.prio),- projected_byte_start: r.projected_byte_start == null ? null : Number(r.projected_byte_start), projected_byte_end: r.projected_byte_end == null ? null : Number(r.projected_byte_end) }))+ projected_byte_start: r.projected_byte_start == null ? null : Number(r.projected_byte_start), projected_byte_end: r.projected_byte_end == null ? null : Number(r.projected_byte_end),+ occurrence_id: r.occurrence_id == null ? null : Number(r.occurrence_id) })).sort((a, b) => a.prio - b.prio || a.page_id - b.page_id || a.chunk_index - b.chunk_index);for (const r of rows) {if (r.kind !== 'page') continue;@@ -79,6 +86,7 @@ export function mapChunkWindowRows(rows: Record<string, unknown>[], maxRows: numtype: String(r.type),revision: String(r.revision),sealed: r.sealed === true || r.sealed === 't',+ ...(r.segmented === true || r.segmented === 't' ? { segmented: true as const } : {}),compiled_truth: String(r.compiled_truth ?? ''),timeline: String(r.timeline ?? ''),max_chunk_index: r.max_chunk_index == null ? -1 : Number(r.max_chunk_index),@@ -90,7 +98,8 @@ export function mapChunkWindowRows(rows: Record<string, unknown>[], maxRows: numconst limited = chunkRows.length > maxRows;const kept = limited ? chunkRows.slice(0, maxRows) : chunkRows;for (const c of kept) pages.get(c.page_id)?.chunks.push({ id: c.id, chunk_index: c.chunk_index, chunk_text: c.chunk_text, chunk_source: c.chunk_source,- ...(c.projected_byte_start != null && c.projected_byte_end != null ? { projected_byte_start: c.projected_byte_start, projected_byte_end: c.projected_byte_end } : {}) });+ ...(c.projected_byte_start != null && c.projected_byte_end != null ? { projected_byte_start: c.projected_byte_start, projected_byte_end: c.projected_byte_end } : {}),+ ...(c.occurrence_id != null ? { occurrence_id: c.occurrence_id } : {}) });if (limited) {const cutoff = chunkRows[maxRows];for (const p of pages.values()) {diff --git a/src/core/search/dedup.ts b/src/core/search/dedup.tsindex 5d4d94d9e3..567b171b21 100644--- a/src/core/search/dedup.ts+++ b/src/core/search/dedup.ts@@ -9,6 +9,13 @@* 5. Compiled truth guarantee: ensure at least 1 compiled_truth chunk per page* (appended, never evicting a kept chunk; the output is re-sorted by score)*+ * Segmented pages (Wave B, spec 7.5): a page stored in segments counts each+ * occurrence cluster (occurrences more than SEGMENT_CLUSTER_BYTES apart are+ * separate regions) as a page in layers 1 and 4, so far-apart regions of one+ * large page each keep up to N chunks, at most MAX_PER_SEGMENTED_PAGE in all.+ * The caller passes the occurrence positions (`regions`, segmentRegions);+ * without them, and for every inline page, nothing changes.+ ** v0.18.0: every page key is composite (source_id, slug). Pre-v0.17 this* was slug alone — under multi-source uniqueness that would collapse two* same-slug pages in different sources into one, destroying recall.@@ -18,11 +25,17 @@* to fix.*/+import type { BrainEngine } from '../engine.ts';import type { SearchResult } from '../types.ts';+import { chunkManifestJoin, chunkVisibleFilter } from './safe-chunks.ts';const COSINE_DEDUP_THRESHOLD = 0.85;const MAX_TYPE_RATIO = 0.6;const MAX_PER_PAGE = 2;+/** Chunks one segmented page may keep across its occurrence clusters. */+export const MAX_PER_SEGMENTED_PAGE = 6;+/** Stored bytes between two occurrences of a segmented page beyond which they are separate regions. */+export const SEGMENT_CLUSTER_BYTES = 1024 * 1024;/*** Composite page key: (source_id, slug). Pre-v0.17 rows lacked source_id@@ -35,25 +48,80 @@ function pageKey(r: SearchResult): string {return `${source}:${r.slug}`;}+/**+ * Occurrence positions of the chunks of segmented pages among `results`, for+ * dedupResults' `regions`: chunk id -> stored byte where the chunk's live+ * occurrence starts. One query, run only when some page has more results+ * than MAX_PER_PAGE (otherwise the region rule changes nothing); a failed+ * read leaves every page under the inline rule.+ */+export async function segmentRegions(engine: Pick<BrainEngine, 'executeRaw'>, results: readonly SearchResult[]): Promise<Map<number, number>> {+ const counts = new Map<string, number>();+ for (const r of results) counts.set(pageKey(r), (counts.get(pageKey(r)) ?? 0) + 1);+ const ids = results.filter(r => counts.get(pageKey(r))! > MAX_PER_PAGE && r.chunk_id > 0).map(r => r.chunk_id);+ if (ids.length === 0) return new Map();+ try {+ const rows = await engine.executeRaw<{ id: number; byte_start: number | string }>(`SELECT cc.id, m.byte_start FROM content_chunks cc+ JOIN pages p ON p.id = cc.page_id AND p.body_storage = 'segmented'+ ${chunkManifestJoin('p', 'cc', 'm')}+ WHERE cc.id = ANY($1::int[]) AND m.byte_start IS NOT NULL AND ${chunkVisibleFilter('p', 'cc')}`, [ids]);+ return new Map(rows.map(r => [Number(r.id), Number(r.byte_start)]));+ } catch {+ return new Map();+ }+}++/**+ * The dedup key of each result: its page, or for a segmented page (a chunk with a region) its page and occurrence+ * cluster. Clusters are single-linkage over the page's occurrence positions in `results`: sorted, a gap over+ * SEGMENT_CLUSTER_BYTES starts a new one. A segmented page's result with no region is a region of its own.+ */+function regionKeys(results: readonly SearchResult[], regions: ReadonlyMap<number, number>): Map<SearchResult, string> {+ const positions = new Map<string, number[]>();+ for (const r of results) {+ const at = regions.get(r.chunk_id);+ if (at !== undefined) positions.set(pageKey(r), [...(positions.get(pageKey(r)) ?? []), at]);+ }+ const clusterOf = new Map<string, Map<number, number>>();+ for (const [page, list] of positions) {+ const sorted = [...new Set(list)].sort((a, b) => a - b);+ const ids = new Map<number, number>();+ let cluster = 0;+ sorted.forEach((at, i) => { if (i > 0 && at - sorted[i - 1]! > SEGMENT_CLUSTER_BYTES) cluster++; ids.set(at, cluster); });+ clusterOf.set(page, ids);+ }+ const keys = new Map<SearchResult, string>();+ for (const r of results) {+ const page = pageKey(r);+ const ids = clusterOf.get(page);+ keys.set(r, ids ? `${page}#${regions.has(r.chunk_id) ? ids.get(regions.get(r.chunk_id)!) : `chunk:${r.chunk_id}`}` : page);+ }+ return keys;+}+export function dedupResults(results: SearchResult[],opts?: {cosineThreshold?: number;maxTypeRatio?: number;maxPerPage?: number;+ /** Segmented pages: chunk id -> stored byte of its occurrence (segmentRegions). */+ regions?: ReadonlyMap<number, number>;},): SearchResult[] {const threshold = opts?.cosineThreshold ?? COSINE_DEDUP_THRESHOLD;const maxRatio = opts?.maxTypeRatio ?? MAX_TYPE_RATIO;const maxPerPage = opts?.maxPerPage ?? MAX_PER_PAGE;+ const keys = opts?.regions?.size ? regionKeys(results, opts.regions) : undefined;+ const regionKey = (r: SearchResult) => keys?.get(r) ?? pageKey(r);// Preserve pre-dedup input for compiled truth guaranteeconst preDedup = results;let deduped = results;- // Layer 1: Top 3 chunks per page by score- deduped = dedupBySource(deduped);+ // Layer 1: Top 3 chunks per page (per region of a segmented page) by score+ deduped = dedupBySource(deduped, regionKey);// Layer 2: Text similarity dedup (Jaccard on word sets)deduped = dedupByTextSimilarity(deduped, threshold);@@ -61,8 +129,8 @@ export function dedupResults(// Layer 3: Type diversity (no page type exceeds 60%)deduped = enforceTypeDiversity(deduped, maxRatio);- // Layer 4: Cap chunks per page- deduped = capPerPage(deduped, maxPerPage);+ // Layer 4: Cap chunks per page (per region of a segmented page, MAX_PER_SEGMENTED_PAGE per page)+ deduped = capPerPage(deduped, maxPerPage, regionKey);// Final pass: guarantee compiled_truth representation, then restore score// order (downstream slice / token budget / evidence assume it).@@ -75,11 +143,11 @@ export function dedupResults(* Layer 1: Keep top 3 chunks per page.* Later layers (text similarity, cap per page) handle further reduction.*/-function dedupBySource(results: SearchResult[]): SearchResult[] {+function dedupBySource(results: SearchResult[], keyOf: (r: SearchResult) => string): SearchResult[] {const byPage = new Map<string, SearchResult[]>();for (const r of results) {- const k = pageKey(r);+ const k = keyOf(r);const existing = byPage.get(k) || [];existing.push(r);byPage.set(k, existing);@@ -168,16 +236,20 @@ function enforceTypeDiversity(results: SearchResult[], maxRatio: number): Search/*** Layer 4: Cap chunks per page.*/-function capPerPage(results: SearchResult[], maxPerPage: number): SearchResult[] {+function capPerPage(results: SearchResult[], maxPerPage: number, keyOf: (r: SearchResult) => string): SearchResult[] {const pageCounts = new Map<string, number>();+ const regionCounts = new Map<string, number>();const kept: SearchResult[] = [];for (const r of results) {- const k = pageKey(r);- const count = pageCounts.get(k) || 0;- if (count < maxPerPage) {+ const page = pageKey(r);+ const k = keyOf(r);+ const count = regionCounts.get(k) || 0;+ const total = pageCounts.get(page) || 0;+ if (count < maxPerPage && (k === page || total < Math.max(MAX_PER_SEGMENTED_PAGE, maxPerPage))) {kept.push(r);- pageCounts.set(k, count + 1);+ regionCounts.set(k, count + 1);+ pageCounts.set(page, total + 1);}}diff --git a/src/core/search/evidence-delivery.ts b/src/core/search/evidence-delivery.tsindex 33bd3430a5..2432da4348 100644--- a/src/core/search/evidence-delivery.ts+++ b/src/core/search/evidence-delivery.ts@@ -13,7 +13,9 @@* protected-body boundary before any slicing (a slice can cut a fence and* read as a protected tail), fetched with the hit chunks in one batched* `getChunkWindows` call that re-authorizes every page under the caller's- * current read scope. Chunks only anchor hits in that text.+ * current read scope. Chunks only anchor hits in that text. A segmented page+ * has no such text: its windows are read around the hits through the segment+ * reader (segmented-evidence.ts) and joined as separate runs.** The normative algorithm (page text, units, allocation, spans) is specified* in docs/evidence-delivery.md; gbrain-evals measures exactly this code.@@ -32,6 +34,7 @@ import { resolveExcludePrivatePages } from './private-visibility.ts';import { safeSplitIndex } from '../text-safe.ts';import { loadFenceChunkOverlay, type FenceChunkOverlay } from '../eligibility/fence-overlay.ts';import { DEFAULT_INLINE_BODY_BYTES, locateChunksByStoredSpans, projectPageText, TIMELINE_SEPARATOR } from '../page-window/document.ts';+import { readSegmentedWindows } from './segmented-evidence.ts';import { stripChunkHeader } from '../chunkers/code.ts';import { OperationError } from '../ops/contract.ts';import { blockDateHeaders, evidenceDateHeaderEnabled } from './evidence-date.ts';@@ -684,12 +687,13 @@ export function pageEvidenceText(page: { compiled_truth: string; timeline: strinreturn projectPageText(page, includeTimeline);}-function locateAnchor(doc: Doc, hit: SearchResult, fold: boolean): Anchor {+/** `placed` (segmented pages): where the hits without a stored span were found; the text is then never searched. */+function locateAnchor(doc: Doc, hit: SearchResult, fold: boolean, placed?: ReadonlyMap<number, { start: number; end: number }>): Anchor {const byId = hit.chunk_id > 0 ? doc.spans.find(x => x.id === hit.chunk_id) : undefined;if (byId) return { chunk_id: hit.chunk_id, mapped: true, pieces: piecesOverlapping(doc, byId.start, byId.end), start: byId.start, end: byId.end, chunkIndex: byId.chunk_index };const text = hitPageText(hit).trim();- if (text.length >= 16) {- const found = locateChunks(doc.text, [{ id: hit.chunk_id, chunk_index: hit.chunk_index, chunk_text: text }], fold)[0];+ if (placed || text.length >= 16) {+ const found = placed ? placed.get(hit.chunk_id) : locateChunks(doc.text, [{ id: hit.chunk_id, chunk_index: hit.chunk_index, chunk_text: text }], fold)[0];if (found) {// A fenced_code chunk_index follows every prose chunk, so it says nothing// about position: the window grows from the prose chunk holding the fence,@@ -731,14 +735,19 @@ function sectionCandidates(doc: Doc, anchors: Anchor[], conversation: boolean):if (a.pieces.length === 0) continue;const first = a.pieces[0];const last = a.pieces[a.pieces.length - 1];- let start = 0;+ // A section never leaves its run (a segmented page's window): the text between runs was not read.+ let lo = first;+ while (lo > 0 && doc.pieces[lo - 1].run === doc.pieces[first].run) lo--;+ let hi = last;+ while (hi + 1 < doc.pieces.length && doc.pieces[hi + 1].run === doc.pieces[last].run) hi++;+ let start = lo;let level = 0;- for (let i = first; i >= 0; i--) {+ for (let i = first; i >= lo; i--) {const p = doc.pieces[i];if (conversation ? p.speaker === opener : p.heading > 0) { start = i; level = conversation ? 0 : p.heading; break; }}- let end = doc.pieces.length - 1;- for (let i = last + 1; i < doc.pieces.length; i++) {+ let end = hi;+ for (let i = last + 1; i <= hi; i++) {const p = doc.pieces[i];if (conversation ? p.speaker === opener : p.heading > 0 && (level === 0 || p.heading <= level)) { end = i - 1; break; }}@@ -766,7 +775,34 @@ function planBlock(page: ChunkWindowPage, hits: SearchResult[], requested: Exclu...(timelineAt < 0 ? [] : locateChunks(text.slice(timelineAt), timelineChunks).map(sp => ({ ...sp, start: sp.start + timelineAt, end: sp.end + timelineAt }))),];const doc = buildDoc(text, spans);- const anchors = hits.map(h => locateAnchor(doc, h, textBytes <= SPAN_ONLY_LOCATE_BYTES));+ return blockFromDoc(page, hits, doc, hits.map(h => locateAnchor(doc, h, textBytes <= SPAN_ONLY_LOCATE_BYTES)), requested, radius, textBytes > DEFAULT_INLINE_BODY_BYTES);+}++/**+ * planBlock for a segmented page (spec 7.4): the same units over the windows readSegmentedWindows reads around the+ * hits, never a page text, a whole-page projection or a text search. Each window is a run of the document: emission+ * marks the gap between two runs and a section never crosses one.+ */+async function planSegmentedBlock(engine: BrainEngine, page: ChunkWindowPage, hits: SearchResult[], requested: Exclude<ReturnUnit, 'chunk' | 'auto'>, radius: number, includeTimeline: boolean): Promise<PlannedBlock> {+ const best = hits[0];+ if (!page.sealed) return fallbackBlock(best, hits, 'unsealed_page');+ if (page.chunks.length === 0 && page.row_limited) return fallbackBlock(best, hits, 'row_limit');+ const read = await readSegmentedWindows(engine, page, hits.map(h => ({ chunk_id: h.chunk_id, chunk_index: h.chunk_index, text: hitPageText(h) })),+ { unit: requested, radius, includeTimeline });+ const doc: Doc = { text: '', pieces: [], spans: [] };+ const placed = new Map<number, { start: number; end: number }>();+ read.runs.forEach((run, k) => {+ const base = doc.text.length;+ for (const p of buildDoc(run.text, []).pieces) doc.pieces.push({ ...p, run: k, start: p.start + base, end: p.end + base });+ for (const sp of run.spans) doc.spans.push({ ...sp, start: sp.start + base, end: sp.end + base });+ for (const [id, at] of read.placed) if (at.run === k) placed.set(id, { start: at.start + base, end: at.end + base });+ doc.text += run.text;+ });+ return blockFromDoc(page, hits, doc, hits.map(h => locateAnchor(doc, h, false, placed)), requested, radius, read.overInline);+}++function blockFromDoc(page: ChunkWindowPage, hits: SearchResult[], doc: Doc, anchors: Anchor[], requested: Exclude<ReturnUnit, 'chunk' | 'auto'>, radius: number, overInline: boolean): PlannedBlock {+ const best = hits[0];if (anchors.every(a => a.pieces.length === 0)) {return fallbackBlock(best, hits, page.row_limited ? 'row_limit' : page.chunks.length === 0 ? 'no_text_chunks' : 'anchor_not_located');}@@ -777,7 +813,7 @@ function planBlock(page: ChunkWindowPage, hits: SearchResult[], requested: Exclulet fallbackReason: string | undefined;let candidates: number[];// Large pages (T18): a page over the inline read size is never delivered whole; it becomes the window around its hits.- if (unit === 'page' && textBytes > DEFAULT_INLINE_BODY_BYTES) { unit = 'window'; fallbackReason = PAGE_OVER_INLINE_BYTES; }+ if (unit === 'page' && overInline) { unit = 'window'; fallbackReason = PAGE_OVER_INLINE_BYTES; }if (unit === 'page') {candidates = doc.pieces.map((_, i) => i);} else if (unit === 'section') {@@ -950,7 +986,7 @@ function selectionCost(b: Block, sel: Set<number>, tokenizer: 'cl100k' | 'heurislet tokens = 0;let chars = 0;order.forEach((i, k) => {- const gap = k > 0 && order[k - 1] !== i - 1;+ const gap = k > 0 && !(order[k - 1] === i - 1 && b.doc.pieces[i - 1].run === b.doc.pieces[i].run);tokens += tok(b, i, tokenizer) + (gap ? omitTok : 0);chars += b.doc.pieces[i].text.length + (gap ? EVIDENCE_OMISSION.length : 0);});@@ -1207,7 +1243,7 @@ export async function deliverEvidence(chunkSources: scope.detail === 'low' ? ['compiled_truth'] : ['compiled_truth', 'timeline'],maxRows: Math.min(MAX_ROWS, requests.reduce((n, r) => n + (r.to_index - r.from_index + 1), 0)),}), timeoutMs);- for (const p of rows) p.fenceOverlay = await loadFenceChunkOverlay(engine, { sourceId: p.source_id, slug: p.slug, compiled_truth: p.compiled_truth, timeline: p.timeline });+ for (const p of rows) if (!p.segmented) p.fenceOverlay = await loadFenceChunkOverlay(engine, { sourceId: p.source_id, slug: p.slug, compiled_truth: p.compiled_truth, timeline: p.timeline });return new Map(rows.map(p => [p.page_id, p]));} catch (e) {return e instanceof EvidenceTimeout ? 'fetch_timeout' : 'fetch_failed';@@ -1251,7 +1287,10 @@ export async function deliverEvidence(} else {const page = pages?.get(g.pageId);if (!page) { dropped.not_readable = (dropped.not_readable ?? 0) + 1; continue; }- b = planBlock(page, g.hits, plan.unit === 'auto' ? 'page' : plan.unit, plan.window, scope.detail !== 'low');+ const unit = plan.unit === 'auto' ? 'page' : plan.unit;+ const read = page.segmented ? await planSegmentedBlock(engine, page, g.hits, unit, plan.window, scope.detail !== 'low').catch(() => null) : planBlock(page, g.hits, unit, plan.window, scope.detail !== 'low');+ if (!read && opts.liveHits === false) { dropped.not_readable = (dropped.not_readable ?? 0) + 1; continue; }+ b = read ?? fallbackBlock(g.hits[0], g.hits, 'segment_read_failed');}if (b.fallbackReason) fallbacks.add(b.fallbackReason);const title = b.hit.title ?? '';diff --git a/src/core/search/exact-lookup.ts b/src/core/search/exact-lookup.tsindex e69deaae9c..98544fbce2 100644--- a/src/core/search/exact-lookup.ts+++ b/src/core/search/exact-lookup.ts@@ -31,7 +31,7 @@* Fail-open everywhere: a probe error returns the organic results unchanged.*/-import { projectedLead } from '../page-window/bounded-lead.ts';+import { pageLeadSource, projectedLead } from '../page-window/bounded-lead.ts';import { hasReadPolicy } from './read-policy-sql.ts';import type { BrainEngine } from '../engine.ts';import type { SearchResult, PageReadPolicy } from '../types.ts';@@ -130,7 +130,7 @@ export async function structuralExactLookup(type: page.type,source_id: page.source_id ?? scope ?? 'default',// Large pages: a bounded, withdrawal-overlaid prefix is sanitized, never the whole body.- chunk_text: (await projectedLead(engine, { slug: page.slug, source_id: page.source_id ?? scope ?? 'default', compiled_truth: page.compiled_truth })).slice(0, 200),+ chunk_text: (await projectedLead(engine, { slug: page.slug, source_id: page.source_id ?? scope ?? 'default', compiled_truth: await pageLeadSource(engine, page) })).slice(0, 200),chunk_index: 0,chunk_id: 0,score: 0, // caller assigns the injection scorediff --git a/src/core/search/hybrid.ts b/src/core/search/hybrid.tsindex f8d522f558..a0f99ecdc5 100644--- a/src/core/search/hybrid.ts+++ b/src/core/search/hybrid.ts@@ -27,7 +27,7 @@ import { loadEmbeddingQueryPrefix } from './query-prefix.ts';import { registerBackgroundWorkDrainer } from '../background-work.ts';import { applyAliasHop, isExcludedIdentity, type IdentityTierOpts } from './alias-hop.ts';export { applyAliasHop, isExcludedIdentity, type IdentityTierOpts };-import { dedupResults } from './dedup.ts';+import { dedupResults, segmentRegions } from './dedup.ts';import { accumulateRrf, type RrfEntry } from './rrf-page-fusion.ts';import type { RrfAttribution } from '../types.ts';import {@@ -1170,7 +1170,7 @@ export async function hybridSearch(// aliasing in the postFusionOpts resolver near line ~256.// Dedup- const deduped = await timer.stage('post_fusion', async () => capSessionPool(req, dedupResults(fused, dedupOpts)));+ const deduped = await timer.stage('post_fusion', async () => capSessionPool(req, dedupResults(fused, { ...dedupOpts, regions: await segmentRegions(req.engine, fused) })));opts?.explainTarget?.observe('deduped', deduped);// Auto-escalate: if detail=low returned 0, retry with high. The innerdiff --git a/src/core/search/hybrid/keyword-only.ts b/src/core/search/hybrid/keyword-only.tsindex 00d0c82fca..905f5d8597 100644--- a/src/core/search/hybrid/keyword-only.ts+++ b/src/core/search/hybrid/keyword-only.ts@@ -12,7 +12,7 @@ import type { SearchResult } from '../../types.ts';import type { FusionListEntry } from '../fusion-lists.ts';import { applyAliasHop } from '../alias-hop.ts';import { applyExactLookupTier } from '../exact-lookup.ts';-import { dedupResults } from '../dedup.ts';+import { dedupResults, segmentRegions } from '../dedup.ts';import { enforceTokenBudget } from '../token-budget.ts';import { pushDegraded, stampBudgetStage } from './degraded.ts';import { stampEvidence } from '../evidence.ts';@@ -59,7 +59,7 @@ export async function searchWithoutEmbeddings(// T3/T4 — alias hop + evidence stamp even without an embedding provider// (the named-thing fix is most valuable exactly when vector is unavailable).trace?.observe('fused', noEmbedResults);- const noEmbedDeduped = dedupResults(noEmbedResults);+ const noEmbedDeduped = dedupResults(noEmbedResults, { regions: await segmentRegions(engine, noEmbedResults) });trace?.observe('deduped', noEmbedDeduped);const noEmbedPreExact = await applyAliasHop(engine, noEmbedDeduped, query, aliasHopOpts);// #1663 — structural exact-lookup tier (slug / exact-title identity).@@ -180,7 +180,7 @@ export async function searchVectorFallback(fallbackResults = await applyFeedbackStage(engine, fallbackResults, { reranked: false });}trace?.observe('fused', fallbackResults);- const kwDeduped = dedupResults(fallbackResults);+ const kwDeduped = dedupResults(fallbackResults, { regions: await segmentRegions(engine, fallbackResults) });trace?.observe('deduped', kwDeduped);const kwPreExact = await applyAliasHop(engine, kwDeduped, query, aliasHopOpts);// #1663 — structural exact-lookup tier (slug / exact-title identity).diff --git a/src/core/search/segmented-evidence.ts b/src/core/search/segmented-evidence.tsnew file mode 100644index 0000000000..628ff2357b--- /dev/null+++ b/src/core/search/segmented-evidence.ts@@ -0,0 +1,146 @@+/**+ * Evidence delivery on a segmented page (Wave B, spec 7.4): the windows an+ * evidence block is cut from, read without a page text.+ *+ * An inline page's evidence is cut from its whole projected text+ * (pageEvidenceText); a segmented page has no such text and never gets one.+ * Each hit is placed from its chunk's references (`occurrence_id` plus the+ * segment-relative projected span getChunkWindows returns, moved to document+ * bytes through the read projection's manifest sums), and only the bytes+ * around it are read with readBodyRange: the per-segment read projection+ * (stored protected regions, the withdrawal overlay per segment, the fence+ * overlay) that a get_page window of the page shows. A `window` reads the+ * hit's neighbor chunks (chunk_index within the radius), a `section` the+ * hit's segment (segments are cut at headings, days and message turns), a+ * `page` the whole text only while it is within the inline read size.+ * Windows are widened to whole lines, merged where they meet, and returned in+ * document order as runs the assembler joins with an omission mark.+ *+ * A chunk span is used only while it still holds the chunk's text (spans+ * drift when a hold or a tier change moves the projection); a hit whose chunk+ * has no stored span (a fenced-code or low-tier chunk) is placed by a unique+ * exact match inside its own segment, never by a search of the page.+ */+import type { BrainEngine } from '../engine.ts';+import type { ChunkWindowPage } from './chunk-windows.ts';+import { DEFAULT_INLINE_BODY_BYTES, TIMELINE_SEPARATOR } from '../page-window/document.ts';+import { openSegmentedBody, projectedLayout, readBodyRange, type SegmentedBody } from '../page-body/read-range.ts';++/** Bytes read past a window's ends so it can start and end on whole lines. */+const LINE_PAD_BYTES = 4096;++export interface EvidenceSpan { id: number; chunk_index: number; start: number; end: number }++export interface SegmentedWindows {+ /** Projected bytes of the text evidence is cut from (its truth only when the timeline is left out). */+ bytes: number;+ /** A `page` unit was asked for over the inline read size: the runs are the windows around the hits. */+ overInline: boolean;+ /** The windows read, in document order; spans are UTF-16 offsets into their run's text. */+ runs: Array<{ text: string; spans: EvidenceSpan[] }>;+ /** Hits whose chunk has no stored span, placed by an exact match in their segment: chunk id -> run and span. */+ placed: Map<number, { run: number; start: number; end: number }>;+}++interface Located extends EvidenceSpan { row: number; text: string }++export async function readSegmentedWindows(engine: BrainEngine, page: ChunkWindowPage,+ hits: ReadonlyArray<{ chunk_id: number; chunk_index: number; text: string }>,+ opts: { unit: 'window' | 'section' | 'page'; radius: number; includeTimeline: boolean }): Promise<SegmentedWindows> {+ const body = await openSegmentedBody(engine, { pageId: page.page_id });+ const layout = await projectedLayout(engine, body);+ const region = opts.includeTimeline ? undefined : 'truth' as const;+ const bytes = region && layout.timelineByte >= 0 ? layout.timelineByte - Buffer.byteLength(TIMELINE_SEPARATOR, 'utf8') : layout.totalBytes;+ const rowOf = new Map(body.rows.map((row, i) => [row.occurrenceId, i]));+ const rowAt = (occurrence: number | undefined) => {+ const i = occurrence === undefined ? undefined : rowOf.get(occurrence);+ return i !== undefined && layout.rowStart[i]! >= 0 && (!region || body.rows[i]!.region === region) ? i : undefined;+ };+ const rowEnd = (i: number) => layout.rowStart[i]! + layout.rowBytes[i]!;+ const located: Located[] = page.chunks.flatMap(c => {+ const row = rowAt(c.occurrence_id);+ const s = c.projected_byte_start;+ const e = c.projected_byte_end;+ if (row === undefined || s == null || e == null || !(e > s) || layout.rowStart[row]! + e > rowEnd(row)) return [];+ return [{ id: c.id, chunk_index: c.chunk_index, start: layout.rowStart[row]! + s, end: layout.rowStart[row]! + e, row, text: c.chunk_text }];+ });++ const placedBytes = new Map<number, { start: number; end: number }>();+ const homes: Array<{ start: number; end: number; chunkIndex: number; row: number }> = [];+ for (const hit of hits) {+ const own = located.find(l => l.id === hit.chunk_id);+ if (own) { homes.push({ ...own, chunkIndex: own.chunk_index }); continue; }+ const chunk = page.chunks.find(c => c.id === hit.chunk_id);+ const row = chunk && chunk.projected_byte_start == null ? rowAt(chunk.occurrence_id) : undefined;+ const needle = hit.text.trim();+ if (row !== undefined && needle.length >= 16) {+ const segment = (await readLines(engine, body, region, layout.rowStart[row]!, rowEnd(row), bytes)).bytes.toString('utf8');+ const at = segment.indexOf(needle);+ if (at >= 0 && segment.lastIndexOf(needle) === at) {+ const start = layout.rowStart[row]! + Buffer.byteLength(segment.slice(0, at), 'utf8');+ const span = { start, end: start + Buffer.byteLength(needle, 'utf8') };+ placedBytes.set(hit.chunk_id, span);+ homes.push({ ...span, row, chunkIndex: located.find(l => l.row === row && l.start <= span.start && span.end <= l.end)?.chunk_index ?? Number.NEGATIVE_INFINITY });+ continue;+ }+ }+ let near: Located | undefined;+ for (const l of located) if (!near || Math.abs(l.chunk_index - hit.chunk_index) < Math.abs(near.chunk_index - hit.chunk_index)) near = l;+ if (near) homes.push({ ...near, chunkIndex: near.chunk_index });+ }++ const overInline = opts.unit === 'page' && bytes > DEFAULT_INLINE_BODY_BYTES;+ const wanted = opts.unit === 'page' && !overInline ? [{ start: 0, end: bytes }] : homes.map(h => {+ if (opts.unit === 'section') return { start: layout.rowStart[h.row]!, end: rowEnd(h.row) };+ const near = located.filter(l => Math.abs(l.chunk_index - h.chunkIndex) <= opts.radius);+ return { start: Math.min(h.start, ...near.map(l => l.start)), end: Math.max(h.end, ...near.map(l => l.end)) };+ });+ const merged: Array<{ start: number; end: number }> = [];+ for (const w of wanted.sort((a, b) => a.start - b.start)) {+ const last = merged[merged.length - 1];+ if (last && w.start <= last.end + 2 * LINE_PAD_BYTES) last.end = Math.max(last.end, w.end);+ else merged.push({ ...w });+ }++ const runs: SegmentedWindows['runs'] = [];+ const placed: SegmentedWindows['placed'] = new Map();+ for (const w of merged) {+ const read = await readLines(engine, body, region, w.start, w.end, bytes);+ const runEnd = read.start + read.bytes.length;+ if (read.bytes.length === 0) continue;+ const text = read.bytes.toString('utf8');+ const charAt = (byte: number) => read.bytes.subarray(0, byte - read.start).toString('utf8').length;+ const inside = (s: { start: number; end: number }) => s.start >= read.start && s.end <= runEnd;+ const spans = located.filter(l => inside(l) && read.bytes.subarray(l.start - read.start, l.end - read.start).toString('utf8').replace(/\s+/g, '') === l.text.replace(/\s+/g, ''))+ .map(l => ({ id: l.id, chunk_index: l.chunk_index, start: charAt(l.start), end: charAt(l.end) }));+ for (const [id, span] of placedBytes) if (inside(span)) placed.set(id, { run: runs.length, start: charAt(span.start), end: charAt(span.end) });+ runs.push({ text, spans });+ }+ return { bytes, overInline, runs, placed };+}++/**+ * Projected bytes [start, end) widened to whole lines: up to LINE_PAD_BYTES are read on each side, the window starts+ * after the last newline before `start` and ends after the first newline at or after `end`; with no newline in reach+ * it is cut on a code point. `limit` is where the text ends.+ */+async function readLines(engine: BrainEngine, body: SegmentedBody, region: 'truth' | undefined, start: number, end: number, limit: number): Promise<{ bytes: Buffer; start: number }> {+ const from = Math.max(0, start - LINE_PAD_BYTES);+ const to = Math.min(limit, end + LINE_PAD_BYTES);+ const pieces: Buffer[] = [];+ let at = from;+ for await (const piece of readBodyRange(engine, { pageId: body.pageId, space: 'projected', start: from, end: to, audience: 'remote', body, region })) {+ if (pieces.length === 0) at = piece.projectedStart;+ pieces.push(piece.bytes);+ }+ const buf = Buffer.concat(pieces);+ const s = Math.max(0, start - at);+ const e = Math.min(buf.length, end - at);+ const before = s > 0 ? buf.lastIndexOf(0x0a, s - 1) : -1;+ let a = before >= 0 ? before + 1 : at === 0 ? 0 : s;+ while (a < buf.length && (buf[a]! & 0xc0) === 0x80) a++;+ const after = buf.indexOf(0x0a, Math.max(a, e - 1));+ let b = after >= 0 ? after + 1 : at + buf.length >= to && to === limit ? buf.length : e;+ while (b > a && b < buf.length && (buf[b]! & 0xc0) === 0x80) b--;+ return { bytes: buf.subarray(a, Math.max(a, b)), start: at + a };+}diff --git a/test/dedup.test.ts b/test/dedup.test.tsindex f543c018b8..f597e9bf8b 100644--- a/test/dedup.test.ts+++ b/test/dedup.test.ts@@ -4,7 +4,8 @@*/import { describe, test, expect } from 'bun:test';-import { dedupResults } from '../src/core/search/dedup.ts';+import { dedupResults, MAX_PER_SEGMENTED_PAGE, SEGMENT_CLUSTER_BYTES } from '../src/core/search/dedup.ts';+import { applySnippetCap } from '../src/core/search/snippet-cap.ts';import type { SearchResult } from '../src/core/types.ts';function makeResult(overrides: Partial<SearchResult> = {}): SearchResult {@@ -300,3 +301,52 @@ describe('compiled truth guarantee keeps evidence and score order (read-path audfor (let i = 1; i < out.length; i++) expect(out[i - 1].score).toBeGreaterThanOrEqual(out[i].score);});});++// Wave B PR 2 (spec 7.5): a segmented page keeps up to 2 chunks per occurrence cluster (occurrences more than+// SEGMENT_CLUSTER_BYTES apart are separate regions), at most MAX_PER_SEGMENTED_PAGE in all; inline pages keep 2.+// Fails when the regions are ignored (every page capped at 2), clusters split at or below 1 MiB, or the page total+// passes 6.+describe('segmented pages: two chunks per occurrence cluster, six per page', () => {+ const MIB = 1024 * 1024;+ const WORDS = ['amber', 'basil', 'cedar', 'delta', 'ember', 'fjord', 'grove', 'heron', 'iris', 'juniper', 'kelp', 'lotus'];+ /** Hits on page `slug`, one per stored occurrence position, in score order, each with distinct text. */+ function hits(slug: string, positions: number[], firstId: number): { results: SearchResult[]; regions: Map<number, number> } {+ const results = positions.map((_, i) => makeResult({ slug, page_id: firstId, chunk_id: firstId + i, chunk_index: 10 + i, score: 1 - i * 0.01,+ chunk_text: `${WORDS[i % WORDS.length]} ${WORDS[(i * 5 + 3) % WORDS.length]} passage ${i} ${'x'.repeat(i)}` }));+ return { results, regions: new Map(positions.map((at, i) => [firstId + i, at])) };+ }++ test('regions more than 1 MiB apart keep two chunks each, capped at six per page', () => {+ const { results, regions } = hits('chat/huge', [0, 0, 0, 3 * MIB, 3 * MIB, 3 * MIB, 6 * MIB, 6 * MIB, 9 * MIB, 9 * MIB, 12 * MIB, 12 * MIB], 100);+ const out = dedupResults(results, { regions });+ expect(MAX_PER_SEGMENTED_PAGE).toBe(6);+ expect(out.length).toBe(6);+ const perRegion = new Map<number, number>();+ for (const r of out) perRegion.set(regions.get(r.chunk_id)!, (perRegion.get(regions.get(r.chunk_id)!) ?? 0) + 1);+ expect([...perRegion.entries()].sort((a, b) => a[0] - b[0])).toEqual([[0, 2], [3 * MIB, 2], [6 * MIB, 2]]);+ });++ test('occurrences at most 1 MiB apart are one region; one byte further starts the next', () => {+ const near = hits('chat/near', [0, SEGMENT_CLUSTER_BYTES, 2 * SEGMENT_CLUSTER_BYTES, 3 * SEGMENT_CLUSTER_BYTES], 200);+ expect(dedupResults(near.results, { regions: near.regions }).length).toBe(2);+ const apart = hits('chat/apart', [0, 0, SEGMENT_CLUSTER_BYTES + 1, SEGMENT_CLUSTER_BYTES + 1, 2 * SEGMENT_CLUSTER_BYTES + 2], 300);+ expect(dedupResults(apart.results, { regions: apart.regions }).map(r => r.chunk_id).sort()).toEqual([300, 301, 302, 303, 304]);+ });++ test('inline pages keep two chunks, with or without regions for other pages', () => {+ const seg = hits('chat/huge', [0, 0, 3 * MIB, 3 * MIB], 400);+ const inline = hits('notes/inline', [0, 0, 0, 0, 0], 500).results;+ const out = dedupResults([...seg.results, ...inline], { regions: seg.regions });+ expect(out.filter(r => r.slug === 'notes/inline').map(r => r.chunk_id)).toEqual([500, 501]);+ expect(out.filter(r => r.slug === 'chat/huge').length).toBe(4);+ expect(dedupResults(inline).map(r => r.chunk_id)).toEqual([500, 501]);+ expect(dedupResults(seg.results).length).toBe(2);+ });++ test('every kept hit of a segmented page points at its own window', () => {+ const { results, regions } = hits('chat/huge', [0, 0, 3 * MIB, 3 * MIB, 6 * MIB, 6 * MIB], 600);+ const capped = applySnippetCap(dedupResults(results, { regions }), 10);+ expect(capped.length).toBe(6);+ for (const r of capped) expect(r.chunk_text).toContain(`get_page chat/huge around_chunk_id=${r.chunk_id}]`);+ });+});diff --git a/test/fixtures/goldens/sql-text/chunks.json b/test/fixtures/goldens/sql-text/chunks.jsonindex d226b48336..782d41955e 100644--- a/test/fixtures/goldens/sql-text/chunks.json+++ b/test/fixtures/goldens/sql-text/chunks.json@@ -156,8 +156,8 @@"array<string>","number"],- "sql": "WITH req AS ( SELECT * FROM unnest($1::int[], $2::int[], $3::int[], $4::int[]) AS r(page_id, lo, hi, prio) ), auth AS ( SELECT p.id, p.slug, p.source_id, p.type, p.knowledge_revision::text AS revision, p.compiled_truth, p.timeline, p.body_generation, (COALESCE(p.chunker_version, 0) >= $5) AS sealed, (SELECT MIN(req.prio) FROM req WHERE req.page_id = p.id) AS prio FROM pages p JOIN sources s ON s.id = p.source_id WHERE p.id = ANY($6::int[]) AND p.deleted_at IS NULL AND (p.text_projection_revision = p.knowledge_revision) IS TRUE AND NOT s.archived AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') ), chunk_rows AS ( SELECT cc.page_id, cc.id AS chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.projected_byte_start, cc.projected_byte_end, a.prio FROM auth a JOIN content_chunks cc ON cc.page_id = a.id WHERE a.sealed AND (cc.body_generation IS NULL OR (cc.body_generation <= a.body_generation AND (cc.retired_generation IS NULL OR cc.retired_generation > a.body_generation))) AND cc.chunk_source = ANY($7::text[]) AND COALESCE(cc.modality, 'text') = 'text' AND EXISTS (SELECT 1 FROM req r WHERE r.page_id = cc.page_id AND cc.chunk_index BETWEEN r.lo AND r.hi) ORDER BY a.prio, cc.page_id, cc.chunk_index LIMIT $8 ) SELECT 'page' AS kind, a.id AS page_id, a.slug, a.source_id, a.type, a.revision, a.sealed, a.prio, (SELECT MAX(c2.chunk_index) FROM content_chunks c2 WHERE c2.page_id = a.id AND (c2.body_generation IS NULL OR (c2.body_generation <= a.body_generation AND (c2.retired_generation IS NULL OR c2.retired_generation > a.body_generation)))) AS max_chunk_index, a.compiled_truth, a.timeline, NULL::int AS chunk_id, NULL::int AS chunk_index, NULL::text AS chunk_text, NULL::text AS chunk_source, NULL::bigint AS projected_byte_start, NULL::bigint AS projected_byte_end FROM auth a UNION ALL SELECT 'chunk' AS kind, c.page_id, NULL, NULL, NULL, NULL, NULL, c.prio, NULL, NULL, NULL, c.chunk_id, c.chunk_index, c.chunk_text, c.chunk_source, c.projected_byte_start, c.projected_byte_end FROM chunk_rows c",- "textSha256": "64aa9e142a90edbb495f64db0e2075740779bf7568da6bd32ecc15fb1cb7dd31"+ "sql": "WITH req AS ( SELECT * FROM unnest($1::int[], $2::int[], $3::int[], $4::int[]) AS r(page_id, lo, hi, prio) ), auth AS ( SELECT p.id, p.slug, p.source_id, p.type, p.knowledge_revision::text AS revision, p.compiled_truth, p.timeline, p.body_generation, p.body_storage = 'segmented' AS segmented, (COALESCE(p.chunker_version, 0) >= $5) AS sealed, (SELECT MIN(req.prio) FROM req WHERE req.page_id = p.id) AS prio FROM pages p JOIN sources s ON s.id = p.source_id WHERE p.id = ANY($6::int[]) AND p.deleted_at IS NULL AND (p.text_projection_revision = p.knowledge_revision) IS TRUE AND NOT s.archived AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') ), chunk_rows AS ( SELECT cc.page_id, cc.id AS chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.projected_byte_start, cc.projected_byte_end, cc.occurrence_id, a.prio FROM auth a JOIN content_chunks cc ON cc.page_id = a.id WHERE a.sealed AND (cc.body_generation IS NULL OR (cc.body_generation <= a.body_generation AND (cc.retired_generation IS NULL OR cc.retired_generation > a.body_generation))) AND cc.chunk_source = ANY($7::text[]) AND COALESCE(cc.modality, 'text') = 'text' AND EXISTS (SELECT 1 FROM req r WHERE r.page_id = cc.page_id AND cc.chunk_index BETWEEN r.lo AND r.hi) ORDER BY a.prio, cc.page_id, cc.chunk_index LIMIT $8 ) SELECT 'page' AS kind, a.id AS page_id, a.slug, a.source_id, a.type, a.revision, a.sealed, a.segmented, a.prio, (SELECT MAX(c2.chunk_index) FROM content_chunks c2 WHERE c2.page_id = a.id AND (c2.body_generation IS NULL OR (c2.body_generation <= a.body_generation AND (c2.retired_generation IS NULL OR c2.retired_generation > a.body_generation)))) AS max_chunk_index, a.compiled_truth, a.timeline, NULL::int AS chunk_id, NULL::int AS chunk_index, NULL::text AS chunk_text, NULL::text AS chunk_source, NULL::bigint AS projected_byte_start, NULL::bigint AS projected_byte_end, NULL::bigint AS occurrence_id FROM auth a UNION ALL SELECT 'chunk' AS kind, c.page_id, NULL, NULL, NULL, NULL, NULL, NULL, c.prio, NULL, NULL, NULL, c.chunk_id, c.chunk_index, c.chunk_text, c.chunk_source, c.projected_byte_start, c.projected_byte_end, c.occurrence_id FROM chunk_rows c",+ "textSha256": "7842c83854f034c7d039a28e23f884e635bc3cb97caffa89197f2fb491587dc7"}],"scopedPrivateSafe": [@@ -174,8 +174,8 @@"array<string>","number"],- "sql": "WITH req AS ( SELECT * FROM unnest($1::int[], $2::int[], $3::int[], $4::int[]) AS r(page_id, lo, hi, prio) ), auth AS ( SELECT p.id, p.slug, p.source_id, p.type, p.knowledge_revision::text AS revision, p.compiled_truth, p.timeline, p.body_generation, (COALESCE(p.chunker_version, 0) >= $5) AS sealed, (SELECT MIN(req.prio) FROM req WHERE req.page_id = p.id) AS prio FROM pages p JOIN sources s ON s.id = p.source_id WHERE p.id = ANY($6::int[]) AND p.source_id = ANY($7::text[]) AND p.deleted_at IS NULL AND (p.text_projection_revision = p.knowledge_revision) IS TRUE AND NOT s.archived AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND ((COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type IN ('atom', 'question') OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(p.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type IN ('atom', 'question') OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND (COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) AND p.chunker_version >= 4 ), chunk_rows AS ( SELECT cc.page_id, cc.id AS chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.projected_byte_start, cc.projected_byte_end, a.prio FROM auth a JOIN content_chunks cc ON cc.page_id = a.id WHERE a.sealed AND (cc.body_generation IS NULL OR (cc.body_generation <= a.body_generation AND (cc.retired_generation IS NULL OR cc.retired_generation > a.body_generation))) AND cc.chunk_source = ANY($8::text[]) AND COALESCE(cc.modality, 'text') = 'text' AND EXISTS (SELECT 1 FROM req r WHERE r.page_id = cc.page_id AND cc.chunk_index BETWEEN r.lo AND r.hi) ORDER BY a.prio, cc.page_id, cc.chunk_index LIMIT $9 ) SELECT 'page' AS kind, a.id AS page_id, a.slug, a.source_id, a.type, a.revision, a.sealed, a.prio, (SELECT MAX(c2.chunk_index) FROM content_chunks c2 WHERE c2.page_id = a.id AND (c2.body_generation IS NULL OR (c2.body_generation <= a.body_generation AND (c2.retired_generation IS NULL OR c2.retired_generation > a.body_generation)))) AS max_chunk_index, a.compiled_truth, a.timeline, NULL::int AS chunk_id, NULL::int AS chunk_index, NULL::text AS chunk_text, NULL::text AS chunk_source, NULL::bigint AS projected_byte_start, NULL::bigint AS projected_byte_end FROM auth a UNION ALL SELECT 'chunk' AS kind, c.page_id, NULL, NULL, NULL, NULL, NULL, c.prio, NULL, NULL, NULL, c.chunk_id, c.chunk_index, c.chunk_text, c.chunk_source, c.projected_byte_start, c.projected_byte_end FROM chunk_rows c",- "textSha256": "4c57a54e1bc0845f89172e2e853c4cc7017a8301e026d48409e37585a162893a"+ "sql": "WITH req AS ( SELECT * FROM unnest($1::int[], $2::int[], $3::int[], $4::int[]) AS r(page_id, lo, hi, prio) ), auth AS ( SELECT p.id, p.slug, p.source_id, p.type, p.knowledge_revision::text AS revision, p.compiled_truth, p.timeline, p.body_generation, p.body_storage = 'segmented' AS segmented, (COALESCE(p.chunker_version, 0) >= $5) AS sealed, (SELECT MIN(req.prio) FROM req WHERE req.page_id = p.id) AS prio FROM pages p JOIN sources s ON s.id = p.source_id WHERE p.id = ANY($6::int[]) AND p.source_id = ANY($7::text[]) AND p.deleted_at IS NULL AND (p.text_projection_revision = p.knowledge_revision) IS TRUE AND NOT s.archived AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND ((COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type IN ('atom', 'question') OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(p.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type IN ('atom', 'question') OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND (COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) AND p.chunker_version >= 4 ), chunk_rows AS ( SELECT cc.page_id, cc.id AS chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.projected_byte_start, cc.projected_byte_end, cc.occurrence_id, a.prio FROM auth a JOIN content_chunks cc ON cc.page_id = a.id WHERE a.sealed AND (cc.body_generation IS NULL OR (cc.body_generation <= a.body_generation AND (cc.retired_generation IS NULL OR cc.retired_generation > a.body_generation))) AND cc.chunk_source = ANY($8::text[]) AND COALESCE(cc.modality, 'text') = 'text' AND EXISTS (SELECT 1 FROM req r WHERE r.page_id = cc.page_id AND cc.chunk_index BETWEEN r.lo AND r.hi) ORDER BY a.prio, cc.page_id, cc.chunk_index LIMIT $9 ) SELECT 'page' AS kind, a.id AS page_id, a.slug, a.source_id, a.type, a.revision, a.sealed, a.segmented, a.prio, (SELECT MAX(c2.chunk_index) FROM content_chunks c2 WHERE c2.page_id = a.id AND (c2.body_generation IS NULL OR (c2.body_generation <= a.body_generation AND (c2.retired_generation IS NULL OR c2.retired_generation > a.body_generation)))) AS max_chunk_index, a.compiled_truth, a.timeline, NULL::int AS chunk_id, NULL::int AS chunk_index, NULL::text AS chunk_text, NULL::text AS chunk_source, NULL::bigint AS projected_byte_start, NULL::bigint AS projected_byte_end, NULL::bigint AS occurrence_id FROM auth a UNION ALL SELECT 'chunk' AS kind, c.page_id, NULL, NULL, NULL, NULL, NULL, NULL, c.prio, NULL, NULL, NULL, c.chunk_id, c.chunk_index, c.chunk_text, c.chunk_source, c.projected_byte_start, c.projected_byte_end, c.occurrence_id FROM chunk_rows c",+ "textSha256": "47699828c429ae990c666c077452379b5829fb304cd261af4d1408d1b0167772"}]},diff --git a/test/large-pages/segmented-evidence-read-cost.test.ts b/test/large-pages/segmented-evidence-read-cost.test.tsnew file mode 100644index 0000000000..395e4a645a--- /dev/null+++ b/test/large-pages/segmented-evidence-read-cost.test.ts@@ -0,0 +1,85 @@+/**+ * Wave B PR 2 (spec 7.4): evidence on a large segmented page costs the hits'+ * windows, not the page.+ *+ * 1. Protects: assemble_evidence with three hits spread over a 40 MiB+ * conversation page loads at most two segment texts per hit from storage+ * (a window can straddle one cut) and delivers each hit's window.+ * 2. Fails when: the segmented path reads the page whole (a whole-text+ * projection, a materialized body, or every segment of the read+ * projection), which loads all ~40 MiB.+ * 3. Seams: the engine's readSegmentTexts, wrapped to count the bytes it+ * returns (every segment text the reader loads goes through it).+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../../src/core/engine.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { importFromFile } from '../../src/core/import-file.ts';+import { readPageBodyPolicy } from '../../src/core/page-body/limits.ts';+import { operations, type OperationContext } from '../../src/core/operations.ts';+import { EVIDENCE_OMISSION } from '../../src/core/search/evidence-delivery.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { testBackends } from '../helpers/test-backends.ts';+import { conversationPage } from '../helpers/conversation-page.ts';++const PAGE_BYTES = 40 * 2 ** 20;+const NEEDLES = [{ at: 0.1, word: 'zzcostone' }, { at: 0.5, word: 'zzcosttwo' }, { at: 0.9, word: 'zzcostthree' }];+const assemble = operations.find(o => o.name === 'assemble_evidence')!;+const dir = mkdtempSync(join(tmpdir(), 'segmented-evidence-cost-'));+afterAll(() => rmSync(dir, { recursive: true, force: true }));++for (const kind of testBackends()) {+ describe(`evidence read cost on a 40 MiB segmented page (${kind})`, () => {+ let engine: BrainEngine;+ 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 engine.setConfig('pages.segmented_storage', 'on');+ const file = join(dir, `${kind}.md`);+ writeFileSync(file, conversationPage(PAGE_BYTES, { seed: 7, needles: NEEDLES }));+ const result = await importFromFile(engine, file, 'chat/cost-example.md', { noEmbed: true, bodyPolicy: await readPageBodyPolicy(engine) });+ rmSync(file, { force: true });+ expect(result.status).toBe('imported');+ }, 600_000);++ afterAll(async () => { await close(); });++ test('three hits load at most two segment texts each and come back as their windows', async () => {+ const [page] = await engine.executeRaw<{ id: number; body_storage: string; body_bytes: number }>("SELECT id, body_storage, body_bytes FROM pages WHERE slug='chat/cost-example'");+ expect(page!.body_storage).toBe('segmented');+ expect(Number(page!.body_bytes)).toBeGreaterThan(PAGE_BYTES - 1024);+ const [{ max_segment }] = await engine.executeRaw<{ max_segment: number }>('SELECT max(byte_len)::int AS max_segment FROM page_body_manifest WHERE page_id=$1', [page!.id]);+ const rows = await engine.executeRaw<{ id: number; chunk_text: string }>("SELECT id, chunk_text FROM content_chunks WHERE page_id=$1 AND chunk_text ~ 'zzcost(one|two|three)' ORDER BY chunk_index", [page!.id]);+ const hits = NEEDLES.map(({ word }) => rows.find(r => r.chunk_text.includes(word))!);+ expect(hits.every(Boolean)).toBe(true);++ let loaded = 0;+ const read = engine.readSegmentTexts.bind(engine);+ engine.readSegmentTexts = async (sourceId, shas) => {+ const texts = await read(sourceId, shas);+ for (const text of texts.values()) loaded += text.byteLength;+ return texts;+ };+ const ctx = { engine, config: {}, logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote: true, sourceId: 'default', emitResponseMeta: () => {} } as unknown as OperationContext;+ const out = await assemble.handler(ctx, { hits: hits.map(h => ({ source_id: 'default', slug: 'chat/cost-example', chunk_id: Number(h.id) })), return_unit: 'window', token_budget: 20_000 }) as { results: Array<{ chunk_text: string; delivered: { unit: string } }> };+ engine.readSegmentTexts = read;++ expect(out.results.length).toBe(1);+ expect(out.results[0]!.delivered.unit).toBe('window');+ for (const { word } of NEEDLES) expect(out.results[0]!.chunk_text).toContain(word);+ expect(out.results[0]!.chunk_text.split(EVIDENCE_OMISSION).length).toBeGreaterThanOrEqual(3);+ expect(loaded).toBeGreaterThan(0);+ expect(loaded).toBeLessThanOrEqual(hits.length * 2 * Number(max_segment));+ }, 600_000);+ });+}diff --git a/test/large-pages/segmented-evidence.test.ts b/test/large-pages/segmented-evidence.test.tsnew file mode 100644index 0000000000..f711512eaf--- /dev/null+++ b/test/large-pages/segmented-evidence.test.ts@@ -0,0 +1,182 @@+/**+ * Wave B PR 2 (spec 7.4, 7.5): evidence delivery and dedup regions on a+ * segmented page.+ *+ * 1. Protects: assemble_evidence on a segmented page cuts its window,+ * section and page units from windows read around the hits through the+ * segment reader, so a remote caller never sees a takes block, a private+ * or withdrawn facts row, or a private key, whichever side of a block the+ * window starts; every delivered run is a slice of the read projection+ * whole-body sanitization gives the same stored body (parity with an+ * inline page); hits far apart come back as one block of separate+ * windows; segmentRegions gives dedup each chunk's occurrence position.+ * 2. Fails when: evidence degrades to the hit chunk on a segmented page (PR 1+ * read the NULL body columns: every unit came back `chunk` with+ * `anchor_not_located`), a window is read from the stored body instead of+ * the remote read projection, or windows are cut from anything other than+ * the projection.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../../src/core/engine.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { operations, type OperationContext } from '../../src/core/operations.ts';+import { buildSegmentedProjection } from '../../src/core/page-body/projection.ts';+import { openSegmentedBody } from '../../src/core/page-body/read-range.ts';+import { EVIDENCE_OMISSION, PAGE_OVER_INLINE_BYTES } from '../../src/core/search/evidence-delivery.ts';+import { segmentRegions } from '../../src/core/search/dedup.ts';+import type { SearchResult } from '../../src/core/types.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, importSegmented, inlineProjection, pageContent, privacyText, privateTokensIn, seedLedger, storedOffsets,+} from '../helpers/segmented-privacy-fixture.ts';++let engine: BrainEngine;+const assemble = operations.find(o => o.name === 'assemble_evidence')!;+const ctx = (): OperationContext => ({ engine, config: {}, logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote: true, sourceId: 'default',+ emitResponseMeta: () => {} } as unknown as OperationContext);++interface Delivered { chunk_text: string; delivered: { unit: string; chunk_ids: number[]; match_spans: Array<{ chunk_id: number; start: number; end: number }>; fallback_reason?: string } }++async function evidence(slug: string, chunkIds: number[], unit: string): Promise<Delivered[]> {+ const out = await assemble.handler(ctx(), { hits: chunkIds.map(chunk_id => ({ source_id: 'default', slug, chunk_id })), return_unit: unit, return_window: 2, token_budget: 30_000 }) as { results: Delivered[] };+ return out.results;+}++/** Chunks of the segments holding the first occurrences of `tokens` in the stored body, at most `per` per segment. */+async function chunksNear(pageId: number, tokens: string[], per = 4): Promise<number[]> {+ const body = await openSegmentedBody(engine, { pageId });+ const occurrences = new Set<number>();+ for (const token of tokens) {+ for (const at of (await storedOffsets(engine, pageId, token)).slice(0, 4)) {+ const row = body.rows.find(r => r.byteStart <= at && at < r.byteStart + r.byteLen);+ if (row) occurrences.add(row.occurrenceId);+ }+ }+ const rows = await engine.executeRaw<{ id: number; occurrence_id: number }>(+ 'SELECT id, occurrence_id FROM content_chunks WHERE page_id=$1 AND occurrence_id = ANY($2::bigint[]) ORDER BY chunk_index', [pageId, [...occurrences]]);+ const picked: number[] = [];+ for (const occurrence of occurrences) {+ const mine = rows.filter(r => Number(r.occurrence_id) === occurrence);+ for (let i = 0; i < per && mine.length; i++) picked.push(Number(mine[Math.floor((i * mine.length) / per)]!.id));+ }+ return [...new Set(picked)];+}++/** Every unit for every hit: no private token, runs are slices of the inline projection, the public tokens show. */+async function expectSafeEvidence(slug: string, pageId: number, hits: number[], ledger: boolean) {+ const projection = (await inlineProjection(engine, slug, pageId)).toString('utf8');+ const seen = new Set<string>();+ let windows = 0;+ for (const chunkId of hits) {+ for (const unit of ['window', 'section', 'page']) {+ for (const r of await evidence(slug, [chunkId], unit)) {+ expect({ chunkId, unit, leaked: privateTokensIn(r.chunk_text, { ledger }) }).toEqual({ chunkId, unit, leaked: [] });+ for (const token of Object.values(PUBLIC)) if (r.chunk_text.includes(token)) seen.add(token);+ if (r.delivered.unit === 'chunk') continue;+ windows++;+ for (const run of r.chunk_text.split(EVIDENCE_OMISSION)) expect(projection.includes(run.trim())).toBe(true);+ }+ }+ }+ expect(windows).toBeGreaterThan(hits.length * 2);+ expect([...seen].sort()).toEqual(Object.values(PUBLIC).sort());+}++for (const kind of testBackends()) {+ describe(`evidence 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();+ }+ }, 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('a window, section or page around a hit is read from the segments and is a slice of the read projection', async () => {+ const r = mulberry32(301);+ const slug = 'chat/evidence-units';+ const pageId = await importSegmented(engine, slug, pageContent(`${privacyText(r, 700_000)}\nzzevidenceneedle sits here once\n${privacyText(r, 700_000)}`));+ const [hit] = await engine.executeRaw<{ id: number }>("SELECT id FROM content_chunks WHERE page_id=$1 AND chunk_text LIKE '%zzevidenceneedle%'", [pageId]);+ const projection = (await inlineProjection(engine, slug, pageId)).toString('utf8');+ for (const unit of ['window', 'section', 'page']) {+ const [block] = await evidence(slug, [Number(hit!.id)], unit);+ expect(block!.delivered.unit).toBe(unit === 'page' ? 'window' : unit);+ expect(block!.delivered.fallback_reason).toBe(unit === 'page' ? PAGE_OVER_INLINE_BYTES : undefined);+ expect(block!.chunk_text).toContain('zzevidenceneedle');+ const span = block!.delivered.match_spans.find(s => s.chunk_id === Number(hit!.id))!;+ expect(block!.chunk_text.slice(span.start, span.end)).toContain('zzevidenceneedle');+ for (const run of block!.chunk_text.split(EVIDENCE_OMISSION)) expect(projection.includes(run.trim())).toBe(true);+ }+ }, 240_000);++ test('hits far apart on one page come back as one block of separate windows', async () => {+ const r = mulberry32(307);+ const slug = 'chat/evidence-far';+ const words = ['zzfarone', 'zzfartwo', 'zzfarthree'];+ const pageId = await importSegmented(engine, slug, pageContent(words.map(w => `${privacyText(r, 600_000, { keys: false })}\n${w} marks this region\n`).join('')));+ const hits = await engine.executeRaw<{ id: number; chunk_text: string }>(+ "SELECT id, chunk_text FROM content_chunks WHERE page_id=$1 AND chunk_text ~ 'zzfar(one|two|three)' ORDER BY chunk_index", [pageId]);+ expect(hits.length).toBe(3);+ const [block] = await evidence(slug, hits.map(h => Number(h.id)), 'window');+ expect(block!.delivered.unit).toBe('window');+ expect(block!.chunk_text.split(EVIDENCE_OMISSION).length).toBeGreaterThanOrEqual(3);+ for (const [i, h] of hits.entries()) {+ const span = block!.delivered.match_spans.find(s => s.chunk_id === Number(h.id))!;+ expect(block!.chunk_text.slice(span.start, span.end)).toContain(words[i]!);+ }+ const regions = await segmentRegions(engine, hits.map(h => ({ slug, source_id: 'default', chunk_id: Number(h.id) }) as SearchResult));+ const starts = hits.map(h => regions.get(Number(h.id))!);+ expect(starts.every(s => Number.isInteger(s))).toBe(true);+ expect(starts[2]! - starts[0]!).toBeGreaterThan(1024 * 1024);+ }, 240_000);++ test('a segment read that fails returns the hit chunk with segment_read_failed, never a guessed window', async () => {+ const r = mulberry32(317);+ const slug = 'chat/evidence-read-failed';+ const pageId = await importSegmented(engine, slug, pageContent(`${privacyText(r, 600_000)}\nzzreadfailneedle sits here once\n${privacyText(r, 600_000)}`));+ const [hit] = await engine.executeRaw<{ id: number; chunk_text: string }>("SELECT id, chunk_text FROM content_chunks WHERE page_id=$1 AND chunk_text LIKE '%zzreadfailneedle%'", [pageId]);+ const read = engine.readSegmentTexts;+ engine.readSegmentTexts = async () => { throw new Error('forced segment read failure'); };+ try {+ for (const unit of ['window', 'section', 'page']) {+ const [block] = await evidence(slug, [Number(hit!.id)], unit);+ expect({ unit, delivered: block!.delivered.unit, reason: block!.delivered.fallback_reason }).toEqual({ unit, delivered: 'chunk', reason: 'segment_read_failed' });+ expect(block!.chunk_text).toBe(hit!.chunk_text);+ }+ } finally {+ engine.readSegmentTexts = read;+ }+ }, 240_000);++ test('no evidence block shows takes, private facts or keys, wherever its window starts', async () => {+ const r = mulberry32(311);+ const slug = 'chat/evidence-private';+ const pageId = await importSegmented(engine, slug, pageContent(privacyText(r, 1_500_000), privacyText(r, 300_000)));+ await expectSafeEvidence(slug, pageId, await chunksNear(pageId, [PRIVATE.takes, PRIVATE.privateFact, PRIVATE.key]), false);+ }, 600_000);++ test('withdrawn, purged and held rows recorded after the import stay out of every evidence block', async () => {+ const r = mulberry32(313);+ const slug = 'chat/evidence-ledger';+ const pageId = await importSegmented(engine, slug, pageContent(privacyText(r, 1_400_000), privacyText(r, 200_000)));+ await seedLedger(engine, slug);+ // Forget bumps the revision and clears the projection; the rebuild rechunks from the overlaid text.+ await engine.executeRaw('UPDATE pages SET knowledge_revision=gen_random_uuid(), text_projection_revision=NULL WHERE id=$1', [pageId]);+ await engine.executeRaw('DELETE FROM content_chunks WHERE page_id=$1', [pageId]);+ expect((await buildSegmentedProjection(engine, { sourceId: 'default', slug })).sealed).toBe(true);+ await expectSafeEvidence(slug, pageId, await chunksNear(pageId, [PRIVATE.withdrawn, PRIVATE.purged, PRIVATE.held]), true);+ }, 600_000);+ });+}diff --git a/test/large-pages/segmented-leads.test.ts b/test/large-pages/segmented-leads.test.tsnew file mode 100644index 0000000000..95b757599a--- /dev/null+++ b/test/large-pages/segmented-leads.test.ts@@ -0,0 +1,102 @@+/**+ * Wave B PR 2 (spec 7.4): bounded leads of a segmented page.+ *+ * 1. Protects: a segmented page's lead is its stored truth_lead; when the+ * lead holds a facts fence it is overlaid alone with the page's withdrawal+ * ledger (no segment text is read), so the lead shows the page's opening+ * prose and public facts and never a withdrawn, purged or private row,+ * takes or a key, and starts like the lead of the same body stored inline+ * (leads do not apply the fence overlay's holds, inline or segmented); the+ * exact-slug and alias snippets (which read the page through getPage) show+ * that lead.+ * 2. Fails when: a segmented lead with a facts fence comes back empty (PR 1+ * failed closed: the snapshot read has no body to overlay), the lead is+ * shown raw, the overlay reads the page's segments, or the getPage+ * snippets read the throwing body getters (PR 1: the exact-slug tier+ * skipped the page, the alias hop threw page_body_segmented).+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../../src/core/engine.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { boundedBodyPrefixSql, overlaidBoundedRows, projectedLead } from '../../src/core/page-window/bounded-lead.ts';+import { boundedProjectedPrefix } from '../../src/core/page-window/document.ts';+import { structuralExactLookup } from '../../src/core/search/exact-lookup.ts';+import { applyAliasHop } from '../../src/core/search/alias-hop.ts';+import { normalizeAlias } from '../../src/core/search/alias-normalize.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { testBackends } from '../helpers/test-backends.ts';+import { mulberry32 } from '../helpers/seeded-random.ts';+import { PEM_BLOCK } from '../helpers/segment-bodies.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import {+ PRIVATE, PUBLIC, importSegmented, pageContent, privacyFacts, privacyTakes, privacyText, privateTokensIn, seedLedger,+} from '../helpers/segmented-privacy-fixture.ts';++let engine: BrainEngine;+const SLUG = 'people/lead-example';+const INLINE = 'people/lead-inline-example';+const OPENING = 'Lead Example runs research at acme-example and writes about widgets.';++for (const kind of testBackends()) {+ describe(`bounded leads 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}`);+ const r = mulberry32(401);+ const content = pageContent(`${OPENING}\n\n${privacyFacts()}\n${privacyTakes()}\n${PEM_BLOCK}\n${privacyText(r, 1_500_000)}`);+ await engine.setConfig('pages.segmented_storage', 'off');+ await importFromContent(engine, INLINE, content, { sourceId: 'default', noEmbed: true });+ await importSegmented(engine, SLUG, content);+ await seedLedger(engine, SLUG);+ await seedLedger(engine, INLINE);+ }, 240_000);++ test('a lead that holds a facts fence is overlaid alone: public rows show, withdrawn and private rows do not, no segment is read', async () => {+ const [row, inline] = await engine.executeRaw<{ slug: string; source_id: string; compiled_truth: string; body_storage: string }>(+ `SELECT p.slug, p.source_id, p.body_storage, ${boundedBodyPrefixSql('p')} AS compiled_truth FROM pages p WHERE p.slug = ANY($1::text[]) ORDER BY p.slug = $2 DESC`, [[SLUG, INLINE], SLUG]);+ expect([row!.body_storage, inline!.body_storage]).toEqual(['segmented', 'inline']);+ let segmentReads = 0;+ const read = engine.readSegmentTexts.bind(engine);+ engine.readSegmentTexts = async (sourceId, shas) => { segmentReads++; return read(sourceId, shas); };+ const [overlaid] = await overlaidBoundedRows(engine, [row!]);+ const lead = await projectedLead(engine, row!);+ engine.readSegmentTexts = read;+ expect(segmentReads).toBe(0);+ expect(lead).toContain(OPENING);+ expect(lead).toContain(PUBLIC.fact);+ expect(privateTokensIn(lead, { ledger: false })).toEqual([]);+ for (const token of [PRIVATE.withdrawn, PRIVATE.purged]) expect(lead).not.toContain(token);+ // The inline row's 65,536-character prefix is cut to bytes in coarser steps than the stored 64 KiB lead, so the+ // two leads end at different bytes; what a snippet shows is the same.+ const inlineLead = await projectedLead(engine, inline!);+ expect(inlineLead.length).toBeGreaterThan(4000);+ expect(lead.slice(0, 4000)).toBe(inlineLead.slice(0, 4000));+ expect(overlaid!.compiled_truth).toContain(PUBLIC.fact);+ expect(boundedProjectedPrefix(overlaid!.compiled_truth)).toBe(lead);+ }, 120_000);++ test('the exact-slug and alias snippets read the stored lead', async () => {+ await engine.setPageAliases(SLUG, 'default', [normalizeAlias('lead exemplar')]);+ const [exact] = await structuralExactLookup(engine, SLUG, { sourceId: 'default' });+ expect(exact?.slug).toBe(SLUG);+ expect(exact!.chunk_text).toContain('Lead Example runs research');+ const [alias] = await applyAliasHop(engine, [], 'lead exemplar', { sourceId: 'default' });+ expect(alias?.slug).toBe(SLUG);+ expect(alias!.chunk_text).toContain('Lead Example runs research');+ for (const text of [exact!.chunk_text, alias!.chunk_text]) expect(privateTokensIn(text, { ledger: false })).toEqual([]);+ }, 120_000);+ });+}diff --git a/test/large-pages/segmented-search-dedup.test.ts b/test/large-pages/segmented-search-dedup.test.tsnew file mode 100644index 0000000000..d9d2020fb0--- /dev/null+++ b/test/large-pages/segmented-search-dedup.test.ts@@ -0,0 +1,103 @@+/**+ * Wave B PR 2 (spec 7.5): search keeps up to six passages from one segmented+ * page when they are far apart.+ *+ * 1. Protects: hybridSearch (the fused path and the keyword-only path) hands+ * dedup the occurrence positions of a segmented page's hits, so three+ * regions more than 1 MiB apart keep two hits each, and an inline page in+ * the same result set keeps two.+ * 2. Fails when: a search path calls dedupResults without the regions (the+ * segmented page is capped at two like an inline page).+ * 3. Seams: the engine's search arms are replaced by fixed lists of real+ * chunk rows (one vector arm via queryEmbedFn, or the keyword arm with+ * embeddings opted out); dedup, segmentRegions and the post-fusion+ * stages run for real.+ */+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 { hybridSearch } from '../../src/core/search/hybrid.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import type { SearchResult } from '../../src/core/types.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { testBackends } from '../helpers/test-backends.ts';+import { mulberry32 } from '../helpers/seeded-random.ts';+import { importSegmented, pageContent } from '../helpers/segmented-privacy-fixture.ts';++const WORDS = ['zzregionone', 'zzregiontwo', 'zzregionthree'];++/** About `bytes` of prose whose words rarely repeat, so no two chunks are near-duplicates for dedup's text layer. */+function varied(r: () => number, bytes: number): string {+ const lines: string[] = [];+ for (let size = 0; size < bytes;) {+ const line = Array.from({ length: 12 }, () => Math.floor(r() * 36 ** 6).toString(36)).join(' ') + '.';+ lines.push(r() < 0.1 ? `${line}\n` : line);+ size += line.length + 1;+ }+ return `${lines.join('\n')}\n`;+}++for (const kind of testBackends()) {+ describe(`search dedup regions of a segmented page (${kind})`, () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ let rows: SearchResult[];++ 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 engine.setConfig('search.reranker.enabled', 'false');+ const r = mulberry32(503);+ await importSegmented(engine, 'chat/regions-example', pageContent(WORDS.map(w => `${varied(r, 1_200_000)}\n${w} opens this region\n`).join('')));+ await engine.setConfig('pages.segmented_storage', 'off');+ await importFromContent(engine, 'notes/inline-example', pageContent(Array.from({ length: 40 }, (_, i) => `## Part ${i}\n\nzzinline passage ${i} ${varied(r, 2_000)}`).join('\n')), { sourceId: 'default', noEmbed: true });+ const select = `SELECT p.slug, p.id AS page_id, p.title, p.type, p.source_id, cc.id AS chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source+ FROM content_chunks cc JOIN pages p ON p.id = cc.page_id`;+ const segmented: SearchResult[] = [];+ for (const word of WORDS) {+ const [hit] = await engine.executeRaw<SearchResult>(`${select} WHERE p.slug='chat/regions-example' AND cc.chunk_text LIKE $1 ORDER BY cc.chunk_index LIMIT 1`, [`%${word}%`]);+ const [next] = await engine.executeRaw<SearchResult>(`${select} WHERE p.slug='chat/regions-example' AND cc.chunk_index < $1 ORDER BY cc.chunk_index DESC LIMIT 1`, [hit!.chunk_index]);+ segmented.push(hit!, next!);+ }+ const inline = await engine.executeRaw<SearchResult>(`${select} WHERE p.slug='notes/inline-example' ORDER BY cc.chunk_index LIMIT 4`);+ rows = [...segmented, ...inline].map((row, i) => ({ ...row, page_id: Number(row.page_id), chunk_id: Number(row.chunk_id), score: 1 - i * 0.01, stale: false }));+ }, 300_000);++ afterAll(async () => { await close(); });++ const perPage = (results: SearchResult[]) => ({+ segmented: results.filter(r => r.slug === 'chat/regions-example').length,+ inline: results.filter(r => r.slug === 'notes/inline-example').length,+ });++ test('the fused path keeps two hits in each far region and two of the inline page', async () => {+ const searchVector = engine.searchVector;+ const searchKeyword = engine.searchKeyword;+ engine.searchVector = async () => rows.map(r => ({ ...r }));+ engine.searchKeyword = async () => [];+ try {+ const results = await hybridSearch(engine, 'regions', { expansion: false, limit: 20, queryEmbedFn: () => Float32Array.from({ length: 1536 }, (_, i) => i === 0 ? 1 : 0) });+ expect(perPage(results)).toEqual({ segmented: 6, inline: 2 });+ } finally {+ engine.searchVector = searchVector;+ engine.searchKeyword = searchKeyword;+ }+ }, 120_000);++ test('the keyword-only path keeps them too', async () => {+ const searchKeyword = engine.searchKeyword;+ engine.searchKeyword = async () => rows.map(r => ({ ...r }));+ try {+ const results = await hybridSearch(engine, 'regions', { expansion: false, limit: 20, _embeddingOptedOut: true });+ expect(perPage(results)).toEqual({ segmented: 6, inline: 2 });+ } finally {+ engine.searchKeyword = searchKeyword;+ }+ }, 120_000);+ });+}diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex a80539f95c..cdfb17b238 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -74,6 +74,10 @@ 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-evidence-read-cost.test.ts+test/large-pages/segmented-evidence.test.ts+test/large-pages/segmented-leads.test.ts+test/large-pages/segmented-search-dedup.test.tstest/large-pages/segmented-shrink-below-ceiling.test.tstest/large-pages/segmented-versions.test.tstest/link-cross-source.test.ts