Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
F2: a widened long-page row is exempt from snippet_chars; ranked chunk rows are still cut
garrytan1d5725fed805
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 089130f8f6..b5d5797b9b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -25,7 +25,7 @@ identifiers and attribution are available in the pre-removal Git revision- **A record can say it amends another without changing how either ranks.** A schema pack declares `amends` (`temporal: event`) and maps it from frontmatter per page type, so `amends: [{name, since}]` links the amendment to the record it changes and records when the new terms take effect (`link_relationships.first_start`). Amends edges are references only: every link-counting ranking reader skips them through one policy (`src/core/link-ranking-policy.ts`): backlink, in-set and cross-source adjacency boosts, relational fanout and chain hops, chain hub degree, enrich inbound order, entity-resolution connection count, generated-page demotion and entity anchoring. `get_links`, `get_backlinks`, `traverse_graph`, card edges, `backlink_count` and `referenced_by` still return them, and `supersedes` keeps its 0.5 down-rank for whole-record replacement. An amends edge whose `since` is still ahead is never hidden by the default liveness filter (`LIVENESS_EXEMPT_LINK_TYPES` in `src/core/link-validity.ts`), and card edges rank it beside events. Example pack: `examples/schema-packs/amends-example/pack.yaml`; guide: [amendments](docs/guides/temporal-edges.md#amendments-the-amends-link); existing pages pick it up with `gbrain extract links --source db --include-frontmatter`.- **Frontmatter `since`/`until` dates only the exact target when several objects match.** `src/core/link-temporal-evidence.ts` still accepts a slug-prefix name (`Acme` for `acme-example`) when it is the only match, but when several objects in one field match one target only the exact name dates it, so `{name: MSA Example}` no longer dates `msa-example-renewal`.- Tests: `test/amends-link.test.ts` (PGLite) and `test/e2e/amends-link-postgres.test.ts` (Postgres) share `test/helpers/amends-ranking-scenarios.ts`: one final-output invariance row per link-counting consumer, each with a ranking-type control that crosses its threshold; amendments versus `supersedes` through final search scores and labels; frontmatter `since` per exact target; and a frozen-clock check that a future-`since` amends edge stays in `get_backlinks`, `traverse_graph` and card edges. `test/link-temporal-evidence.test.ts` adds the prefix-sharing target pair.-- **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; `section` is the value under test). Under the implied `auto` on `search` and `query`, a hit on a page whose rendered body holds at least `search.long_page_min_chars` characters (new key, default 20,000) is widened to that unit inside the existing `search.return_budget_conversation` budget; every other hit keeps its ranked chunk, reserved first, and widened units fill only what is left. 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 a positive `snippet_chars` (which head-cuts every block) keeps it off, and `snippet_chars: 0` leaves it on. 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 character/byte-count preflight under the read scope, and delivery confirms the threshold on the rendered body; 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: replay case, threshold key, cap and explicit-unit paths byte-identical with the key on), `test/e2e/evidence-long-page.test.ts` (Postgres). No passage selector is built; the unit is chosen later by the frozen-hit comparison.+- **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; `section` is the value under test). Under the implied `auto` on `search` and `query`, a hit on a page whose rendered body holds at least `search.long_page_min_chars` characters (new key, default 20,000) is widened to that unit inside the existing `search.return_budget_conversation` budget; every other hit keeps its ranked chunk, reserved first, and widened units fill only what is left. 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` keeps it off. A widened row is exempt from `snippet_chars` and comes back whole, still inside `search.return_budget_conversation` and the long-page limits; `snippet_chars` keeps cutting every ranked chunk row, and `delivered {unit, reason}` explains the longer row. 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 character/byte-count preflight under the read scope, and delivery confirms the threshold on the rendered body; 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: replay case, threshold key, cap and explicit-unit paths byte-identical with the key on, `snippet_chars` 300 survival of the widened row on the serialized lean MCP output), `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.mdindex 326a8adfae..a3828eb35c 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`. `search.long_page_unit` (F2, default `off`): `withLongPagePolicy` (called only by the `search`/`query` caller, so recall, think and `assemble_evidence` never carry it) sets `plan.longPage` (unit plus `search.long_page_min_chars`, default 20,000) under an implied `auto` with no explicit budget or positive `snippet_chars`; `selectLongPages` runs one character/byte-count preflight under the read scope (long = stored body at least `minChars` characters, confirmed on the rendered `pageEvidenceText` at delivery; at most `LONG_PAGE_MAX_PAGES` 5 and `LONG_PAGE_MAX_INPUT_BYTES` 1,000,000, whole pages only; `LONG_PAGE_DEADLINE_MS` 2,000 for preflight plus fetch) and returns exactly `effectivePlan` when no page is long; `deliverEvidence` fetches the selected pages in their own bounded `getChunkWindows` call, delivers them in the unit with `reason: long_page`, and returns any it cannot deliver (limits, deadline, fetch failure, over budget) as their ranked chunk with `reason: long_page_chunk` and a `long_page_*` fallback. Normative spec: `docs/evidence-delivery.md`. Tests: `test/evidence-delivery.test.ts`, `test/evidence-delivery-golden.test.ts`, `test/e2e/evidence-delivery-leak.test.ts`, `test/e2e/evidence-delivery-parity.test.ts`; bench `scripts/bench-evidence-delivery.ts`.+- `src/core/search/evidence-delivery.ts` — the `return_unit` evidence assembler (default `auto`: conversation pages by type or `chat/`/`conversations/` slug come back whole under `search.return_budget_conversation` (24,000), every other hit is its unchanged chunk; `effectivePlan` skips the stage when an implied `auto` sees no conversation hit, so that path and `chunk` stay byte-identical). `resolveEvidencePlan` validates `return_unit` / `return_window` (invalid_params naming the allowed values and an example), reads `search.return_unit` / `think.return_unit`, `search.return_window`, `search.return_budget_default` (6,000), `search.return_budget_conversation` (24,000) and clamps remote budgets to `search.return_budget_max_remote` (32,000, reported). Snippet precedence: explicit `snippet_chars` > explicit `return_unit` > subagent default cap > config unit. `deliverEvidence` groups hits by page_id (one block per page at its best rank), makes ONE `engine.getChunkWindows` call (re-authorizes every page; unauthorized pages are dropped, never served from hit text), builds the page text from the stored body sanitized whole and passed through `credentialSafeProjection` before slicing (`pageEvidenceText`: compiled truth + serializer timeline sentinel + timeline; frontmatter excluded; private-key spans become newline-padded `<REDACTED:private_key_pem>` tokens, the same text the chunkers cut from), locates the hit chunks in it (`locateChunks`: exact, then whitespace-insensitive, since the chunker trims and folds whitespace), cuts `window` / `section` (ATX headings outside code fences, or conversation rounds detected structurally, never by page type) / `page` / `auto` (fenced-code hits are placed by their code minus the chunker's synthesized header), counts tokens as the sum of per-line cl100k counts, reserves each page's matching span before enriching by rank, caps blocks at 60,000 characters, redacts secrets before final accounting, and returns NEW rows with `delivered` plus a `delivery` meta. The plan records `budgetExplicit` (the caller passed the budget) and the resolved `packing` (`search.auto_packing` or the library override); `capEngaged` (unit `auto`, explicit budget, packing not `off`) routes allocation to `allocateCapped`: global rank one first (cut with `EVIDENCE_CUT_MARKER` when it alone exceeds the budget), the rank-order prefix of other non-conversation chunks that fits (rest `budget_note`), then conversations by `cap_only` (floors, then enrichment), `breadth_capped` (longest prefix whose title + floor + `return_window` target window fits; rest `breadth_cap`) or `depth_first` (each session grown in turn); nothing spills. `capEvidenceToBudget` recounts title + `chunk_text` at the final boundary (after redaction and `capDeliveredSnippets`, whose marker is paid from the row's own allocation) and rewrites `budget_used`. Without an explicit budget none of this runs and the bytes are the pre-cap path's. Fetch failure/timeout (5 s) falls back to the hit chunk only for live hits. `assembleEvidenceForHits` / op `assemble_evidence` deliver the exact evidence `query` returns for a frozen `(source_id, slug, chunk_id)` list, `effective_date` included (`applyEffectiveDate`, the live rows' normalizer); `evidenceFingerprint` hashes it (gbrain-evals E1/E3 parity). With `search.evidence_date_header` on (`plan.dateHeader`), each block (including `auto` passthrough chunks) starts with its one-line date header from `evidence-date.ts`, reserved in the block floor like the title, counted in `delivered.tokens`, with spans shifted past it and `delivery.date_header: true`; a failed date read renders `unknown` and adds `date_header_unavailable`. `search.long_page_unit` (F2, default `off`): `withLongPagePolicy` (called only by the `search`/`query` caller, so recall, think and `assemble_evidence` never carry it) sets `plan.longPage` (unit plus `search.long_page_min_chars`, default 20,000) under an implied `auto` with no explicit budget (`snippet_chars` does not turn it off; `capDeliveredSnippets` skips `reason: long_page` rows and cuts every other row); `selectLongPages` runs one character/byte-count preflight under the read scope (long = stored body at least `minChars` characters, confirmed on the rendered `pageEvidenceText` at delivery; at most `LONG_PAGE_MAX_PAGES` 5 and `LONG_PAGE_MAX_INPUT_BYTES` 1,000,000, whole pages only; `LONG_PAGE_DEADLINE_MS` 2,000 for preflight plus fetch) and returns exactly `effectivePlan` when no page is long; `deliverEvidence` fetches the selected pages in their own bounded `getChunkWindows` call, delivers them in the unit with `reason: long_page`, and returns any it cannot deliver (limits, deadline, fetch failure, over budget) as their ranked chunk with `reason: long_page_chunk` and a `long_page_*` fallback. Normative spec: `docs/evidence-delivery.md`. Tests: `test/evidence-delivery.test.ts`, `test/evidence-delivery-golden.test.ts`, `test/e2e/evidence-delivery-leak.test.ts`, `test/e2e/evidence-delivery-parity.test.ts`; bench `scripts/bench-evidence-delivery.ts`.- `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 by a ranking link type 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.mdindex ca80994eb1..978454a680 100644--- a/docs/evidence-delivery.md+++ b/docs/evidence-delivery.md@@ -199,16 +199,20 @@ delivered unit is always the one around the ranked hit.|---|---|---|---|| 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 positive `snippet_chars`, and the hit is a long non-conversation page | that unit (`delivered.reason: "long_page"`) |+| 3 | `search.long_page_unit` (not `off`) | `return_unit` omitted, `search.return_unit` unset or `auto`, no explicit `token_budget`, 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 theassembler, so `recall`, `think` (`think.return_unit`) and `assemble_evidence`-never read the key and stay byte-identical with it on. A positive-`snippet_chars` keeps it off because it cuts every delivered block from the-front, so a widened unit would lose its tail (`snippet_chars: 0`, full text,-leaves it on and the unit comes back whole);-an explicit `token_budget` keeps it off because the cap (next section) keeps+never read the key and stay byte-identical with it on. `snippet_chars` does+not turn it off: a row widened by it (`delivered: {unit, reason: "long_page"}`)+is exempt from `snippet_chars` and comes back whole, because a head cut would+drop the tail the unit was widened to reach. The widened row still sits inside+`search.return_budget_conversation` and the long-page page and input-byte+limits below, and `snippet_chars` still cuts every other row, ranked chunks+included (those rows report `delivered: {truncated: true}`). The+`delivered.unit` and `reason` on the row are what tell the reader why it is+longer than `snippet_chars`. An explicit `token_budget` keeps it off because the cap (next section) keepsits 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`.@@ -311,14 +315,17 @@ so a bare budget does not engage the cap.1. An explicit `snippet_chars` wins: delivered blocks are capped at that manycharacters (spans are clipped, `delivered.truncated` becomes true and- `snippet_cap` is reported).+ `snippet_cap` is reported). The one exemption is a row widened by+ `search.long_page_unit` (`delivered.reason: "long_page"`): it comes back+ whole, within `search.return_budget_conversation` and the long-page limits.2. Then an explicit `return_unit`: the subagent default snippet cap is skippedfor its blocks.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` (with `search.long_page_unit`- for long non-conversation hits, which an explicit `snippet_chars` keeps off).+ for long non-conversation hits, whose widened rows are exempt from an+ explicit `snippet_chars`; see rule 1).## Response shape (additive)diff --git a/docs/mcp/TOOL_REFERENCE.md b/docs/mcp/TOOL_REFERENCE.mdindex 678b303a44..c58a6d3a26 100644--- a/docs/mcp/TOOL_REFERENCE.md+++ b/docs/mcp/TOOL_REFERENCE.md@@ -299,7 +299,7 @@ Hybrid search with vector + keyword + multi-query expansion. Prefer `query` for| `limit` | number | Max results. Omitted or 0 resolves from the active search mode (10 conservative / 25 balanced / 50 tokenmax by default, or the configured `search.searchLimit` override) — for both text queries and image-similarity queries (`image` param). || `offset` | number | Skip first N results (for pagination) || `types` | array | Filter results to pages whose `type` is in this list (e.g. ['person','company']). CLI: --types person,company. Applied at SQL level on every retrieval leg — the same filter `whoknows` uses. Stacks with all other filters. |-| `snippet_chars` | number | Cap each result's chunk_text at N characters (a "… [truncated]" marker names the get_page recovery move). 0 forces full text. Unset: subagent tool loops default to the agent.search_snippet_chars config (300; 0=full); every other caller gets full text. |+| `snippet_chars` | number | Cap each result's chunk_text at N characters (a "… [truncated]" marker names the get_page recovery move). 0 forces full text. Unset: subagent tool loops default to the agent.search_snippet_chars config (300; 0=full); every other caller gets full text. A row widened by `search.long_page_unit` (`delivered: {unit, reason: "long_page"}`) is exempt and comes back whole; every other row is still cut. || `return_unit` | string (`chunk`, `window`, `section`, `page`, `auto`) | Evidence unit returned in each result's chunk_text (default: config search.return_unit, which defaults to 'auto').<br> 'chunk' — the ranked chunk only (~300-450 tokens per result).<br> 'window' — the hit chunk plus return_window neighbor chunks each side (local context, ~3x chunk).<br> 'section' — the enclosing markdown section, or the conversation rounds around the hit.<br> 'page' — the whole page/session, capped. Use for multi-session or temporal questions where the answer needs the whole conversation.<br> 'auto' — the whole page for conversation pages (conversation/transcript/chat/meeting/slack/imessage types, chat/ or conversations/ slugs), the ranked chunk unchanged for everything else. When no hit is a conversation the response is exactly the chunk response.<br>Non-chunk units return one result per page, packed into token_budget (default 6000, auto 24000; remote max 32000), with a `delivered` object (unit, chunk_ids, match_spans, tokens, truncated; reason under auto) per result and `delivery` in the response meta. || `return_window` | number | Neighbor chunks on each side for return_unit 'window' (integer 1-3, default 1). || `token_budget` | number | Token budget. Chunk mode, and whenever return_unit is omitted: caps the cumulative chunk payload (results that would overflow are skipped). Explicit non-chunk return_unit: the budget for delivered evidence (default search.return_budget_default = 6000, auto 24000; remote max search.return_budget_max_remote = 32000). |@@ -396,7 +396,7 @@ Every call also reports how many pages match the query's keywords (`keyword_tota| `mode` | string | Search mode (conservative\|balanced\|tokenmax). Local callers only: an agent-facing caller that sets it is refused (`search_mode_local_only`) with a fix naming `match: "keyword"`. || `source_id` | string | Scope search to a single source. Defaults to OperationContext.sourceId (set from CLI --source / GBRAIN_SOURCE / .gbrain-source dotfile); when unset, an unqualified read spans every federated source. Pass '__all__' to span every source for trusted local callers; for remote callers '__all__' spans only your granted sources. || `types` | array | Filter results to pages whose `type` is in this list (e.g. ['person','company']). CLI: --types person,company. Applied at SQL level on every retrieval leg — the same filter `whoknows` uses. Stacks with all other filters. |-| `snippet_chars` | number | Cap each result's chunk_text at N characters (a "… [truncated]" marker names the get_page recovery move). 0 forces full text. Unset: subagent tool loops default to the agent.search_snippet_chars config (300; 0=full); every other caller gets full text. |+| `snippet_chars` | number | Cap each result's chunk_text at N characters (a "… [truncated]" marker names the get_page recovery move). 0 forces full text. Unset: subagent tool loops default to the agent.search_snippet_chars config (300; 0=full); every other caller gets full text. A row widened by `search.long_page_unit` (`delivered: {unit, reason: "long_page"}`) is exempt and comes back whole; every other row is still cut. || `return_unit` | string (`chunk`, `window`, `section`, `page`, `auto`) | Evidence unit returned in each result's chunk_text (default: config search.return_unit, which defaults to 'auto').<br> 'chunk' — the ranked chunk only (~300-450 tokens per result).<br> 'window' — the hit chunk plus return_window neighbor chunks each side (local context, ~3x chunk).<br> 'section' — the enclosing markdown section, or the conversation rounds around the hit.<br> 'page' — the whole page/session, capped. Use for multi-session or temporal questions where the answer needs the whole conversation.<br> 'auto' — the whole page for conversation pages (conversation/transcript/chat/meeting/slack/imessage types, chat/ or conversations/ slugs), the ranked chunk unchanged for everything else. When no hit is a conversation the response is exactly the chunk response.<br>Non-chunk units return one result per page, packed into token_budget (default 6000, auto 24000; remote max 32000), with a `delivered` object (unit, chunk_ids, match_spans, tokens, truncated; reason under auto) per result and `delivery` in the response meta. || `return_window` | number | Neighbor chunks on each side for return_unit 'window' (integer 1-3, default 1). || `token_budget` | number | Token budget for delivered evidence when return_unit is not 'chunk' (default search.return_budget_default = 6000; auto: search.return_budget_conversation = 24000). Ignored in chunk mode. |diff --git a/src/core/ops/search.ts b/src/core/ops/search.tsindex ecd16f2d18..ce587cb85d 100644--- a/src/core/ops/search.ts+++ b/src/core/ops/search.ts@@ -164,7 +164,7 @@ async function evidencePlanFor(ctx: OperationContext, p: Record<string, unknown>snippetChars: p.snippet_chars,snippetCap,op,- }), { snippetChars: p.snippet_chars });+ }));}/**diff --git a/src/core/search/evidence-delivery.ts b/src/core/search/evidence-delivery.tsindex c8c4cd944a..ea0b2b97ea 100644--- a/src/core/search/evidence-delivery.ts+++ b/src/core/search/evidence-delivery.ts@@ -357,15 +357,14 @@ export function longPageMinCharsValueProblem(value: string): string | null {/*** 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 positive- * `snippet_chars` (it head-cuts every delivered block, so a widened unit- * would lose its tail; `0` means full text and leaves it on). Read errors and- * unknown values are `off`; an unusable threshold is the default.+ * `auto`: no `return_unit` on the call, `search.return_unit` unset or `auto`+ * and no explicit budget (the cap keeps its rules). `snippet_chars` does not+ * turn it off: a widened row (`delivered.reason: 'long_page'`) is exempt from+ * the snippet cap (capDeliveredSnippets), every other row is cut as before.+ * Read errors and unknown values are `off`; an unusable threshold is the default.*/-export async function withLongPagePolicy(engine: BrainEngine, plan: EvidencePlan | null, input: { snippetChars: unknown }): Promise<EvidencePlan | null> {+export async function withLongPagePolicy(engine: BrainEngine, plan: EvidencePlan | null): Promise<EvidencePlan | null> {if (!plan || plan.unit !== 'auto' || plan.explicitUnit || plan.budgetExplicit) return plan;- if (typeof input.snippetChars === 'number' && Number.isFinite(input.snippetChars) && Math.floor(input.snippetChars) > 0) return plan;const raw = (await engine.getConfig(LONG_PAGE_UNIT_CONFIG_KEY).catch(() => null))?.trim();if (raw !== 'window' && raw !== 'section' && raw !== 'page') return plan;const min = (await engine.getConfig(LONG_PAGE_MIN_CHARS_CONFIG_KEY).catch(() => null)) ?? '';@@ -1420,7 +1419,10 @@ export function capEvidenceToBudget<T extends SearchResult & { delivered?: Deliv/*** Explicit `snippet_chars` precedence: cap delivered blocks at `cap`* characters (marker names the get_page recovery move), clip spans, mark- * truncated and re-count. Non-mutating.+ * truncated and re-count. A long-page row widened by the F2 policy+ * (`delivered.reason: 'long_page'`) is exempt: it already fits the delivery+ * budget and the page limits, and a head cut would drop the passage it was+ * widened for. Non-mutating.*/export function capDeliveredSnippets<T extends SearchResult & { delivered?: DeliveredEvidence }>(results: T[],@@ -1432,7 +1434,7 @@ export function capDeliveredSnippets<T extends SearchResult & { delivered?: Deliconst tokenizer = delivery.tokenizer;let markerOmitted = false;const out = results.map(r => {- if (typeof r.chunk_text !== 'string' || r.chunk_text.length <= cap) return r;+ if (typeof r.chunk_text !== 'string' || r.chunk_text.length <= cap || r.delivered?.reason === 'long_page') return r;any = true;let keep = cap;let text = r.chunk_text.slice(0, cap) + buildSnippetMarker(r.slug, r.chunk_text.length - cap, r.follow_up);diff --git a/test/e2e/evidence-long-page.test.ts b/test/e2e/evidence-long-page.test.tsindex 5dccb63810..e99fd55b1e 100644--- a/test/e2e/evidence-long-page.test.ts+++ b/test/e2e/evidence-long-page.test.ts@@ -5,7 +5,7 @@* golden, the replay case (default 20,000-character threshold, section; a* medium and a short hit keep their ranked chunks), the cap and explicit-unit* paths unchanged with the key on, the serialized lean MCP `delivered {unit,- * reason}`, the precedence+ * reason}`, the widened row surviving `snippet_chars` 300, 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.@@ -78,6 +78,24 @@ run('long-page delivery on Postgres', () => {}});+ test('snippet_chars 300: the widened section survives whole with delivered {unit, reason}; every other row is cut to 300 exactly as with the key off and marks delivered {truncated}', async () => {+ const off = await mcpCall(engine, 'search', { query: 'renewal fee', snippet_chars: 300 });+ const [on, full] = await withConfig(engine, { [KEY]: 'section' }, async () => [+ await mcpCall(engine, 'search', { query: 'renewal fee', snippet_chars: 300 }),+ await mcpCall(engine, 'search', { query: 'renewal fee' }),+ ]);+ const widened = long(on.rows);+ expect(widened.delivered).toEqual({ unit: 'section', reason: 'long_page' });+ expect(widened.chunk_text).toBe(long(full.rows).chunk_text);+ expect(String(widened.chunk_text).length).toBeGreaterThan(300);+ for (const r of on.rows.filter(r => r.slug !== LONG_SLUG)) {+ const { delivered, ...rest } = r;+ expect(JSON.stringify(rest)).toBe(JSON.stringify(off.rows.find(o => o.slug === r.slug)));+ expect(delivered).toEqual(String(r.chunk_text).includes('[truncated ') ? { truncated: true } : undefined);+ }+ expect(on.rows.some(r => r.slug !== LONG_SLUG && String(r.chunk_text).includes('[truncated '))).toBe(true);+ });+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' }));diff --git a/test/evidence-long-page.test.ts b/test/evidence-long-page.test.tsindex 23ddc197c9..8f4d5d82f6 100644--- a/test/evidence-long-page.test.ts+++ b/test/evidence-long-page.test.ts@@ -8,8 +8,8 @@* Long means a rendered body of at least `search.long_page_min_chars`* (default 20,000) characters. Precedence (docs/evidence-delivery.md "Long* pages"): explicit `return_unit` > non-`auto` `search.return_unit` >- * `search.long_page_unit`; an explicit `token_budget` or a positive- * `snippet_chars` keeps it off. recall, think and+ * `search.long_page_unit`; an explicit `token_budget` keeps it off. A widened+ * row is exempt from `snippet_chars`; every other row is cut. 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.@@ -207,15 +207,24 @@ describe('precedence', () => {}});- test('a positive snippet_chars keeps the key off (it head-cuts every block); 0 (full text) leaves it on and the section survives whole', async () => {- 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);- const whole = await withConfig(engine, { [KEY]: 'section' }, async () => [- long((await mcpCall(engine, 'search', { query: 'renewal fee', snippet_chars: 0 })).rows),- long((await mcpCall(engine, 'search', { query: 'renewal fee' })).rows),+ test('snippet_chars 300: the widened section survives whole and keeps delivered {unit, reason}; every other row is cut to 300 exactly as with the key off and marks delivered {truncated}', async () => {+ const off = await mcpCall(engine, 'search', { query: 'renewal fee', snippet_chars: 300 });+ const [on, full] = await withConfig(engine, { [KEY]: 'section' }, async () => [+ await mcpCall(engine, 'search', { query: 'renewal fee', snippet_chars: 300 }),+ await mcpCall(engine, 'search', { query: 'renewal fee' }),]);- expect(whole[0].delivered).toEqual({ unit: 'section', reason: 'long_page' });- expect(whole[0].chunk_text).toBe(whole[1].chunk_text);+ const widened = long(on.rows);+ expect(widened.delivered).toEqual({ unit: 'section', reason: 'long_page' });+ expect(widened.chunk_text).toBe(long(full.rows).chunk_text);+ expect(String(widened.chunk_text).length).toBeGreaterThan(300);+ for (const r of on.rows.filter(r => r.slug !== LONG_SLUG)) {+ const { delivered, ...rest } = r;+ expect(JSON.stringify(rest)).toBe(JSON.stringify(off.rows.find(o => o.slug === r.slug)));+ expect(delivered).toEqual(String(r.chunk_text).includes('[truncated ') ? { truncated: true } : undefined);+ }+ expect(on.rows.some(r => r.slug !== LONG_SLUG && String(r.chunk_text).includes('[truncated '))).toBe(true);+ const zero = await withConfig(engine, { [KEY]: 'section' }, () => mcpCall(engine, 'search', { query: 'renewal fee', snippet_chars: 0 }));+ expect(long(zero.rows).chunk_text).toBe(long(full.rows).chunk_text);});});@@ -283,16 +292,16 @@ describe('selection limits (size preflight)', () => {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 positive snippet_chars', async () => {+ test('the policy is resolved only under an implied auto, with no explicit budget; snippet_chars does not turn it off', 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);+ (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' })))?.longPage ?? null);expect(await resolve({})).toEqual({ unit: 'page', minChars: DEFAULT_LONG_PAGE_MIN_CHARS });expect(await resolve({}, { [MIN_KEY]: '5000' })).toEqual({ unit: 'page', minChars: 5000 });expect(await resolve({}, { [MIN_KEY]: 'lots' })).toEqual({ unit: 'page', minChars: DEFAULT_LONG_PAGE_MIN_CHARS });expect(await resolve({ snippet_chars: 0 })).toEqual({ unit: 'page', minChars: DEFAULT_LONG_PAGE_MIN_CHARS });expect(await resolve({ return_unit: 'auto' })).toBeNull();expect(await resolve({ token_budget: 2000 })).toBeNull();- expect(await resolve({ snippet_chars: 200 })).toBeNull();+ expect(await resolve({ snippet_chars: 200 })).toEqual({ unit: 'page', minChars: DEFAULT_LONG_PAGE_MIN_CHARS });expect(await resolve({}, { 'search.return_unit': 'section' })).toBeNull();});