Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

F2: search.long_page_unit delivers long non-conversation pages in a unit, off by default

garrytan975e57da2f19
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 43fe2751d5..1b0b1a7195 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,6 +12,7 @@ identifiers and attribution are available in the pre-removal Git revision
## [Unreleased: cat40 next wave part 1, version stamped at merge] - 2026-10-12
+- **Evidence delivery (F2 plumbing): long non-conversation pages can come back in a delivery unit, off by default.** New key `search.long_page_unit` (`off` default | `window` | `section` | `page`; `gbrain config set` refuses other values). Under the implied `auto` on `search` and `query`, a hit on a page whose stored body holds at least 8,000 bytes is delivered in that unit, counted in the existing delivery budget; every other hit keeps its ranked chunk. One precedence table (`docs/evidence-delivery.md`, "Long pages"): an explicit `return_unit`, then a non-`auto` `search.return_unit`, then this key; an explicit `token_budget` or `snippet_chars` keeps it off. The policy is resolved at the search/query caller (`withLongPagePolicy`), so recall, think and `assemble_evidence` are byte-identical with it on. `selectLongPages` runs one byte-count preflight under the read scope; at most 5 long pages and 1,000,000 body bytes per call are fetched in their own bounded batched call under a 2,000 ms deadline, whole pages only; any long page it cannot deliver keeps its ranked chunk (`delivered.reason: "long_page_chunk"`, a `long_page_*` fallback code). Lean rows keep `delivered: {unit, reason}` on long-page rows (plus `truncated: true` when cut); every other lean row keeps `{truncated: true}` only. The off path is byte-identical (`test/evidence-delivery-golden.test.ts` unchanged); a second frozen golden pins the on path (`test/fixtures/goldens/evidence-delivery/long-page-on-path.json`). Tests: `test/evidence-long-page.test.ts` (PGLite), `test/e2e/evidence-long-page.test.ts` (Postgres). No passage selector is built; the unit is chosen later by the frozen-hit comparison.
- **Served instructions (F4): the record in effect on the date asked about governs, not the newest one.** Instruction 7 now reads "The record whose terms are in effect on the date asked about governs: a page's `date`/`effective_date` is when it was written, not when its terms take effect, and a change not yet effective does not apply yet; drafts, proposals and agent-written notes do not override records." (`date` is named only where `entity` is callable). It replaces "prefer the newest governing source: a later correction, handoff or executed change outranks an older record". The rule now leads the answering clause and ends inside the first 2,048 characters capped harnesses read (starter 1,566–1,842, full 1,717–1,993; it started at 1,943 and 2,094). New key `mcp.instructions_governing_rule` (`in_effect` default, `newest` serves the earlier sentence for measurement). Budget: the sentence is 74 characters longer; 11 are paid by cutting "the best-ranked excerpts" to "top excerpts" in the same clause, and +63 is recorded in `test/mcp-schema-budget.test.ts` (5,108 for the maximal rendering). Tests: `test/mcp-instructions-governing-rule.test.ts`.
- **Served instructions (d5b): the brief clause no longer recommends a `referenced_by` walk batch mode cannot do.** `src/mcp/instructions.ts`: the walk is on the single-name `entity` card, and the clause names what a compact `entity names` row carries on this brain (its `next` to the card while `entity.names_references` is on, the default; `records` by type once `entity.record_types` enrolls page types, empty by default). Every transport reads both keys at initialize through `readInstructionContent` (fail-closed to the defaults); the static contract, bootstrap's instructions file and the SDK constructor fallback are the defaults rendering. One reader module, `src/core/entity-references-config.ts`, serves both keys. Budget: +70 characters for the maximal rendering (+39 at the default), recorded in `test/mcp-schema-budget.test.ts` and `test/mcp-initialize-instructions.test.ts`. Tests: `test/mcp-instructions-references.test.ts`.
diff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.md
index c586397b33..a769ecf5d7 100644
--- a/docs/architecture/key-files/core-search-2.md
+++ b/docs/architecture/key-files/core-search-2.md
@@ -7,7 +7,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`. 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`.
+- `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` under an implied `auto` with no explicit budget or `snippet_chars`; `selectLongPages` runs one byte-count preflight under the read scope (long = `LONG_PAGE_MIN_BYTES` 8,000; 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`.
- `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`.
- `src/core/search/entity-anchor.ts` — entity-anchored retrieval: `entityAnchoredPages` (the entity page plus up to 10 pages that link to it or name it as a word, newest by `COALESCE(effective_date, updated_at)`; question/synthesis/pinned-question pages excluded) and `prefixAnchoredPages`, shared by pinned-question refresh (`questions/refresh.ts` `anchoredSlugs`) and the `query`/`search` ops; `asksForCurrentState` (deterministic cue regex), `namedEntity` (exactly one `isFactEntityPage` page whose title `isTitleMentionedInQuery` matches, the title match before the read-policy filter; a title inside a longer matched title is the same mention); `applyEntityAnchoring` (anchored rows first, at most half the row count, organic rows of the same page moved up, missing pages read through `getChunkWindows` under the caller's scope, rows stamped `entity_anchored`, token budget re-applied, fail-open); `entityAnchoringEnabled` (`search.entity_anchoring`, default off). Tests: `test/search-entity-anchor.test.ts`. Gates: `docs/eval/decisions/entity-anchoring-query/`.
diff --git a/docs/evidence-delivery.md b/docs/evidence-delivery.md
index cd23b04f24..380c6cd233 100644
--- a/docs/evidence-delivery.md
+++ b/docs/evidence-delivery.md
@@ -82,6 +82,9 @@ Per-call params on `search`, `query`, `recall`:
- `return_unit`: `chunk` | `window` | `section` | `page` | `auto`. Default from
config `search.return_unit` (default `auto`).
+- `search.long_page_unit` (config only, default `off`): `window` | `section` |
+ `page` for long non-conversation hits under the implied `auto`; see
+ [Long pages](#long-pages-searchlong_page_unit).
- `return_window`: integer 1–3, default from `search.return_window` (default 1).
Used by `window` (and by the `section` fallback to `window`).
- Budget: `token_budget` on `search` / `query`, `budget_tokens` on `recall`.
@@ -177,6 +180,67 @@ explicit budget never returns less than `chunk` would, and `budget_used`
exceeds `budget_tokens` only by such unchanged chunks. An explicit budget
changes this; see the next section.
+### Long pages (`search.long_page_unit`)
+
+Off by default. `gbrain config set search.long_page_unit section` (or `window`,
+`page`; `off` turns it back off) makes `search` and `query` deliver a **long
+non-conversation hit** in that unit under the implied `auto`, the way `auto`
+already delivers conversations whole. Every other hit keeps its ranked chunk
+unchanged. The value is a delivery unit from the table above and the unit
+algorithms are the same; nothing selects passages by term overlap, so the
+delivered unit is always the one around the ranked hit.
+
+**Which unit applies.** One table decides, per call and hit:
+
+| # | Source | When it applies | Unit |
+|---|---|---|---|
+| 1 | `return_unit` on the call | always (`auto` included: an explicit `auto` keeps every non-conversation chunk) | that unit |
+| 2 | `search.return_unit` set to anything but `auto` | `return_unit` omitted | that unit, every hit |
+| 3 | `search.long_page_unit` (not `off`) | `return_unit` omitted, `search.return_unit` unset or `auto`, no explicit `token_budget`, no explicit `snippet_chars`, and the hit is a long non-conversation page | that unit (`delivered.reason: "long_page"`) |
+| 4 | implied `auto` | everything else | conversations whole, other hits their ranked chunk |
+
+The policy is resolved at the `search`/`query` caller and passed to the
+assembler, so `recall`, `think` (`think.return_unit`) and `assemble_evidence`
+never read the key and stay byte-identical with it on. An explicit
+`snippet_chars` keeps it off because a cut from the front could drop the hit;
+an explicit `token_budget` keeps it off because the cap (next section) keeps
+its own rules, and `query`'s bare `token_budget` is chunk-mode budgeting anyway.
+The subagent default snippet cap already keeps the implied `auto` on `chunk`.
+
+**What is long.** A page whose stored body (compiled truth plus timeline;
+compiled truth only under `detail: "low"`) holds at least **8,000 bytes**
+(`LONG_PAGE_MIN_BYTES`, about 2,000 tokens or four chunks). Conversation pages
+(see [Conversation detection](#conversation-detection)) and saved-fact rows are
+never long pages.
+
+**Limits.** One size preflight query reads the byte counts of the hit pages
+under the caller's read scope; it never reads a body. Then, in rank order, at
+most **5** long pages (`LONG_PAGE_MAX_PAGES`) holding at most **1,000,000**
+stored-body bytes together (`LONG_PAGE_MAX_INPUT_BYTES`) are fetched in one
+bounded batched call of their own, so they can neither slow nor fail the
+conversation fetch. A page that would cross a limit is skipped whole, never
+sliced: bodies are sanitized whole before any cut. Preflight plus fetch share
+a cooperative **2,000 ms** deadline (`LONG_PAGE_DEADLINE_MS`). A long page that
+cannot be delivered in its unit keeps its ranked chunk, byte-identical to the
+off path, with `delivered.reason: "long_page_chunk"` and a fallback code
+saying why (below). A preflight that fails or misses the deadline leaves the
+call on the off path.
+
+**Budget.** Long pages are counted in the same delivery budget as
+conversations (`search.return_budget_conversation`, default 24,000, clamped for
+remote callers): unchanged chunks are paid for first, then conversations and
+long pages reserve their matching span and grow in rank order. A long page
+whose matching span no longer fits keeps its ranked chunk
+(`long_page_chunk`, fallback `long_page_over_budget`), so the key never returns
+less than `chunk` would.
+
+**Response.** A long-page block is an ordinary delivered row (`delivered.unit`
+is the unit that ran; a `section` with no structure falls back to `window`
+with `no_section_structure`). Lean rows (the remote default) keep
+`delivered: { unit, reason }` on both long-page reasons, plus `truncated: true`
+when cut; every other lean row keeps only `{ truncated: true }`. A response
+with no long page and no conversation is byte-identical to the key off.
+
### Explicit budgets (the cap)
When the caller passes a budget (`token_budget` on `query`, `search` and
@@ -243,7 +307,8 @@ so a bare budget does not engage the cap.
3. Then the subagent default snippet cap (`agent.search_snippet_chars`, 300):
when it applies, neither the implied `auto` nor a config-level
`search.return_unit` expands.
-4. Then `search.return_unit` from config, else `auto`.
+4. Then `search.return_unit` from config, else `auto` (with `search.long_page_unit`
+ for long non-conversation hits, which an explicit `snippet_chars` keeps off).
## Response shape (additive)
@@ -265,7 +330,7 @@ so those responses carry neither `delivered` nor `delivery`.
"revision": "3f0c…", // pages.knowledge_revision the text was read from
"unmapped_chunk_ids": [], // hits whose chunk is no longer in the current revision (present only when non-empty)
"fallback_reason": "fetch_failed", // present only when the block fell back to the hit chunk text
- "reason": "conversation_type" // auto only: conversation_type | conversation_slug | not_conversation | conversation_over_budget
+ "reason": "conversation_type" // auto only: conversation_type | conversation_slug | not_conversation | conversation_over_budget | saved_fact | long_page | long_page_chunk
}
```
@@ -328,6 +393,9 @@ delivered text and each result gains `delivered`.
| `budget_clamped` | A remote budget above the max was clamped. | Clamped budget. |
| `tokenizer_heuristic` | cl100k unavailable; char/4 heuristic used. | Counts from the heuristic. |
| `date_header_unavailable` | Date headers are on but the page dates could not be read. | Every header reads `[observed unknown]`. |
+| `long_page_pages` / `long_page_bytes` | `search.long_page_unit`: the long page came after 5 long pages, or would cross 1,000,000 stored-body bytes. | Its ranked chunk (`reason: long_page_chunk`). |
+| `long_page_over_budget` | `search.long_page_unit`: the long page's matching span no longer fit the budget. | Its ranked chunk (`reason: long_page_chunk`). |
+| `long_page_deadline` / `long_page_fetch_failed` / `long_page_preflight_failed` | `search.long_page_unit`: the size preflight or the long-page fetch missed the 2,000 ms deadline or failed. | Its ranked chunk (`reason: long_page_chunk`); a failed preflight leaves the call on the off path. |
| drop `not_readable` | The page is no longer readable by this caller (deleted, private, grant revoked, quarantined, archived source, source outside scope). | Result removed. Never falls back to cached text. |
| `snippet_marker_omitted` | Under an explicit `auto` budget, a row's allocation could not hold the snippet recovery marker. | Capped block without the marker, `truncated: true`. |
| drop `budget_floor` | Not even the block's matching span fits the remaining budget. | Result removed (rank one is instead cut to fit). Under `auto` without an explicit budget nothing is dropped for budget: the conversation keeps its ranked chunks. |
@@ -377,7 +445,9 @@ warning naming the minimum server version.
part of delivered text; `page` text is the sanitized body only.
- **Non-mutation.** The stage returns new result objects and never mutates or
caches expanded text.
-- **Bounded work.** One engine query per request. It reads each hit page's
+- **Bounded work.** One engine query per request (with `search.long_page_unit`
+ on and a long page among the hits: plus one size preflight and one bounded
+ long-page fetch, see [Long pages](#long-pages-searchlong_page_unit)). It reads each hit page's
body once (bounded by the import size cap) plus the chunks within
±`return_window` of each hit; each block ≤ 60,000 characters (under the
64 KiB output-redaction field limit).
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 1addd89c48..2143f4479a 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -36,12 +36,12 @@ src/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0
src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refresh
src/commands/hook.ts 1932 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + import; +2 fix wave 11 integration: W1 router help guard import beside the W2 managed-root import; +2 fix wave 13 P4.9 #6399: a header-only Codex rollout ends empty_session, not parser_drift; +3 W14 P4.16 (#5799): banner and SessionStart note read livePushStatuses (predicate in core/workspace-push.ts); +1 W15 P5.7 (#4992): gitChildEnv import for the hook git probes (launches moved onto core/spawn.ts)
src/core/chunkers/code.ts 1602 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts); +10 Lua grammar swap: GRAMMAR_REVISIONS + chunkerStamp() (per-language re-chunk gate); +4: CodeChunkOptions.timeoutMs (per-call parse cap; markdown fences parse under a short cap) and the "Parsing failed" → ChunkerTimeoutError mapping in parseWithTimeout
-src/core/config.ts 1957 ratchet +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +2 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types (one line) and mcp.instructions_governing_rule
+src/core/config.ts 1958 ratchet +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types (one line), mcp.instructions_governing_rule and search.long_page_unit
src/core/bootstrap/harness.ts 2610 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts)
src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option
src/core/ops/pages.ts 683 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept)
src/core/search/mode.ts 1594 ratchet +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)
src/commands/eval-longmemeval.ts 1519 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)
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 1512 ratchet 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)
+src/core/search/evidence-delivery.ts 1631 ratchet 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)
src/commands/config.ts 1507 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
diff --git a/src/core/config.ts b/src/core/config.ts
index 2053f602ac..8a17514142 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1406,6 +1406,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
'search.return_budget_conversation',
'search.return_budget_max_remote',
'search.auto_packing',
+ 'search.long_page_unit', // F2: delivery unit for long non-conversation hits under an implied auto: off (default) | window | section | page (search/evidence-delivery.ts)
'search.evidence_date_header', // C1: one-line date header per delivered block (default off; search/evidence-date.ts)
'search.entity_anchoring', // entity-anchored retrieval for entity-scoped current-state query/search (default off; search/entity-anchor.ts)
'search.query_facts_arm', // query adds matching active facts as rows in spare capacity (default on; search/facts-arm.ts)
diff --git a/src/core/ops/search.ts b/src/core/ops/search.ts
index e7560743b0..ecd16f2d18 100644
--- a/src/core/ops/search.ts
+++ b/src/core/ops/search.ts
@@ -34,7 +34,7 @@ import { redactRetrievalOutput } from '../search/output-redaction.ts';
import { projectRows, resultRowsFor } from '../search/lean-rows.ts';
import { buildScoreDetails } from '../search/explain-formatter.ts';
import { TargetTrace, diagnoseProbe, diagnoseTrace, probeTarget, type ExplainTargetDiagnosis } from '../search/explain-target.ts';
-import { assembleEvidenceForHits, capDeliveredSnippets, capEvidenceToBudget, deliverEvidence, effectivePlan, pagePlanHits, resolveEvidencePlan, unsupportedDelivery, type DeliveryMeta, type DeliveryScope, type EvidencePlan, type FrozenHit, type ReturnUnit } from '../search/evidence-delivery.ts';
+import { assembleEvidenceForHits, capDeliveredSnippets, capEvidenceToBudget, deliverEvidence, pagePlanHits, resolveEvidencePlan, selectLongPages, unsupportedDelivery, withLongPagePolicy, type DeliveryMeta, type DeliveryScope, type EvidencePlan, type FrozenHit, type ReturnUnit } from '../search/evidence-delivery.ts';
import { privateProvenanceFilterFragment, resolveExcludePrivatePages } from '../search/private-visibility.ts';
import { AUDIT_ROW_SOURCES } from '../facts/audit-sources.ts';
import { SAFE_FENCE_CHUNKER_VERSION } from '../search/safe-chunks.ts';
@@ -150,10 +150,11 @@ const RETURN_WINDOW_PARAM = {
/**
* With a plan, `token_budget` budgets the delivered evidence, so query's
* chunk-level budget stays off; query's token_budget without a return_unit
- * keeps its chunk-mode meaning.
+ * keeps its chunk-mode meaning. The long-page policy (`search.long_page_unit`)
+ * is resolved here, at the search/query caller, and nowhere else.
*/
async function evidencePlanFor(ctx: OperationContext, p: Record<string, unknown>, snippetCap: number, op: 'search' | 'query'): Promise<EvidencePlan | null> {
- return resolveEvidencePlan(ctx.engine, {
+ return withLongPagePolicy(ctx.engine, await resolveEvidencePlan(ctx.engine, {
legacyBudget: op === 'query' && typeof p.token_budget === 'number',
remote: ctx.remote,
viaSubagent: ctx.viaSubagent,
@@ -163,7 +164,7 @@ async function evidencePlanFor(ctx: OperationContext, p: Record<string, unknown>
snippetChars: p.snippet_chars,
snippetCap,
op,
- });
+ }), { snippetChars: p.snippet_chars });
}
/**
@@ -173,9 +174,10 @@ async function evidencePlanFor(ctx: OperationContext, p: Record<string, unknown>
*/
async function withEvidence(ctx: OperationContext, p: Record<string, unknown>, results: SearchResult[], plan: EvidencePlan | null,
scope: DeliveryScope, meta: HybridSearchMeta | null): Promise<{ rows: SearchResult[]; evidence?: { delivery: DeliveryMeta; explicitSnippet: boolean } }> {
- const applied = effectivePlan(plan, results);
+ const deliveryScope = { ...scope, requireSafeChunks: ctx.remote !== false };
+ const { plan: applied, longPages } = await selectLongPages(ctx.engine, plan, results, deliveryScope);
if (!applied) return { rows: results };
- const d = await deliverEvidence(ctx.engine, results, applied, { ...scope, requireSafeChunks: ctx.remote !== false }, { liveHits: meta?.cache?.status !== 'hit' });
+ const d = await deliverEvidence(ctx.engine, results, applied, deliveryScope, { liveHits: meta?.cache?.status !== 'hit', ...(longPages ? { longPages } : {}) });
return { rows: d.results, evidence: { delivery: d.delivery, explicitSnippet: typeof p.snippet_chars === 'number' && Number.isFinite(p.snippet_chars) } };
}
diff --git a/src/core/search/config-values.ts b/src/core/search/config-values.ts
index 476b0c7e0e..78d80e75b7 100644
--- a/src/core/search/config-values.ts
+++ b/src/core/search/config-values.ts
@@ -6,6 +6,7 @@
import { HNSW_ITERATIVE_SCAN_KEY, HNSW_ITERATIVE_SCAN_MODES, hnswIterativeScanValueProblem } from './hnsw-iterative-scan.ts';
import { CJK_KEYWORD_DEADLINE_DEFAULT_MS, CJK_KEYWORD_DEADLINE_KEY, cjkKeywordDeadlineValueProblem } from './cjk-keyword-deadline.ts';
import { AUTO_PACKING_CONFIG_KEY, DEFAULT_AUTO_PACKING, autoPackingValueProblem } from './evidence-packing.ts';
+import { LONG_PAGE_UNIT_CONFIG_KEY, longPageUnitValueProblem } from './evidence-delivery.ts';
interface SearchValueRule {
problem: (value: string) => string | null;
@@ -17,6 +18,7 @@ export const SEARCH_VALUE_RULES: Readonly<Record<string, SearchValueRule>> = {
[HNSW_ITERATIVE_SCAN_KEY]: { problem: hnswIterativeScanValueProblem, example: HNSW_ITERATIVE_SCAN_MODES[0] },
[CJK_KEYWORD_DEADLINE_KEY]: { problem: cjkKeywordDeadlineValueProblem, example: String(CJK_KEYWORD_DEADLINE_DEFAULT_MS) },
[AUTO_PACKING_CONFIG_KEY]: { problem: autoPackingValueProblem, example: DEFAULT_AUTO_PACKING },
+ [LONG_PAGE_UNIT_CONFIG_KEY]: { problem: longPageUnitValueProblem, example: 'section' },
};
/** The refusal for an invalid value of a validated `search.*` key, or null. */
diff --git a/src/core/search/evidence-delivery.ts b/src/core/search/evidence-delivery.ts
index 64ceda6077..3e472f9ff3 100644
--- a/src/core/search/evidence-delivery.ts
+++ b/src/core/search/evidence-delivery.ts
@@ -79,7 +79,9 @@ export interface MatchSpan { chunk_id: number; start: number; end: number }
* a conversation whose matching span no longer fits the budget keeps its
* ranked chunks too.
*/
-export type AutoReason = 'conversation_type' | 'conversation_slug' | 'not_conversation' | 'conversation_over_budget' | 'saved_fact';
+export type AutoReason = 'conversation_type' | 'conversation_slug' | 'not_conversation' | 'conversation_over_budget' | 'saved_fact'
+ /** `search.long_page_unit` delivered this long page in its unit; `long_page_chunk`: it kept its ranked chunk (`delivery.fallbacks` says why). */
+ | 'long_page' | 'long_page_chunk';
export interface DeliveredEvidence {
unit: DeliveredUnit;
@@ -130,6 +132,8 @@ export interface EvidencePlan {
budgetClamped?: { requested: number; max: number };
/** `search.evidence_date_header` is on: each block starts with its date header line. */
dateHeader?: true;
+ /** F2: set only by the search/query caller (withLongPagePolicy); recall, think and assemble_evidence never carry it. */
+ longPage?: LongPagePolicy;
}
/** The cap runs only under `auto`, with a budget the caller passed and a packing other than `off`. */
@@ -314,6 +318,91 @@ export function effectivePlan(plan: EvidencePlan | null, hits: SearchResult[]):
return hits.some(h => conversationSignal(h) !== null) ? plan : null;
}
+// ---------------------------------------------------------------------------
+// auto: long non-conversation pages (search.long_page_unit, F2)
+// ---------------------------------------------------------------------------
+
+export const LONG_PAGE_UNIT_CONFIG_KEY = 'search.long_page_unit';
+export const LONG_PAGE_UNITS = ['off', 'window', 'section', 'page'] as const;
+export type LongPageUnit = Exclude<typeof LONG_PAGE_UNITS[number], 'off'>;
+/** A page is long when its stored body (compiled truth, plus timeline unless `detail: "low"`) holds this many bytes: about 2,000 tokens, four or more chunks. */
+export const LONG_PAGE_MIN_BYTES = 8_000;
+/** Long pages per call that get the unit, in rank order; later ones keep their chunk (`long_page_pages`). */
+export const LONG_PAGE_MAX_PAGES = 5;
+/** Stored-body bytes those pages may bring in; a page that would cross it keeps its chunk (`long_page_bytes`), since bodies are read whole and never sliced. */
+export const LONG_PAGE_MAX_INPUT_BYTES = 1_000_000;
+/** Cooperative deadline for the size preflight plus the long-page fetch (`long_page_deadline`). */
+export const LONG_PAGE_DEADLINE_MS = 2_000;
+
+export interface LongPagePolicy { unit: LongPageUnit }
+
+/** The long pages one call delivers in the policy's unit, and the ones that keep their chunk (page id → fallback code). */
+export interface LongPageSelection {
+ unit: LongPageUnit;
+ pages: ReadonlySet<number>;
+ kept: ReadonlyMap<number, string>;
+ deadlineAt: number;
+ fallbacks: string[];
+}
+
+export function longPageUnitValueProblem(value: string): string | null {
+ return (LONG_PAGE_UNITS as readonly string[]).includes(value.trim()) ? null : `${LONG_PAGE_UNIT_CONFIG_KEY} must be one of ${LONG_PAGE_UNITS.join(', ')} (got ${JSON.stringify(value.slice(0, 40))}).`;
+}
+
+/**
+ * The F2 policy for a search/query call. It applies only under an implied
+ * `auto`: no `return_unit` on the call, `search.return_unit` unset or `auto`,
+ * no explicit budget (the cap keeps its rules) and no explicit `snippet_chars`
+ * (a head cut could drop the hit). Read errors and unknown values are `off`.
+ */
+export async function withLongPagePolicy(engine: BrainEngine, plan: EvidencePlan | null, input: { snippetChars: unknown }): Promise<EvidencePlan | null> {
+ if (!plan || plan.unit !== 'auto' || plan.explicitUnit || plan.budgetExplicit) return plan;
+ if (typeof input.snippetChars === 'number' && Number.isFinite(input.snippetChars)) return plan;
+ const raw = (await engine.getConfig(LONG_PAGE_UNIT_CONFIG_KEY).catch(() => null))?.trim();
+ return raw === 'window' || raw === 'section' || raw === 'page' ? { ...plan, longPage: { unit: raw } } : plan;
+}
+
+/**
+ * The plan to run for these hits once the long-page policy is applied: a
+ * size preflight (one query, the caller's read scope) finds the long
+ * non-conversation pages and keeps the rank-order ones inside the page and
+ * byte limits. With no long page this is exactly effectivePlan, so a
+ * response without one is unchanged; a failed or late preflight is too.
+ */
+export async function selectLongPages(engine: BrainEngine, plan: EvidencePlan | null, hits: SearchResult[], scope: DeliveryScope): Promise<{ plan: EvidencePlan | null; longPages?: LongPageSelection }> {
+ const base = effectivePlan(plan, hits);
+ if (!plan?.longPage) return { plan: base };
+ const deadlineAt = Date.now() + LONG_PAGE_DEADLINE_MS;
+ const ids: number[] = [];
+ for (const h of hits) if (!h.fact_row && conversationSignal(h) === null && Number.isFinite(h.page_id) && !ids.includes(h.page_id)) ids.push(h.page_id);
+ if (ids.length === 0) return { plan: base };
+ let bytes: Map<number, number>;
+ try {
+ const params: unknown[] = [ids];
+ const filter = pageReadFilter('p', scope, params, true);
+ const timeline = scope.detail === 'low' ? '' : ` + octet_length(COALESCE(p.timeline, ''))`;
+ const rows = await withTimeout(engine.executeRaw<{ id: number; bytes: number }>(
+ `SELECT p.id, octet_length(COALESCE(p.compiled_truth, ''))${timeline} AS bytes FROM pages p
+ WHERE p.id = ANY($1::int[]) AND ${filter} AND ${currentTextProjectionFilter('p')}${requiresSafeChunks(scope) ? ` AND ${safeChunksFilter('p')}` : ''}`,
+ params), LONG_PAGE_DEADLINE_MS);
+ bytes = new Map(rows.map(r => [Number(r.id), Number(r.bytes)]));
+ } catch (e) {
+ return { plan: base, ...(base ? { longPages: { unit: plan.longPage.unit, pages: new Set(), kept: new Map(), deadlineAt, fallbacks: [e instanceof EvidenceTimeout ? 'long_page_deadline' : 'long_page_preflight_failed'] } } : {}) };
+ }
+ const pages = new Set<number>();
+ const kept = new Map<number, string>();
+ let total = 0;
+ for (const id of ids) {
+ const size = bytes.get(id);
+ if (size === undefined || size < LONG_PAGE_MIN_BYTES) continue;
+ if (pages.size >= LONG_PAGE_MAX_PAGES) kept.set(id, 'long_page_pages');
+ else if (total + size > LONG_PAGE_MAX_INPUT_BYTES) kept.set(id, 'long_page_bytes');
+ else { pages.add(id); total += size; }
+ }
+ if (pages.size === 0 && kept.size === 0) return { plan: base };
+ return { plan, longPages: { unit: plan.longPage.unit, pages, kept, deadlineAt, fallbacks: [] } };
+}
+
// ---------------------------------------------------------------------------
// Tokens
// ---------------------------------------------------------------------------
@@ -650,7 +739,7 @@ function sectionCandidates(doc: Doc, anchors: Anchor[], conversation: boolean):
return set.size === 0 ? null : [...set].sort((x, y) => x - y);
}
-function planBlock(page: ChunkWindowPage, hits: SearchResult[], plan: EvidencePlan, includeTimeline: boolean): PlannedBlock {
+function planBlock(page: ChunkWindowPage, hits: SearchResult[], requested: Exclude<ReturnUnit, 'chunk' | 'auto'>, radius: number, includeTimeline: boolean): 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');
@@ -669,7 +758,7 @@ function planBlock(page: ChunkWindowPage, hits: SearchResult[], plan: EvidencePl
const labels = doc.pieces.map(p => p.speaker).filter((x): x is string => x !== null);
const conversation = isConversationLabels(labels);
const hasHeadings = doc.pieces.some(p => p.heading > 0);
- let unit: DeliveredUnit = plan.unit === 'auto' ? 'page' : plan.unit;
+ let unit: DeliveredUnit = requested;
let fallbackReason: string | undefined;
let candidates: number[];
if (unit === 'page') {
@@ -679,11 +768,11 @@ function planBlock(page: ChunkWindowPage, hits: SearchResult[], plan: EvidencePl
if (sec) candidates = sec;
else {
unit = 'window';
- if (plan.unit === 'section') fallbackReason = 'no_section_structure';
- candidates = windowCandidates(doc, anchors, plan.window);
+ fallbackReason = 'no_section_structure';
+ candidates = windowCandidates(doc, anchors, radius);
}
} else {
- candidates = windowCandidates(doc, anchors, plan.window);
+ candidates = windowCandidates(doc, anchors, radius);
}
return {
hit: best, hits, doc, unit, candidates, anchors,
@@ -1011,6 +1100,8 @@ export interface DeliverOptions {
*/
liveHits?: boolean;
timeoutMs?: number;
+ /** F2: the long pages selectLongPages chose for these hits (search/query only). */
+ longPages?: LongPageSelection;
}
function withTimeout<T>(p: Promise<T>, ms: number): Promise<T> {
@@ -1046,50 +1137,69 @@ export async function deliverEvidence(
type Group = { pageId: number | null; hits: SearchResult[]; rank: number; reason?: AutoReason };
const groups: Group[] = [];
const byPage = new Map<number, Group>();
+ const long = auto ? opts.longPages : undefined;
+ for (const code of long?.fallbacks ?? []) fallbacks.add(code);
hits.forEach((h, rank) => {
// A saved-fact row (facts arm) has no page to expand: it is delivered as written, paid for first.
if (h.fact_row) { passthrough.push({ rank, hit: h, reason: 'saved_fact' }); return; }
const signal = auto ? conversationSignal(h) : null;
- if (auto && !signal) { passthrough.push({ rank, hit: h, reason: 'not_conversation' }); return; }
+ const longPage = !signal && long?.pages.has(h.page_id) === true;
+ if (auto && !signal && !longPage) {
+ const code = long?.kept.get(h.page_id);
+ if (code) fallbacks.add(code);
+ passthrough.push({ rank, hit: h, reason: code ? 'long_page_chunk' : 'not_conversation' });
+ return;
+ }
const id = Number.isFinite(h.page_id) ? h.page_id : null;
const g = id === null ? undefined : byPage.get(id);
if (g) { g.hits.push(h); return; }
- const ng: Group = { pageId: id, hits: [h], rank, ...(signal ? { reason: signal } : {}) };
+ const ng: Group = { pageId: id, hits: [h], rank, ...(signal ? { reason: signal } : longPage ? { reason: 'long_page' as const } : {}) };
if (id !== null) byPage.set(id, ng);
groups.push(ng);
});
// Chunks only anchor hits in the page text; every unit but window (and the
- // section fallback to window) needs just the hit chunks themselves.
- const radius = plan.window;
- const requests: ChunkWindowRequest[] = [];
- groups.forEach((g, rank) => {
- if (g.pageId === null) return;
- for (const h of g.hits) {
- const at = Number.isFinite(h.chunk_index) ? h.chunk_index : 0;
- requests.push({ page_id: g.pageId, from_index: Math.max(0, at - radius), to_index: at + radius, priority: rank });
- }
- });
- const maxRows = Math.min(MAX_ROWS, requests.reduce((n, r) => n + (r.to_index - r.from_index + 1), 0));
-
- let pages: Map<number, ChunkWindowPage> | null = null;
- let fetchFailure: string | null = null;
- if (requests.length > 0) {
+ // section fallback to window) needs just the hit chunks themselves. Long
+ // pages (F2) are read in their own bounded call under the long-page
+ // deadline, so they can neither slow nor fail the conversation fetch.
+ const fetchPages = async (want: Group[], timeoutMs: number): Promise<Map<number, ChunkWindowPage> | string> => {
+ const requests: ChunkWindowRequest[] = [];
+ want.forEach((g, rank) => {
+ if (g.pageId === null) return;
+ for (const h of g.hits) {
+ const at = Number.isFinite(h.chunk_index) ? h.chunk_index : 0;
+ requests.push({ page_id: g.pageId, from_index: Math.max(0, at - plan.window), to_index: at + plan.window, priority: rank });
+ }
+ });
+ if (requests.length === 0) return new Map();
+ if (timeoutMs <= 0) return 'fetch_timeout';
try {
const rows = await withTimeout(engine.getChunkWindows(requests, {
...(scope.sourceIds && scope.sourceIds.length > 0 ? { sourceIds: scope.sourceIds } : scope.sourceId ? { sourceId: scope.sourceId } : {}),
excludePrivate: scope.excludePrivate,
requireSafeChunks: requiresSafeChunks(scope),
chunkSources: scope.detail === 'low' ? ['compiled_truth'] : ['compiled_truth', 'timeline'],
- maxRows,
- }), opts.timeoutMs ?? EVIDENCE_FETCH_TIMEOUT_MS);
+ 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 });
- pages = new Map(rows.map(p => [p.page_id, p]));
+ return new Map(rows.map(p => [p.page_id, p]));
} catch (e) {
- fetchFailure = e instanceof EvidenceTimeout ? 'fetch_timeout' : 'fetch_failed';
- fallbacks.add(fetchFailure);
+ return e instanceof EvidenceTimeout ? 'fetch_timeout' : 'fetch_failed';
}
- }
+ };
+ const longGroups = groups.filter(g => g.reason === 'long_page');
+ const [mainFetch, longFetch] = await Promise.all([
+ fetchPages(groups.filter(g => g.reason !== 'long_page'), opts.timeoutMs ?? EVIDENCE_FETCH_TIMEOUT_MS),
+ long && longGroups.length > 0 ? fetchPages(longGroups, long.deadlineAt - Date.now()) : Promise.resolve(new Map<number, ChunkWindowPage>()),
+ ]);
+ const pages = typeof mainFetch === 'string' ? null : mainFetch;
+ const fetchFailure = typeof mainFetch === 'string' ? mainFetch : null;
+ if (fetchFailure) fallbacks.add(fetchFailure);
+ // A long page that cannot be delivered in its unit keeps its ranked chunks, exactly as with the policy off.
+ const keepChunks = (g: Group, code: string) => {
+ fallbacks.add(code);
+ for (const h of g.hits) passthrough.push({ rank: hits.indexOf(h), hit: h, reason: 'long_page_chunk' });
+ };
// C1 date headers: one line per block (passthrough rows included), paid for inside the budget like the title.
const headerFor = plan.dateHeader ? await blockDateHeaders(engine, hits, () => fallbacks.add('date_header_unavailable')) : () => '';
@@ -1097,7 +1207,13 @@ export async function deliverEvidence(
const planned: Block[] = [];
for (const g of groups) {
let b: PlannedBlock;
- if (g.pageId === null) {
+ if (g.reason === 'long_page') {
+ if (typeof longFetch === 'string') { keepChunks(g, longFetch === 'fetch_timeout' ? 'long_page_deadline' : 'long_page_fetch_failed'); continue; }
+ const page = longFetch.get(g.pageId!);
+ if (!page) { dropped.not_readable = (dropped.not_readable ?? 0) + 1; continue; }
+ b = planBlock(page, g.hits, long!.unit, plan.window, scope.detail !== 'low');
+ if (b.unit === 'chunk') { keepChunks(g, b.fallbackReason ?? 'long_page_fallback'); continue; }
+ } else if (g.pageId === null) {
b = fallbackBlock(g.hits[0], g.hits, 'page_missing');
} else if (fetchFailure) {
if (opts.liveHits === false) { dropped.not_readable = (dropped.not_readable ?? 0) + 1; continue; }
@@ -1105,7 +1221,7 @@ 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, scope.detail !== 'low');
+ b = planBlock(page, g.hits, plan.unit === 'auto' ? 'page' : plan.unit, plan.window, scope.detail !== 'low');
}
if (b.fallbackReason) fallbacks.add(b.fallbackReason);
const title = b.hit.title ?? '';
@@ -1124,7 +1240,10 @@ export async function deliverEvidence(
// whose matching span no longer fits keeps its ranked chunks instead.
const reserved = passthrough.reduce((n, p) => n + countEvidenceTokens(headerFor(p.hit) + (p.hit.chunk_text ?? ''), tokenizer) + countEvidenceTokens(p.hit.title ?? '', tokenizer), 0);
kept = allocate(planned, Math.max(0, plan.budgetTokens - reserved), tokenizer, dropped, auto
- ? b => { for (const h of b.hits) passthrough.push({ rank: hits.indexOf(h), hit: h, reason: 'conversation_over_budget' }); }
+ ? b => {
+ if (b.reason === 'long_page') fallbacks.add('long_page_over_budget');
+ for (const h of b.hits) passthrough.push({ rank: hits.indexOf(h), hit: h, reason: b.reason === 'long_page' ? 'long_page_chunk' : 'conversation_over_budget' });
+ }
: undefined);
}
let results: DeliveredSearchResult[] = kept.map(b => {
diff --git a/src/core/search/lean-rows.ts b/src/core/search/lean-rows.ts
index d078c3db45..445976818e 100644
--- a/src/core/search/lean-rows.ts
+++ b/src/core/search/lean-rows.ts
@@ -18,6 +18,10 @@
* only as `generated` (a machine-written page); modality when not text; stale
* only when set (true, or the held-file object from #5988);
* - `delivered: { truncated: true }` whenever evidence delivery truncated;
+ * on a long page `search.long_page_unit` considered, `delivered: { unit,
+ * reason }` (plus `truncated: true` when cut): `reason` is `long_page`
+ * when the page came back in that unit, `long_page_chunk` when it kept
+ * its ranked chunk;
* - `evidence_omitted` on a keyword-mode row whose text did not fit.
* `fields: "full"`, the `mcp.result_rows: full` host config and gbrain's own
* thin client get every field; trusted local callers always do.
@@ -55,7 +59,12 @@ export function leanRow(row: Record<string, unknown>): Record<string, unknown> {
else if (key === 'stale' && (value === true || (typeof value === 'object' && value !== null))) out[key] = value;
else if (key === 'modality' && value !== 'text') out[key] = value;
else if (key === 'provenance' && value === 'generated') out[key] = value;
- else if (key === 'delivered' && (value as { truncated?: unknown }).truncated === true) out[key] = { truncated: true };
+ else if (key === 'delivered') {
+ const d = value as { unit?: unknown; reason?: unknown; truncated?: unknown };
+ const truncated = d.truncated === true ? { truncated: true } : {};
+ if (d.reason === 'long_page' || d.reason === 'long_page_chunk') out[key] = { unit: d.unit, reason: d.reason, ...truncated };
+ else if (d.truncated === true) out[key] = truncated;
+ }
}
return out;
}
diff --git a/test/config-search-registry.test.ts b/test/config-search-registry.test.ts
index e8a4aa69bd..ef3f12fab3 100644
--- a/test/config-search-registry.test.ts
+++ b/test/config-search-registry.test.ts
@@ -45,6 +45,7 @@ const DIRECTLY_READ_SINGLETONS = [
'search.return_budget_conversation',
'search.return_budget_max_remote',
'search.auto_packing', // search/evidence-delivery.ts (explicit-budget cap)
+ 'search.long_page_unit', // search/evidence-delivery.ts (long non-conversation pages under implied auto)
'search.evidence_date_header', // search/evidence-delivery.ts (C1)
'search.entity_anchoring', // search/entity-anchor.ts (ops/search.ts)
'search.query_facts_arm', // search/facts-arm.ts (search/query-arms.ts)
diff --git a/test/e2e/evidence-long-page.test.ts b/test/e2e/evidence-long-page.test.ts
new file mode 100644
index 0000000000..7da49f03ff
--- /dev/null
+++ b/test/e2e/evidence-long-page.test.ts
@@ -0,0 +1,92 @@
+/**
+ * F2 (`search.long_page_unit`) on Postgres: the PGLite unit arm
+ * (test/evidence-long-page.test.ts) run against a real Postgres brain. Pins
+ * the off path (byte-identical to return_unit chunk), the frozen on-path
+ * golden, the serialized lean MCP `delivered {unit, reason}`, the precedence
+ * of a non-auto global unit, the over-budget fallback, recall/think/
+ * assemble_evidence unchanged with the key on, and the d5b/F4 instruction
+ * config readers, all on the same engine.
+ *
+ * Runs when DATABASE_URL is set.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import type { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import type { SearchResult } from '../../src/core/types.ts';
+import { assembleEvidenceForHits } from '../../src/core/search/evidence-delivery.ts';
+import { buildMcpInstructions, readInstructionContent } from '../../src/mcp/instructions.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { DECIDING, LONG_SLUG, mcpCall, opCall, seedLongPages, withConfig } from '../helpers/long-page-fixture.ts';
+
+const GOLDEN = join(import.meta.dir, '../fixtures/goldens/evidence-delivery/long-page-on-path.json');
+const KEY = 'search.long_page_unit';
+const run = process.env.DATABASE_URL ? describe : describe.skip;
+let engine: PostgresEngine;
+let close: () => Promise<void> = async () => {};
+
+beforeAll(async () => {
+ if (!process.env.DATABASE_URL) return;
+ const isolated = await isolatedPersistencePostgres(process.env.DATABASE_URL);
+ engine = isolated.engine;
+ close = isolated.close;
+ await seedLongPages(engine);
+}, 240_000);
+afterAll(async () => { await close(); }, 120_000);
+
+const long = (rows: Array<Record<string, unknown>>) => rows.find(r => r.slug === LONG_SLUG)!;
+
+run('long-page delivery on Postgres', () => {
+ test('off (unset or `off`) is byte-identical to return_unit chunk', async () => {
+ for (const [name, params] of [['search', { query: 'renewal fee' }], ['query', { query: 'renewal fee', expand: false }]] as const) {
+ const chunk = await mcpCall(engine, name, { ...params, return_unit: 'chunk' });
+ expect((await mcpCall(engine, name, params)).bytes).toBe(chunk.bytes);
+ expect((await withConfig(engine, { [KEY]: 'off' }, () => mcpCall(engine, name, params))).bytes).toBe(chunk.bytes);
+ }
+ });
+
+ test('on: the frozen golden holds, and the lean long row carries delivered {unit, reason}', async () => {
+ const want = JSON.parse(readFileSync(GOLDEN, 'utf8')) as Record<string, string>;
+ for (const unit of ['window', 'section', 'page'] as const) {
+ const on = await withConfig(engine, { [KEY]: unit }, () => mcpCall(engine, 'search', { query: 'renewal fee' }));
+ expect(long(on.rows).delivered).toEqual({ unit, reason: 'long_page' });
+ const ids = (bytes: string) => bytes.replace(/\\"chunk_id\\":\d+/g, '\\"chunk_id\\":0');
+ expect(ids(on.bytes)).toBe(ids(want[`mcp-search:${unit}`]));
+ }
+ const page = await withConfig(engine, { [KEY]: 'page' }, () => mcpCall(engine, 'search', { query: 'renewal fee' }));
+ expect(String(long(page.rows).chunk_text)).toContain(DECIDING);
+ });
+
+ test('global window wins over the long-page section; explicit budget keeps it off; over budget keeps the chunk', async () => {
+ const pick = (rows: unknown) => (rows as Array<SearchResult & { delivered?: { unit: string; reason?: string } }>).find(r => r.slug === LONG_SLUG)!;
+ const global = await withConfig(engine, { 'search.return_unit': 'window', [KEY]: 'section' }, () => opCall(engine, 'search', { query: 'renewal fee' }));
+ expect(pick(global.result).delivered).toEqual(expect.objectContaining({ unit: 'window' }));
+ expect(pick(global.result).delivered?.reason).toBeUndefined();
+ const budget = await withConfig(engine, { [KEY]: 'section' }, () => opCall(engine, 'search', { query: 'renewal fee', token_budget: 4000 }));
+ expect(pick(budget.result).delivered?.reason).not.toBe('long_page');
+ const over = await withConfig(engine, { [KEY]: 'section', 'search.return_budget_conversation': '40' }, () => mcpCall(engine, 'search', { query: 'renewal fee' }));
+ expect(long(over.rows).delivered).toEqual({ unit: 'chunk', reason: 'long_page_chunk' });
+ });
+
+ test('recall and queryless assemble_evidence are unchanged with the key on', async () => {
+ const capture = async () => {
+ const page = await engine.getPage(LONG_SLUG);
+ const [chunk] = await engine.executeRaw<{ id: number }>(`SELECT id FROM content_chunks WHERE page_id = $1 ORDER BY chunk_index LIMIT 1`, [page!.id]);
+ return {
+ recall: (await mcpCall(engine, 'recall', { query: 'renewal fee' })).bytes,
+ assembled: JSON.stringify(await assembleEvidenceForHits(engine, { hits: [{ source_id: 'default', slug: LONG_SLUG, chunk_id: chunk.id }], return_unit: 'auto', caller: { remote: true } })),
+ };
+ };
+ const off = await capture();
+ expect(await withConfig(engine, { [KEY]: 'section' }, capture)).toEqual(off);
+ });
+
+ test('instruction content (d5b names-row references, F4 governing rule) reads from Postgres config', async () => {
+ expect(await readInstructionContent(engine)).toEqual({ references: { namesRow: true, records: false }, governingRule: 'in_effect' });
+ const content = await withConfig(engine, { 'entity.names_references': 'false', 'entity.record_types': 'contract', 'mcp.instructions_governing_rule': 'newest' }, () => readInstructionContent(engine));
+ expect(content).toEqual({ references: { namesRow: false, records: true }, governingRule: 'newest' });
+ const text = buildMcpInstructions(content);
+ expect(text).toContain('a `names` row lists `records` by type.');
+ expect(text).toContain('For what is true now, prefer the newest governing source');
+ });
+});
diff --git a/test/evidence-long-page.test.ts b/test/evidence-long-page.test.ts
new file mode 100644
index 0000000000..f02e3e9b17
--- /dev/null
+++ b/test/evidence-long-page.test.ts
@@ -0,0 +1,267 @@
+/**
+ * F2 plumbing: `search.long_page_unit` delivers long non-conversation hits in
+ * an existing unit (`window`, `section`, `page`) under an implied `auto`, on
+ * `search` and `query` only. Off (the default) is byte-identical to
+ * `return_unit: "chunk"`; the on path is pinned by its own frozen golden
+ * (test/fixtures/goldens/evidence-delivery/long-page-on-path.json).
+ *
+ * Precedence (docs/evidence-delivery.md "Long pages"): explicit `return_unit`
+ * > non-`auto` `search.return_unit` > `search.long_page_unit`; an explicit
+ * `token_budget` or `snippet_chars` keeps it off. recall, think and
+ * `assemble_evidence` never read it. Assertions are on the serialized lean
+ * MCP output a remote agent receives. The Postgres arm is
+ * test/e2e/evidence-long-page.test.ts.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { SearchResult } from '../src/core/types.ts';
+import {
+ LONG_PAGE_DEADLINE_MS, LONG_PAGE_MAX_INPUT_BYTES, LONG_PAGE_MAX_PAGES, LONG_PAGE_MIN_BYTES, assembleEvidenceForHits, deliverEvidence,
+ longPageUnitValueProblem, resolveEvidencePlan, selectLongPages, withLongPagePolicy, type EvidencePlan,
+} from '../src/core/search/evidence-delivery.ts';
+import { searchConfigValueRefusal } from '../src/core/search/config-values.ts';
+import { leanRow } from '../src/core/search/lean-rows.ts';
+import { runThink } from '../src/core/think/index.ts';
+import { CONVERSATION_PAGE, DECIDING, LONG_SLUG, mcpCall, opCall, seedLongPages, withConfig } from './helpers/long-page-fixture.ts';
+
+const GOLDEN = join(import.meta.dir, 'fixtures/goldens/evidence-delivery/long-page-on-path.json');
+const KEY = 'search.long_page_unit';
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await seedLongPages(engine);
+}, 240_000);
+afterAll(async () => { await engine?.disconnect(); }, 120_000);
+
+const long = (rows: Array<Record<string, unknown>>) => rows.find(r => r.slug === LONG_SLUG)!;
+
+describe('off path', () => {
+ test('unset and `off` are byte-identical to return_unit chunk on search and query, with no delivery keys', async () => {
+ for (const [name, params] of [['search', { query: 'renewal fee' }], ['query', { query: 'renewal fee', expand: false }]] as const) {
+ const chunk = await mcpCall(engine, name, { ...params, return_unit: 'chunk' });
+ const unset = await mcpCall(engine, name, params);
+ const off = await withConfig(engine, { [KEY]: 'off' }, () => mcpCall(engine, name, params));
+ expect(unset.bytes).toBe(chunk.bytes);
+ expect(off.bytes).toBe(chunk.bytes);
+ expect(unset.bytes).not.toContain('"delivered"');
+ expect(unset.bytes).not.toContain('"delivery"');
+ }
+ });
+
+ test('an unknown stored value reads as off; config set refuses it', async () => {
+ const chunk = await mcpCall(engine, 'search', { query: 'renewal fee', return_unit: 'chunk' });
+ expect((await withConfig(engine, { [KEY]: 'sentence' }, () => mcpCall(engine, 'search', { query: 'renewal fee' }))).bytes).toBe(chunk.bytes);
+ expect(longPageUnitValueProblem('section')).toBeNull();
+ expect(searchConfigValueRefusal(KEY, 'sentence')?.message).toContain('off, window, section, page');
+ });
+});
+
+describe('on path (serialized lean MCP output)', () => {
+ for (const unit of ['window', 'section', 'page'] as const) {
+ test(`${unit}: the long row carries delivered {unit, reason}; short rows are their off-path bytes`, async () => {
+ const off = await mcpCall(engine, 'search', { query: 'renewal fee' });
+ const on = await withConfig(engine, { [KEY]: unit }, () => mcpCall(engine, 'search', { query: 'renewal fee' }));
+ const row = long(on.rows);
+ expect(row.delivered).toEqual({ unit, reason: 'long_page' });
+ expect(String(row.chunk_text).length).toBeGreaterThan(String(long(off.rows).chunk_text).length);
+ expect(on.rows.map(r => r.slug)).toEqual(off.rows.map(r => r.slug));
+ for (const r of on.rows.filter(r => r.slug !== LONG_SLUG)) expect(JSON.stringify(r)).toBe(JSON.stringify(off.rows.find(o => o.slug === r.slug)));
+ });
+ }
+
+ test('query delivers the same way', async () => {
+ const on = await withConfig(engine, { [KEY]: 'section' }, () => mcpCall(engine, 'query', { query: 'renewal fee', expand: false }));
+ expect(long(on.rows).delivered).toEqual({ unit: 'section', reason: 'long_page' });
+ });
+
+ test('term words that recur in non-deciding clauses: the unit is anchored on the ranked hit, never on term overlap', async () => {
+ const off = long((await mcpCall(engine, 'search', { query: 'renewal fee' })).rows);
+ const deliveredText = async (unit: string) => String(long((await withConfig(engine, { [KEY]: unit }, () => mcpCall(engine, 'search', { query: 'renewal fee' }))).rows).chunk_text);
+ const section = await deliveredText('section');
+ expect(section.startsWith(String(off.chunk_text).slice(0, 200))).toBe(true);
+ expect(section).not.toContain(DECIDING);
+ expect(section).not.toContain('## Term and renewal');
+ expect(await deliveredText('page')).toContain(DECIDING);
+ });
+
+ test('frozen on-path golden', async () => {
+ const got: Record<string, string> = {};
+ for (const unit of ['window', 'section', 'page'] as const) {
+ got[`mcp-search:${unit}`] = (await withConfig(engine, { [KEY]: unit }, () => mcpCall(engine, 'search', { query: 'renewal fee' }))).bytes;
+ }
+ if (process.env.GBRAIN_TEST_UPDATE_GOLDENS === '1') {
+ mkdirSync(dirname(GOLDEN), { recursive: true });
+ writeFileSync(GOLDEN, JSON.stringify(got, null, 2) + '\n');
+ }
+ const want = JSON.parse(readFileSync(GOLDEN, 'utf8')) as Record<string, string>;
+ expect(Object.keys(got).sort()).toEqual(Object.keys(want).sort());
+ for (const key of Object.keys(want)) expect(`${key}: ${got[key]}`).toBe(`${key}: ${want[key]}`);
+ });
+
+ test('a long page whose matching span no longer fits the budget keeps its ranked chunk (long_page_chunk)', async () => {
+ const off = await mcpCall(engine, 'search', { query: 'renewal fee' });
+ const on = await withConfig(engine, { [KEY]: 'section', 'search.return_budget_conversation': '40' }, () => mcpCall(engine, 'search', { query: 'renewal fee' }));
+ const row = long(on.rows);
+ expect(row.delivered).toEqual({ unit: 'chunk', reason: 'long_page_chunk' });
+ expect(row.chunk_text).toBe(long(off.rows).chunk_text);
+ expect((JSON.parse(on.bytes) as { _meta: { retrieval: { delivery: { fallbacks: string[] } } } })._meta.retrieval.delivery.fallbacks).toContain('long_page_over_budget');
+ });
+});
+
+describe('on path with a conversation in the hit list', () => {
+ let mixed: PGLiteEngine;
+ beforeAll(async () => {
+ mixed = new PGLiteEngine();
+ await mixed.connect({});
+ await mixed.initSchema();
+ await seedLongPages(mixed);
+ await seedLongPages(mixed, [CONVERSATION_PAGE]);
+ }, 120_000);
+ afterAll(async () => { await mixed?.disconnect(); }, 120_000);
+
+ test('a conversation in the same hit list still comes back whole', async () => {
+ const on = await withConfig(mixed, { [KEY]: 'section' }, () => opCall(mixed, 'search', { query: 'renewal fee' }));
+ const rows = on.result as Array<SearchResult & { delivered: { unit: string; reason: string } }>;
+ expect(rows.find(r => r.slug === CONVERSATION_PAGE.slug)!.delivered).toMatchObject({ unit: 'page', reason: 'conversation_slug' });
+ expect(rows.find(r => r.slug === LONG_SLUG)!.delivered).toMatchObject({ unit: 'section', reason: 'long_page' });
+ expect(rows.find(r => r.slug === 'notes/short-example')!.delivered).toMatchObject({ unit: 'chunk', reason: 'not_conversation' });
+ });
+});
+
+describe('precedence', () => {
+ const deliveredOf = async (config: Record<string, string>, params: Record<string, unknown>) =>
+ withConfig(engine, config, async () => {
+ const { result, meta } = await opCall(engine, 'search', { query: 'renewal fee', ...params });
+ return { row: (result as Array<SearchResult & { delivered?: { unit: string; reason?: string } }>).find(r => r.slug === LONG_SLUG)!, meta };
+ });
+
+ test('a non-auto global search.return_unit wins: global window + long-page section delivers window everywhere', async () => {
+ const { row } = await deliveredOf({ 'search.return_unit': 'window', [KEY]: 'section' }, {});
+ expect(row.delivered?.unit).toBe('window');
+ expect(row.delivered?.reason).toBeUndefined();
+ });
+
+ test('an explicit return_unit wins (chunk is the off path; auto keeps every non-conversation chunk)', async () => {
+ const chunk = await mcpCall(engine, 'search', { query: 'renewal fee', return_unit: 'chunk' });
+ expect((await withConfig(engine, { [KEY]: 'section' }, () => mcpCall(engine, 'search', { query: 'renewal fee', return_unit: 'chunk' }))).bytes).toBe(chunk.bytes);
+ const { row } = await deliveredOf({ [KEY]: 'section' }, { return_unit: 'auto' });
+ expect(row.delivered).toMatchObject({ unit: 'chunk', reason: 'not_conversation' });
+ const page = await deliveredOf({ [KEY]: 'section' }, { return_unit: 'page' });
+ expect(page.row.delivered?.unit).toBe('page');
+ expect(page.row.delivered?.reason).toBeUndefined();
+ });
+
+ test('a config-level auto is still the implied auto: the key applies', async () => {
+ const { row } = await deliveredOf({ 'search.return_unit': 'auto', [KEY]: 'section' }, {});
+ expect(row.delivered).toMatchObject({ unit: 'section', reason: 'long_page' });
+ });
+
+ test('an explicit token_budget or snippet_chars keeps the key off', async () => {
+ const budget = await deliveredOf({ [KEY]: 'section' }, { token_budget: 4000 });
+ expect(budget.row.delivered?.reason).not.toBe('long_page');
+ const snippet = await withConfig(engine, { [KEY]: 'section' }, () => mcpCall(engine, 'search', { query: 'renewal fee', snippet_chars: 300 }));
+ expect(snippet.bytes).toBe((await mcpCall(engine, 'search', { query: 'renewal fee', snippet_chars: 300 })).bytes);
+ });
+});
+
+describe('other callers stay byte-identical with the key on', () => {
+ test('recall, think and queryless assemble_evidence', async () => {
+ const capture = async () => {
+ const recall = (await mcpCall(engine, 'recall', { query: 'renewal fee' })).bytes;
+ const page = await engine.getPage(LONG_SLUG);
+ const [chunk] = await engine.executeRaw<{ id: number }>(`SELECT id FROM content_chunks WHERE page_id = $1 ORDER BY chunk_index LIMIT 1`, [page!.id]);
+ const assembled = JSON.stringify(await assembleEvidenceForHits(engine, { hits: [{ source_id: 'default', slug: LONG_SLUG, chunk_id: chunk.id }], return_unit: 'auto', caller: { remote: true } }));
+ const prompts: string[] = [];
+ await runThink(engine, {
+ question: 'renewal fee', remote: false, referenceDate: '2026-01-15',
+ client: { create: async (params: { messages: unknown[] }) => {
+ prompts.push(JSON.stringify(params.messages));
+ return { content: [{ type: 'text', text: '{"answer":"ok","citations":[],"gaps":[]}' }], usage: { input_tokens: 1, output_tokens: 1 } };
+ } } as never,
+ });
+ return { recall, assembled, think: prompts[0] };
+ };
+ const off = await capture();
+ for (const unit of ['window', 'section', 'page']) expect(await withConfig(engine, { [KEY]: unit }, capture)).toEqual(off);
+ });
+});
+
+describe('selection limits (size preflight)', () => {
+ const plan = { requestedUnit: 'auto', unit: 'auto', window: 1, budgetTokens: 24000, explicitUnit: false, budgetExplicit: false, packing: 'cap_only', longPage: { unit: 'section' } } as EvidencePlan;
+ const hit = (page_id: number, slug = `notes/p${page_id}`): SearchResult => ({ slug, page_id, title: slug, type: 'note', chunk_text: 'x', chunk_source: 'compiled_truth', chunk_id: page_id * 10, chunk_index: 0, score: 1, stale: false });
+ const sized = (sizes: Record<number, number>) => ({ executeRaw: async () => Object.entries(sizes).map(([id, bytes]) => ({ id: Number(id), bytes })) }) as unknown as BrainEngine;
+
+ test(`long means at least ${LONG_PAGE_MIN_BYTES} bytes; no long page is effectivePlan exactly (null without a conversation)`, async () => {
+ expect(await selectLongPages(sized({ 1: LONG_PAGE_MIN_BYTES - 1 }), plan, [hit(1)], {})).toEqual({ plan: null });
+ const at = await selectLongPages(sized({ 1: LONG_PAGE_MIN_BYTES }), plan, [hit(1)], {});
+ expect([...at.longPages!.pages]).toEqual([1]);
+ });
+
+ test(`at most ${LONG_PAGE_MAX_PAGES} pages, in rank order; later long pages keep their chunk`, async () => {
+ const ids = Array.from({ length: LONG_PAGE_MAX_PAGES + 2 }, (_, i) => i + 1);
+ const sel = await selectLongPages(sized(Object.fromEntries(ids.map(id => [id, 10_000]))), plan, ids.map(id => hit(id)), {});
+ expect([...sel.longPages!.pages]).toEqual(ids.slice(0, LONG_PAGE_MAX_PAGES));
+ expect([...sel.longPages!.kept]).toEqual(ids.slice(LONG_PAGE_MAX_PAGES).map(id => [id, 'long_page_pages']));
+ });
+
+ test(`at most ${LONG_PAGE_MAX_INPUT_BYTES} body bytes; a page that would cross it is never sliced, it keeps its chunk`, async () => {
+ const half = Math.floor(LONG_PAGE_MAX_INPUT_BYTES * 0.6);
+ const sel = await selectLongPages(sized({ 1: half, 2: half, 3: 9_000 }), plan, [hit(1), hit(2), hit(3)], {});
+ expect([...sel.longPages!.pages]).toEqual([1, 3]);
+ expect([...sel.longPages!.kept]).toEqual([[2, 'long_page_bytes']]);
+ });
+
+ test('conversation and saved-fact hits are never preflighted', async () => {
+ let asked: unknown[] = [];
+ const spy = { executeRaw: async (_sql: string, params: unknown[]) => { asked = params[0] as unknown[]; return []; } } as unknown as BrainEngine;
+ await selectLongPages(spy, plan, [hit(1, 'chat/a'), { ...hit(2), fact_row: { id: 1, valid_from: '2026-01-01', valid_until: null } }, hit(3)], {});
+ expect(asked).toEqual([3]);
+ });
+
+ test('a late preflight is the off path; with a conversation hit it is reported as long_page_deadline', async () => {
+ const hanging = { executeRaw: () => new Promise(() => {}) } as unknown as BrainEngine;
+ expect(await selectLongPages(hanging, plan, [hit(1)], {})).toEqual({ plan: null });
+ const mixed = await selectLongPages(hanging, plan, [hit(1), hit(2, 'chat/a')], {});
+ expect(mixed.plan).toBe(plan);
+ expect(mixed.longPages?.fallbacks).toEqual(['long_page_deadline']);
+ }, LONG_PAGE_DEADLINE_MS * 3 + 5_000);
+
+ test('the policy is resolved only under an implied auto, with no explicit budget or snippet_chars', async () => {
+ const resolve = async (input: Record<string, unknown>, config: Record<string, string> = {}) => withConfig(engine, { [KEY]: 'page', ...config }, async () =>
+ (await withLongPagePolicy(engine, await resolveEvidencePlan(engine, { remote: true, returnUnit: input.return_unit, returnWindow: undefined, budget: input.token_budget, snippetChars: input.snippet_chars, snippetCap: 0, op: 'search' }), { snippetChars: input.snippet_chars }))?.longPage ?? null);
+ expect(await resolve({})).toEqual({ unit: 'page' });
+ expect(await resolve({ return_unit: 'auto' })).toBeNull();
+ expect(await resolve({ token_budget: 2000 })).toBeNull();
+ expect(await resolve({ snippet_chars: 200 })).toBeNull();
+ expect(await resolve({}, { 'search.return_unit': 'section' })).toBeNull();
+ });
+
+ test('a failed long-page fetch keeps the ranked chunks (long_page_fetch_failed), never the conversation fetch', async () => {
+ const page = await engine.getPage(LONG_SLUG);
+ const rows = await engine.executeRaw<{ id: number; chunk_index: number; chunk_text: string }>(`SELECT id, chunk_index, chunk_text FROM content_chunks WHERE page_id = $1 ORDER BY chunk_index LIMIT 1`, [page!.id]);
+ const h: SearchResult = { slug: LONG_SLUG, page_id: page!.id, title: LONG_SLUG, type: 'note', chunk_text: rows[0].chunk_text, chunk_source: 'compiled_truth', chunk_id: rows[0].id, chunk_index: 0, score: 1, stale: false };
+ const failing = new Proxy(engine, { get: (t, k) => k === 'getChunkWindows' ? async () => { throw new Error('boom'); } : (t as never)[k] }) as BrainEngine;
+ const { results, delivery } = await deliverEvidence(failing, [h], plan, {}, { longPages: { unit: 'section', pages: new Set([page!.id]), kept: new Map(), deadlineAt: Date.now() + 1000, fallbacks: [] } });
+ expect(results[0].chunk_text).toBe(h.chunk_text);
+ expect(results[0].delivered).toMatchObject({ unit: 'chunk', reason: 'long_page_chunk' });
+ expect(delivery.fallbacks).toEqual(expect.arrayContaining(['long_page_fetch_failed']));
+ expect(delivery.applied_unit).toBe('auto');
+ expect(leanRow(results[0] as never).delivered).toEqual({ unit: 'chunk', reason: 'long_page_chunk' });
+ });
+});
+
+describe('lean rows', () => {
+ test('keep {truncated: true} alone for every other row, and {unit, reason, truncated?} for long-page rows', () => {
+ const base = { slug: 'a', chunk_text: 't' };
+ expect(leanRow({ ...base, delivered: { unit: 'page', truncated: true, reason: 'conversation_type' } }).delivered).toEqual({ truncated: true });
+ expect(leanRow({ ...base, delivered: { unit: 'chunk', truncated: false, reason: 'not_conversation' } }).delivered).toBeUndefined();
+ expect(leanRow({ ...base, delivered: { unit: 'section', truncated: true, reason: 'long_page' } }).delivered).toEqual({ unit: 'section', reason: 'long_page', truncated: true });
+ expect(leanRow({ ...base, delivered: { unit: 'window', truncated: false, reason: 'long_page' } }).delivered).toEqual({ unit: 'window', reason: 'long_page' });
+ });
+});
diff --git a/test/fixtures/goldens/evidence-delivery/long-page-on-path.json b/test/fixtures/goldens/evidence-delivery/long-page-on-path.json
new file mode 100644
index 0000000000..963579230e
--- /dev/null
+++ b/test/fixtures/goldens/evidence-delivery/long-page-on-path.json
@@ -0,0 +1,5 @@
+{
+ "mcp-search:window": "{\"content\":[{\"type\":\"text\",\"text\":\"[{\\\"slug\\\":\\\"contracts/msa-example\\\",\\\"title\\\":\\\"contracts/msa-example\\\",\\\"type\\\":\\\"note\\\",\\\"chunk_text\\\":\\\"## Definitions\\\\n\\\\nThe renewal fee means the amount stated in the order form. Clause 1 on definitions restates the general obligations of both parties and the notice address for correspondence. Clause 2 on definitions restates the general obligations of both parties and the notice address for correspondence. Clause 3 on definitions restates the general obligations of both parties and the notice address for correspondence. Clause 4 on definitions restates the general obligations of both parties and the notice address for correspondence. Clause 5 on definitions restates the general obligations of both parties and the notice address for correspondence. Clause 6 on definitions restates the general obligations of both parties and the notice address for correspondence. Clause 7 on definitions restates the general obligations of both parties and the notice address for correspondence. Clause 8 on definitions restates the general obligations of both parties and the notice address for correspondence. Clause 9 on definitions restates the general obligations of both parties and the notice address for correspondence. Clause 10 on definitions restates the general obligations of both parties and the notice address for correspondence. Clause 11 on definitions restates the general obligations of both parties and the notice address for correspondence. Clause 12 on definitions restates the general obligations of both parties and the notice address for correspondence. Clause 13 on definitions restates the general obligations of both parties and the notice address for correspondence. Clause 14 on definitions restates the general obligations of both parties and the notice address for correspondence. Clause 15 on definitions restates the general obligations of both parties and the notice address for correspondence. Clause 16 on definitions restates the general obligations of both parties and the notice address for correspondence. Clause 17 on definitions restates the general obligations of both parties and the notice address for correspondence. Clause 18 on definitions restates the general obligations of both parties and the notice address for correspondence.\\\\n\\\\n## Fees\\\\n\\\\nNo renewal fee applies to trial seats, and the renewal fee is invoiced in advance. Clause 1 on fees restates the general obligations of both parties and the notice address for correspondence. Clause 2 on fees restates the general obligations of both parties and the notice address for correspondence. Clause 3 on fees restates the general obligations of both parties and the notice address for correspondence. Clause 4 on fees restates the general obligations of both parties and the notice address for correspondence. Clause 5 on fees restates the general obligations of both parties and the notice address for correspondence. Clause 6 on fees restates the general obligations of both parties and the notice address for correspondence. Clause 7 on fees restates the general obligations of both parties and the notice address for correspondence. Clause 8 on fees restates the general obligations of both parties and the notice address for correspondence. Clause 9 on fees restates the general obligations of both parties and the notice address for correspondence. Clause 10 on fees restates the general obligations of both parties and the notice address for correspondence. Clause 11 on fees restates the general obligations of both parties and the notice address for correspondence. Clause 12 on fees restates the general obligations of both parties and the notice address for correspondence. Clause 13 on fees restates the general obligations of both parties and the notice address for correspondence. Clause 14 on fees restates the general obligations of both parties and the notice address for correspondence. Clause 15 on fees restates the general obligations of both parties and the notice address for correspondence. Clause 16 on fees restates the general obligations of both parties and the notice address for correspondence. Clause 17 on fees restates the general obligations of both parties and the notice address for correspondence. Clause 18 on fees restates the general obligations of both parties and the notice address for correspondence.\\\\n\\\\n## Term and renewal\\\\n\\\\nThe agreement renews each year; a renewal fee change needs written notice. Clause 1 on term restates the general obligations of both parties and the notice address for correspondence. Clause 2 on term restates the general obligations of both parties and the notice address for correspondence. Clause 3 on term restates the general obligations of both parties and the notice address for correspondence. Clause 4 on term restates the general obligations of both parties and the notice address for correspondence. Clause 5 on term restates the general obligations of both parties and the notice address for correspondence. Clause 6 on term restates the general obligations of both parties and the notice address for correspondence. Clause 7 on term restates the general obligations of both parties and the notice address for correspondence. Clause 8 on term restates the general obligations of both parties and the notice address for correspondence. Clause 9 on term restates the general obligations of both parties and the notice address for correspondence. Clause 10 on term restates the general obligations of both parties and the notice address for correspondence. Clause 11 on term restates the general obligations of both parties and the notice address for correspondence. Clause 12 on term restates the general obligations of both parties and the notice address for correspondence. Clause 13 on term restates the general obligations of both parties and the notice address for correspondence. Clause 14 on term restates the general obligations of both parties and the notice\\\",\\\"chunk_id\\\":1,\\\"score\\\":0.9518601894378662,\\\"source_id\\\":\\\"default\\\",\\\"effective_date\\\":null,\\\"id\\\":\\\"gbrain-page:v1:WyJkZWZhdWx0IiwiY29udHJhY3RzL21zYS1leGFtcGxlIl0\\\",\\\"evidence\\\":\\\"keyword_exact\\\",\\\"create_safety\\\":\\\"probable\\\",\\\"delivered\\\":{\\\"unit\\\":\\\"window\\\",\\\"reason\\\":\\\"long_page\\\"},\\\"trust_tier\\\":\\\"unknown\\\",\\\"origin\\\":\\\"legacy\\\"},{\\\"slug\\\":\\\"notes/handbook-example\\\",\\\"title\\\":\\\"notes/handbook-example\\\",\\\"type\\\":\\\"note\\\",\\\"chunk_text\\\":\\\"## Renewals\\\\n\\\\nThe handbook describes how a renewal fee is quoted. Clause 1 on handbook restates the general obligations of both parties and the notice address for correspondence. Clause 2 on handbook restates the general obligations of both parties and the notice address for correspondence. Clause 3 on handbook restates the general obligations of both parties and the notice address for correspondence.\\\",\\\"chunk_id\\\":6,\\\"score\\\":0.5802597999572754,\\\"source_id\\\":\\\"default\\\",\\\"effective_date\\\":null,\\\"id\\\":\\\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvaGFuZGJvb2stZXhhbXBsZSJd\\\",\\\"evidence\\\":\\\"weak_semantic\\\",\\\"create_safety\\\":\\\"unknown\\\",\\\"trust_tier\\\":\\\"unknown\\\",\\\"origin\\\":\\\"legacy\\\"},{\\\"slug\\\":\\\"notes/short-example\\\",\\\"title\\\":\\\"notes/short-example\\\",\\\"type\\\":\\\"note\\\",\\\"chunk_text\\\":\\\"A short note: ask about the renewal fee before the call.\\\",\\\"chunk_id\\\":5,\\\"score\\\":0.3964128792285919,\\\"source_id\\\":\\\"default\\\",\\\"effective_date\\\":null,\\\"id\\\":\\\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvc2hvcnQtZXhhbXBsZSJd\\\",\\\"evidence\\\":\\\"weak_semantic\\\",\\\"create_safety\\\":\\\"unknown\\\",\\\"trust_tier\\\":\\\"unknown\\\",\\\"origin\\\":\\\"legacy\\\"}]\"}],\"_meta\":{\"retrieval\":{\"returned_count\":3,\"retrieved_count\":3,\"projection_readiness\":{\"status\":\"ready\",\"ready\":true},\"delivery\":{\"requested_unit\":\"auto\",\"applied_unit\":\"auto\",\"return_window\":1,\"budget_tokens\":24000,\"budget_used\":1181,\"tokens_delivered\":1168,\"tokenizer\":\"cl100k\",\"coordinates\":\"utf16\",\"blocks\":3,\"dropped\":0,\"dropped_reasons\":{},\"fallbacks\":[]},\"rows\":\"lean\"}}}",
+ "mcp-search:section": "{\"content\":[{\"type\":\"text\",\"text\":\"[{\\\"slug\\\":\\\"contracts/msa-example\\\",\\\"title\\\":\\\"contracts/msa-example\\\",\\\"type\\\":\\\"note\\\",\\\"chunk_text\\\":\\\"## Definitions\\\\n\\\\nThe renewal fee means the amount stated in the order form. Clause 1 on definitions restates the general obligations of both parties and the notice address for correspondence. Clause 2 on definitions restates the general obligations of both parties and the notice address for correspondence. Clause 3 on definitions restates the general obligations of both parties and the notice address for correspondence. Clause 4 on definitions restates the general obligations of both parties and the notice address for correspondence. Clause 5 on definitions restates the general obligations of both parties and the notice address for correspondence. Clause 6 on definitions restates the general obligations of both parties and the notice address for correspondence. Clause 7 on definitions restates the general obligations of both parties and the notice address for correspondence. Clause 8 on definitions restates the general obligations of both parties and the notice address for correspondence. Clause 9 on definitions restates the general obligations of both parties and the notice address for correspondence. Clause 10 on definitions restates the general obligations of both parties and the notice address for correspondence. Clause 11 on definitions restates the general obligations of both parties and the notice address for correspondence. Clause 12 on definitions restates the general obligations of both parties and the notice address for correspondence. Clause 13 on definitions restates the general obligations of both parties and the notice address for correspondence. Clause 14 on definitions restates the general obligations of both parties and the notice address for correspondence. Clause 15 on definitions restates the general obligations of both parties and the notice address for correspondence. Clause 16 on definitions restates the general obligations of both parties and the notice address for correspondence. Clause 17 on definitions restates the general obligations of both parties and the notice address for correspondence. Clause 18 on definitions restates the general obligations of both parties and the notice address for correspondence.\\\\n\\\\n## Fees\\\\n\\\\nNo renewal fee applies to trial seats, and the renewal fee is invoiced in advance. Clause 1 on fees restates the general obligations of both parties and the notice address for correspondence. Clause 2 on fees restates the general obligations of both parties and the notice address for correspondence. Clause 3 on fees restates the general obligations of both parties and the notice address for correspondence. Clause 4 on fees restates the general obligations of both parties and the notice address for correspondence. Clause 5 on fees restates the general obligations of both parties and the notice address for correspondence. Clause 6 on fees restates the general obligations of both parties and the notice address for correspondence. Clause 7 on fees restates the general obligations of both parties and the notice address for correspondence. Clause 8 on fees restates the general obligations of both parties and the notice address for correspondence. Clause 9 on fees restates the general obligations of both parties and the notice address for correspondence. Clause 10 on fees restates the general obligations of both parties and the notice address for correspondence. Clause 11 on fees restates the general obligations of both parties and the notice address for correspondence. Clause 12 on fees restates the general obligations of both parties and the notice address for correspondence. Clause 13 on fees restates the general obligations of both parties and the notice address for correspondence. Clause 14 on fees restates the general obligations of both parties and the notice address for correspondence. Clause 15 on fees restates the general obligations of both parties and the notice address for correspondence. Clause 16 on fees restates the general obligations of both parties and the notice address for correspondence. Clause 17 on fees restates the general obligations of both parties and the notice address for correspondence. Clause 18 on fees restates the general obligations of both parties and the notice address for correspondence.\\\",\\\"chunk_id\\\":1,\\\"score\\\":0.9518601894378662,\\\"source_id\\\":\\\"default\\\",\\\"effective_date\\\":null,\\\"id\\\":\\\"gbrain-page:v1:WyJkZWZhdWx0IiwiY29udHJhY3RzL21zYS1leGFtcGxlIl0\\\",\\\"evidence\\\":\\\"keyword_exact\\\",\\\"create_safety\\\":\\\"probable\\\",\\\"delivered\\\":{\\\"unit\\\":\\\"section\\\",\\\"reason\\\":\\\"long_page\\\"},\\\"trust_tier\\\":\\\"unknown\\\",\\\"origin\\\":\\\"legacy\\\"},{\\\"slug\\\":\\\"notes/handbook-example\\\",\\\"title\\\":\\\"notes/handbook-example\\\",\\\"type\\\":\\\"note\\\",\\\"chunk_text\\\":\\\"## Renewals\\\\n\\\\nThe handbook describes how a renewal fee is quoted. Clause 1 on handbook restates the general obligations of both parties and the notice address for correspondence. Clause 2 on handbook restates the general obligations of both parties and the notice address for correspondence. Clause 3 on handbook restates the general obligations of both parties and the notice address for correspondence.\\\",\\\"chunk_id\\\":6,\\\"score\\\":0.5802597999572754,\\\"source_id\\\":\\\"default\\\",\\\"effective_date\\\":null,\\\"id\\\":\\\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvaGFuZGJvb2stZXhhbXBsZSJd\\\",\\\"evidence\\\":\\\"weak_semantic\\\",\\\"create_safety\\\":\\\"unknown\\\",\\\"trust_tier\\\":\\\"unknown\\\",\\\"origin\\\":\\\"legacy\\\"},{\\\"slug\\\":\\\"notes/short-example\\\",\\\"title\\\":\\\"notes/short-example\\\",\\\"type\\\":\\\"note\\\",\\\"chunk_text\\\":\\\"A short note: ask about the renewal fee before the call.\\\",\\\"chunk_id\\\":5,\\\"score\\\":0.3964128792285919,\\\"source_id\\\":\\\"default\\\",\\\"effective_date\\\":null,\\\"id\\\":\\\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvc2hvcnQtZXhhbXBsZSJd\\\",\\\"evidence\\\":\\\"weak_semantic\\\",\\\"create_safety\\\":\\\"unknown\\\",\\\"trust_tier\\\":\\\"unknown\\\",\\\"origin\\\":\\\"legacy\\\"}]\"}],\"_meta\":{\"retrieval\":{\"returned_count\":3,\"retrieved_count\":3,\"projection_readiness\":{\"status\":\"ready\",\"ready\":true},\"delivery\":{\"requested_unit\":\"auto\",\"applied_unit\":\"auto\",\"return_window\":1,\"budget_tokens\":24000,\"budget_used\":878,\"tokens_delivered\":865,\"tokenizer\":\"cl100k\",\"coordinates\":\"utf16\",\"blocks\":3,\"dropped\":0,\"dropped_reasons\":{},\"fallbacks\":[]},\"rows\":\"lean\"}}}",
+ "mcp-search:page": "{\"content\":[{\"type\":\"text\",\"text\":\"[{\\\"slug\\\":\\\"contracts/msa-example\\\",\\\"title\\\":\\\"contracts/msa-example\\\",\\\"type\\\":\\\"note\\\",\\\"chunk_text\\\":\\\"## Definitions\\\\n\\\\nThe renewal fee means the amount stated in the order form. Clause 1 on definitions restates the general obligations of both parties and the notice address for correspondence. Clause 2 on definitions restates the general obligations of both parties and the notice address for correspondence. Clause 3 on definitions restates the general obligations of both parties and the notice address for correspondence. Clause 4 on definitions restates the general obligations of both parties and the notice address for correspondence. Clause 5 on definitions restates the general obligations of both parties and the notice address for correspondence. Clause 6 on definitions restates the general obligations of both parties and the notice address for correspondence. Clause 7 on definitions restates the general obligations of both parties and the notice address for correspondence. Clause 8 on definitions restates the general obligations of both parties and the notice address for correspondence. Clause 9 on definitions restates the general obligations of both parties and the notice address for correspondence. Clause 10 on definitions restates the general obligations of both parties and the notice address for correspondence. Clause 11 on definitions restates the general obligations of both parties and the notice address for correspondence. Clause 12 on definitions restates the general obligations of both parties and the notice address for correspondence. Clause 13 on definitions restates the general obligations of both parties and the notice address for correspondence. Clause 14 on definitions restates the general obligations of both parties and the notice address for correspondence. Clause 15 on definitions restates the general obligations of both parties and the notice address for correspondence. Clause 16 on definitions restates the general obligations of both parties and the notice address for correspondence. Clause 17 on definitions restates the general obligations of both parties and the notice address for correspondence. Clause 18 on definitions restates the general obligations of both parties and the notice address for correspondence.\\\\n\\\\n## Fees\\\\n\\\\nNo renewal fee applies to trial seats, and the renewal fee is invoiced in advance. Clause 1 on fees restates the general obligations of both parties and the notice address for correspondence. Clause 2 on fees restates the general obligations of both parties and the notice address for correspondence. Clause 3 on fees restates the general obligations of both parties and the notice address for correspondence. Clause 4 on fees restates the general obligations of both parties and the notice address for correspondence. Clause 5 on fees restates the general obligations of both parties and the notice address for correspondence. Clause 6 on fees restates the general obligations of both parties and the notice address for correspondence. Clause 7 on fees restates the general obligations of both parties and the notice address for correspondence. Clause 8 on fees restates the general obligations of both parties and the notice address for correspondence. Clause 9 on fees restates the general obligations of both parties and the notice address for correspondence. Clause 10 on fees restates the general obligations of both parties and the notice address for correspondence. Clause 11 on fees restates the general obligations of both parties and the notice address for correspondence. Clause 12 on fees restates the general obligations of both parties and the notice address for correspondence. Clause 13 on fees restates the general obligations of both parties and the notice address for correspondence. Clause 14 on fees restates the general obligations of both parties and the notice address for correspondence. Clause 15 on fees restates the general obligations of both parties and the notice address for correspondence. Clause 16 on fees restates the general obligations of both parties and the notice address for correspondence. Clause 17 on fees restates the general obligations of both parties and the notice address for correspondence. Clause 18 on fees restates the general obligations of both parties and the notice address for correspondence.\\\\n\\\\n## Term and renewal\\\\n\\\\nThe agreement renews each year; a renewal fee change needs written notice. Clause 1 on term restates the general obligations of both parties and the notice address for correspondence. Clause 2 on term restates the general obligations of both parties and the notice address for correspondence. Clause 3 on term restates the general obligations of both parties and the notice address for correspondence. Clause 4 on term restates the general obligations of both parties and the notice address for correspondence. Clause 5 on term restates the general obligations of both parties and the notice address for correspondence. Clause 6 on term restates the general obligations of both parties and the notice address for correspondence. Clause 7 on term restates the general obligations of both parties and the notice address for correspondence. Clause 8 on term restates the general obligations of both parties and the notice address for correspondence. Clause 9 on term restates the general obligations of both parties and the notice address for correspondence. Clause 10 on term restates the general obligations of both parties and the notice address for correspondence. Clause 11 on term restates the general obligations of both parties and the notice address for correspondence. Clause 12 on term restates the general obligations of both parties and the notice address for correspondence. Clause 13 on term restates the general obligations of both parties and the notice address for correspondence. Clause 14 on term restates the general obligations of both parties and the notice address for correspondence. Clause 15 on term restates the general obligations of both parties and the notice address for correspondence. Clause 16 on term restates the general obligations of both parties and the notice address for correspondence. Clause 17 on term restates the general obligations of both parties and the notice address for correspondence. Clause 18 on term restates the general obligations of both parties and the notice address for correspondence.\\\\n\\\\n## Amendment 2\\\\n\\\\nEffective 2026-03-01 the annual renewal fee for acme-example is 4,200 USD. Clause 1 on amendment restates the general obligations of both parties and the notice address for correspondence. Clause 2 on amendment restates the general obligations of both parties and the notice address for correspondence. Clause 3 on amendment restates the general obligations of both parties and the notice address for correspondence. Clause 4 on amendment restates the general obligations of both parties and the notice address for correspondence. Clause 5 on amendment restates the general obligations of both parties and the notice address for correspondence. Clause 6 on amendment restates the general obligations of both parties and the notice address for correspondence.\\\\n\\\\n## Notices\\\\n\\\\nClause 1 on notices restates the general obligations of both parties and the notice address for correspondence. Clause 2 on notices restates the general obligations of both parties and the notice address for correspondence. Clause 3 on notices restates the general obligations of both parties and the notice address for correspondence. Clause 4 on notices restates the general obligations of both parties and the notice address for correspondence. Clause 5 on notices restates the general obligations of both parties and the notice address for correspondence. Clause 6 on notices restates the general obligations of both parties and the notice address for correspondence. Clause 7 on notices restates the general obligations of both parties and the notice address for correspondence. Clause 8 on notices restates the general obligations of both parties and the notice address for correspondence. Clause 9 on notices restates the general obligations of both parties and the notice address for correspondence. Clause 10 on notices restates the general obligations of both parties and the notice address for correspondence. Clause 11 on notices restates the general obligations of both parties and the notice address for correspondence. Clause 12 on notices restates the general obligations of both parties and the notice address for correspondence. Clause 13 on notices restates the general obligations of both parties and the notice address for correspondence. Clause 14 on notices restates the general obligations of both parties and the notice address for correspondence. Clause 15 on notices restates the general obligations of both parties and the notice address for correspondence. Clause 16 on notices restates the general obligations of both parties and the notice address for correspondence. Clause 17 on notices restates the general obligations of both parties and the notice address for correspondence. Clause 18 on notices restates the general obligations of both parties and the notice address for correspondence.\\\",\\\"chunk_id\\\":1,\\\"score\\\":0.9518601894378662,\\\"source_id\\\":\\\"default\\\",\\\"effective_date\\\":null,\\\"id\\\":\\\"gbrain-page:v1:WyJkZWZhdWx0IiwiY29udHJhY3RzL21zYS1leGFtcGxlIl0\\\",\\\"evidence\\\":\\\"keyword_exact\\\",\\\"create_safety\\\":\\\"probable\\\",\\\"delivered\\\":{\\\"unit\\\":\\\"page\\\",\\\"reason\\\":\\\"long_page\\\"},\\\"trust_tier\\\":\\\"unknown\\\",\\\"origin\\\":\\\"legacy\\\"},{\\\"slug\\\":\\\"notes/handbook-example\\\",\\\"title\\\":\\\"notes/handbook-example\\\",\\\"type\\\":\\\"note\\\",\\\"chunk_text\\\":\\\"## Renewals\\\\n\\\\nThe handbook describes how a renewal fee is quoted. Clause 1 on handbook restates the general obligations of both parties and the notice address for correspondence. Clause 2 on handbook restates the general obligations of both parties and the notice address for correspondence. Clause 3 on handbook restates the general obligations of both parties and the notice address for correspondence.\\\",\\\"chunk_id\\\":6,\\\"score\\\":0.5802597999572754,\\\"source_id\\\":\\\"default\\\",\\\"effective_date\\\":null,\\\"id\\\":\\\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvaGFuZGJvb2stZXhhbXBsZSJd\\\",\\\"evidence\\\":\\\"weak_semantic\\\",\\\"create_safety\\\":\\\"unknown\\\",\\\"trust_tier\\\":\\\"unknown\\\",\\\"origin\\\":\\\"legacy\\\"},{\\\"slug\\\":\\\"notes/short-example\\\",\\\"title\\\":\\\"notes/short-example\\\",\\\"type\\\":\\\"note\\\",\\\"chunk_text\\\":\\\"A short note: ask about the renewal fee before the call.\\\",\\\"chunk_id\\\":5,\\\"score\\\":0.3964128792285919,\\\"source_id\\\":\\\"default\\\",\\\"effective_date\\\":null,\\\"id\\\":\\\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvc2hvcnQtZXhhbXBsZSJd\\\",\\\"evidence\\\":\\\"weak_semantic\\\",\\\"create_safety\\\":\\\"unknown\\\",\\\"trust_tier\\\":\\\"unknown\\\",\\\"origin\\\":\\\"legacy\\\"}]\"}],\"_meta\":{\"retrieval\":{\"returned_count\":3,\"retrieved_count\":3,\"projection_readiness\":{\"status\":\"ready\",\"ready\":true},\"delivery\":{\"requested_unit\":\"auto\",\"applied_unit\":\"auto\",\"return_window\":1,\"budget_tokens\":24000,\"budget_used\":1791,\"tokens_delivered\":1778,\"tokenizer\":\"cl100k\",\"coordinates\":\"utf16\",\"blocks\":3,\"dropped\":0,\"dropped_reasons\":{},\"fallbacks\":[]},\"rows\":\"lean\"}}}"
+}
diff --git a/test/fixtures/goldens/exports/runtime.json b/test/fixtures/goldens/exports/runtime.json
index b8570463af..f24c32015c 100644
--- a/test/fixtures/goldens/exports/runtime.json
+++ b/test/fixtures/goldens/exports/runtime.json
@@ -803,6 +803,12 @@
"EVIDENCE_DELIVERY_MIN_SERVER_VERSION",
"EVIDENCE_FETCH_TIMEOUT_MS",
"EVIDENCE_OMISSION",
+ "LONG_PAGE_DEADLINE_MS",
+ "LONG_PAGE_MAX_INPUT_BYTES",
+ "LONG_PAGE_MAX_PAGES",
+ "LONG_PAGE_MIN_BYTES",
+ "LONG_PAGE_UNITS",
+ "LONG_PAGE_UNIT_CONFIG_KEY",
"MAX_ASSEMBLE_HITS",
"MIN_EXPLICIT_AUTO_BUDGET",
"RETURN_BUDGET_CONVERSATION_KEY",
@@ -827,6 +833,7 @@
"evidenceTokenizer",
"isConversationLabels",
"locateChunks",
+ "longPageUnitValueProblem",
"pageEvidenceText",
"pagePlanHits",
"parseAutoPacking",
@@ -834,8 +841,10 @@
"parseReturnWindow",
"resolveEvidencePlan",
"resolveFrozenHits",
+ "selectLongPages",
"splitPieces",
- "unsupportedDelivery"
+ "unsupportedDelivery",
+ "withLongPagePolicy"
],
"./search/expansion": [
"expandQuery",
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index 61543b7033..9ef59009fc 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -6873,7 +6873,7 @@
"kind": "type",
"name": "AutoReason",
"signature": [
- "\"conversation_type\" | \"conversation_slug\" | \"not_conversation\" | \"conversation_over_budget\" | \"saved_fact\""
+ "\"conversation_type\" | \"conversation_slug\" | \"not_conversation\" | \"conversation_over_budget\" | \"saved_fact\" | \"long_page\" | \"long_page_chunk\""
]
},
{
@@ -6908,6 +6908,7 @@
"kind": "interface",
"members": [
"liveHits?: boolean | undefined",
+ "longPages?: LongPageSelection | undefined",
"timeoutMs?: number | undefined"
],
"name": "DeliverOptions"
@@ -7018,6 +7019,7 @@
"budgetTokens: number",
"dateHeader?: true | undefined",
"explicitUnit: boolean",
+ "longPage?: LongPagePolicy | undefined",
"packing: \"off\" | \"cap_only\" | \"breadth_capped\" | \"depth_first\"",
"requestedUnit: \"auto\" | \"window\" | \"chunk\" | \"section\" | \"page\"",
"unit: \"auto\" | \"window\" | \"section\" | \"page\"",
@@ -7034,6 +7036,73 @@
],
"name": "FrozenHit"
},
+ {
+ "kind": "variable",
+ "name": "LONG_PAGE_DEADLINE_MS",
+ "signature": [
+ "2000"
+ ]
+ },
+ {
+ "kind": "variable",
+ "name": "LONG_PAGE_MAX_INPUT_BYTES",
+ "signature": [
+ "1000000"
+ ]
+ },
+ {
+ "kind": "variable",
+ "name": "LONG_PAGE_MAX_PAGES",
+ "signature": [
+ "5"
+ ]
+ },
+ {
+ "kind": "variable",
+ "name": "LONG_PAGE_MIN_BYTES",
+ "signature": [
+ "8000"
+ ]
+ },
+ {
+ "kind": "variable",
+ "name": "LONG_PAGE_UNITS",
+ "signature": [
+ "readonly [\"off\", \"window\", \"section\", \"page\"]"
+ ]
+ },
+ {
+ "kind": "variable",
+ "name": "LONG_PAGE_UNIT_CONFIG_KEY",
+ "signature": [
+ "\"search.long_page_unit\""
+ ]
+ },
+ {
+ "kind": "interface",
+ "members": [
+ "unit: LongPageUnit"
+ ],
+ "name": "LongPagePolicy"
+ },
+ {
+ "kind": "interface",
+ "members": [
+ "deadlineAt: number",
+ "fallbacks: string[]",
+ "kept: ReadonlyMap<number, string>",
+ "pages: ReadonlySet<number>",
+ "unit: LongPageUnit"
+ ],
+ "name": "LongPageSelection"
+ },
+ {
+ "kind": "type",
+ "name": "LongPageUnit",
+ "signature": [
+ "\"window\" | \"section\" | \"page\""
+ ]
+ },
{
"kind": "variable",
"name": "MAX_ASSEMBLE_HITS",
@@ -7235,6 +7304,13 @@
"(text: string, chunks: Array<{ id: number; chunk_index: number; chunk_text: string; }>) => Array<{ id: number; chunk_index: number; start: number; end: number; }>"
]
},
+ {
+ "kind": "function",
+ "name": "longPageUnitValueProblem",
+ "signature": [
+ "(value: string) => string | null"
+ ]
+ },
{
"kind": "function",
"name": "pageEvidenceText",
@@ -7284,6 +7360,13 @@
"(engine: BrainEngine, hits: FrozenHit[], scope: PageReadScope) => Promise<{ rows: SearchResult[]; unresolved: number[]; }>"
]
},
+ {
+ "kind": "function",
+ "name": "selectLongPages",
+ "signature": [
+ "(engine: BrainEngine, plan: EvidencePlan | null, hits: SearchResult[], scope: DeliveryScope) => Promise<{ plan: EvidencePlan | null; longPages?: LongPageSelection; }>"
+ ]
+ },
{
"kind": "function",
"name": "splitPieces",
@@ -7297,6 +7380,13 @@
"signature": [
"(plan: EvidencePlan, reason: string) => DeliveryMeta"
]
+ },
+ {
+ "kind": "function",
+ "name": "withLongPagePolicy",
+ "signature": [
+ "(engine: BrainEngine, plan: EvidencePlan | null, input: { snippetChars: unknown; }) => Promise<EvidencePlan | null>"
+ ]
}
],
"./search/expansion": [
diff --git a/test/helpers/long-page-fixture.ts b/test/helpers/long-page-fixture.ts
new file mode 100644
index 0000000000..44fc07c07f
--- /dev/null
+++ b/test/helpers/long-page-fixture.ts
@@ -0,0 +1,81 @@
+/**
+ * Shared corpus and calls for the long-page delivery tests (F2,
+ * `search.long_page_unit`): the PGLite unit arm (test/evidence-long-page.test.ts)
+ * and the Postgres arm (test/e2e/evidence-long-page.test.ts).
+ *
+ * `contracts/msa-example` is the one long page (well over LONG_PAGE_MIN_BYTES,
+ * with ATX sections). Its term words ("renewal fee") recur in clauses that do
+ * not decide the value, so a delivered unit has to be anchored on the ranked
+ * hit, never on term overlap. The other pages are short; `chat/session-example`
+ * is a conversation for the mixed case.
+ */
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { operations, type OperationContext } from '../../src/core/operations.ts';
+import { dispatchToolCall } from '../../src/mcp/dispatch.ts';
+import { prepareMarkdownChunks } from '../../src/core/markdown-chunks.ts';
+import { installFixtureChunks } from './page-projection.ts';
+import { offPathMcpBytes } from './evidence-delivery-fixture.ts';
+import { withEnv } from './with-env.ts';
+
+const filler = (topic: string, n: number) => Array.from({ length: n }, (_, i) => `Clause ${i + 1} on ${topic} restates the general obligations of both parties and the notice address for correspondence.`).join(' ');
+
+export const LONG_SLUG = 'contracts/msa-example';
+export const DECIDING = 'Effective 2026-03-01 the annual renewal fee for acme-example is 4,200 USD.';
+
+export const LONG_PAGE_CORPUS: Array<{ slug: string; type: string; body: string }> = [
+ {
+ slug: LONG_SLUG,
+ type: 'note',
+ body: [
+ `## Definitions\n\nThe renewal fee means the amount stated in the order form. ${filler('definitions', 18)}`,
+ `## Fees\n\nNo renewal fee applies to trial seats, and the renewal fee is invoiced in advance. ${filler('fees', 18)}`,
+ `## Term and renewal\n\nThe agreement renews each year; a renewal fee change needs written notice. ${filler('term', 18)}`,
+ `## Amendment 2\n\n${DECIDING} ${filler('amendment', 6)}`,
+ `## Notices\n\n${filler('notices', 18)}`,
+ ].join('\n\n'),
+ },
+ { slug: 'notes/short-example', type: 'note', body: 'A short note: ask about the renewal fee before the call.' },
+ { slug: 'notes/handbook-example', type: 'note', body: `## Renewals\n\nThe handbook describes how a renewal fee is quoted. ${filler('handbook', 3)}` },
+];
+
+export const CONVERSATION_PAGE = {
+ slug: 'chat/session-example', type: 'note',
+ body: Array.from({ length: 6 }, (_, i) => `**user:** question ${i} about the renewal fee\n\n**assistant:** answer ${i} about the renewal fee and the notice period`).join('\n\n'),
+};
+
+export async function seedLongPages(engine: BrainEngine, pages = LONG_PAGE_CORPUS): Promise<void> {
+ for (const p of pages) {
+ await engine.putPage(p.slug, { type: p.type as never, title: p.slug, compiled_truth: p.body, timeline: '', frontmatter: {} });
+ await installFixtureChunks(engine, p.slug, await prepareMarkdownChunks({ compiled_truth: p.body, timeline: '' }));
+ }
+ await engine.setConfig('search.mcp_keyword_only', 'true');
+ await engine.setConfig('feedback.enabled', 'false');
+}
+
+/** One remote stdio MCP call, as the agent receives it (notice blocks removed); `rows` is the parsed content[0]. */
+export async function mcpCall(engine: BrainEngine, name: string, params: Record<string, unknown>): Promise<{ bytes: string; rows: Array<Record<string, unknown>> }> {
+ return withEnv({ GBRAIN_BACKUP_CHECK: '0' }, async () => {
+ const res = await dispatchToolCall(engine, name, params, { remote: true, transport: 'stdio', sourceId: 'default' });
+ const bytes = offPathMcpBytes(res as never);
+ const body = JSON.parse((JSON.parse(bytes) as { content: Array<{ text: string }> }).content[0].text) as unknown;
+ return { bytes, rows: Array.isArray(body) ? body as Array<Record<string, unknown>> : [] };
+ });
+}
+
+/** One op call through the handler (trusted local unless `remote`), returning the full rows and the retrieval meta. */
+export async function opCall(engine: BrainEngine, name: string, params: Record<string, unknown>, remote = false): Promise<{ result: unknown; meta: Record<string, unknown> | undefined }> {
+ let meta: Record<string, unknown> | undefined;
+ const ctx = {
+ engine, config: {}, logger: console, dryRun: false, remote, sourceId: 'default',
+ emitResponseMeta: (key: string, value: unknown) => { if (key === 'retrieval') meta = value as Record<string, unknown>; },
+ } as unknown as OperationContext;
+ const result = await operations.find(o => o.name === name)!.handler(ctx, params);
+ return { result, meta };
+}
+
+export async function withConfig<T>(engine: BrainEngine, values: Record<string, string>, run: () => Promise<T>): Promise<T> {
+ for (const [k, v] of Object.entries(values)) await engine.setConfig(k, v);
+ try { return await run(); } finally {
+ await engine.executeRaw(`DELETE FROM config WHERE key = ANY($1::text[])`, [Object.keys(values)]);
+ }
+}