Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

v0.60.23.0 feat(search): auto-detect conversation evidence by default + page-unit code fallback fix (#5785)

Garry Tanf7a6d42e4b6a
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 62441af678..ea1ba30db9 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.60.22.0",
+ "version": "0.60.23.0",
"description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.",
"author": {
"name": "Garry Tan",
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index 149952810e..694f85811d 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.60.22.0",
+ "version": "0.60.23.0",
"description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.",
"author": {
"name": "Garry Tan",
diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.md
index 1778928d70..c64c314082 100644
--- a/BOOTSTRAP_FOR_AGENTS.md
+++ b/BOOTSTRAP_FOR_AGENTS.md
@@ -1,4 +1,4 @@
-<!-- gbrain-runbook-stamp: 0.60.22.0 -->
+<!-- gbrain-runbook-stamp: 0.60.23.0 -->
<!-- This stamp must equal the VERSION file at every release; CI enforces it
(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it to
the installed binary and warns on skew. -->
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0d45fd5d42..14eea5f797 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,67 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [0.60.23.0] - 2026-09-30
+
+**Search now returns whole conversations by default. A hit on a session, transcript, meeting or chat log comes back as the full page, and every other hit stays exactly the chunk it was. On development data this answered far more conversation questions than chunks, at about four times the reading cost for those hits. A held-out check could not confirm the gain because its chats were too short to show one. Also fixed: two evidence-delivery bugs where a page whose best hit was fenced code got that code chunk instead of the page, and the code chunker's synthesized header line leaked into delivered text.**
+
+`return_unit` now defaults to `auto`, and `auto` changed meaning. It decides per hit from fields every search row already has, with no extra query and no model call. When the page type is `conversation`, `transcript`, `chat`, `meeting`, `slack` or `imessage` (and their collector variants), or the slug starts with `chat/` or `conversations/`, the hit gets the `page` unit: the whole sanitized body plus timeline, exactly what `return_unit: "page"` returns. Pages from `gbrain transcripts ingest` and the chat connectors match both rules. Everything else keeps its ranked chunk byte for byte, and a response with no conversation hit is exactly the chunk response.
+
+What was measured (gbrain-evals report, [PR #49](https://github.com/garrytan/gbrain-evals/pull/49), `docs/benchmarks/2026-09-30-evidence-auto-v2.md`). Both runs used an earlier 16,000-token default budget:
+
+| | Correct | Reader input per question |
+| --- | --- | --- |
+| LongMemEval-S (500 questions, development data): chunks | 312 | about 3,500 tokens |
+| LongMemEval-S: `auto` | 445 (+145 / −12 against chunks, p = 4e-30) | about 15,100 tokens |
+| LongMemEval-S: whole page (reference) | 457 | about 15,300 tokens |
+| Sealed confirmation set (150 new questions, preregistered): chunks | 147 | about 3,100 tokens |
+| Sealed confirmation set: `auto` | 149 (+2 / −0) | about 5,000 tokens |
+
+LongMemEval-S is development data: the evidence-delivery work was designed on it, so its result is not an independent test. The preregistered sealed check returned **fail**. Chunks already scored 147 of 150, because the sealed chats are short, so the check could show neither a benefit nor harm. Garry chose to ship `auto` on the development-data evidence. A harder sealed set is being built to confirm it.
+
+The default budget is now **24,000 tokens**, raised after that measurement. At 16,000, 81 of the 500 LongMemEval questions had sessions trimmed, which cost about 4 correct answers against whole pages. A follow-up check measures the 24,000 default.
+
+| | Before | After |
+| --- | --- | --- |
+| Hit on a conversation page, `return_unit` omitted | the ranked chunk | the whole page, one result per page at its best rank |
+| Any other hit | the ranked chunk | the same chunk, unchanged |
+| Response with no conversation hit | — | byte-identical to `return_unit: "chunk"` (no `delivered`, no `delivery`) |
+| Budget for conversations | — | 24,000 tokens (`search.return_budget_conversation`), clamped to 32,000 for remote callers |
+| Why a result got its unit | — | `delivered.reason` and `gbrain search --explain` |
+
+Things to watch: the cost is real. When search hits conversations, your agent reads whole sessions: about 15,000 tokens per question instead of about 3,500 in the LongMemEval run, and up to the 24,000-token budget. Searches with no conversation hits cost exactly what they did before. To get the old behavior everywhere, pass `return_unit: "chunk"`, or run `gbrain config set search.return_unit chunk` and `gbrain config set think.return_unit chunk`. To keep `auto` with less reading, lower `search.return_budget_conversation`. Old knobs keep their meaning: with no `return_unit`, `query`'s `token_budget` and `recall`'s `budget_tokens` or `budget_policy` still work on chunks, and subagent snippet caps still keep subagent searches on chunks. Expansion still never shows more than `get_page` shows the same caller.
+
+### To take advantage of v0.60.23.0
+
+`gbrain upgrade`. There is no migration. To see what `auto` decided for each result:
+
+```bash
+gbrain search "when did we move the launch?" --explain
+```
+
+**Say to your agent:** *"Search my brain for what we decided about the acme-example renewal, then read the sessions that come back."*
+
+The detection rules, budget sharing and fallback codes are in `docs/evidence-delivery.md`. To measure the default on a frozen hit list, call `assemble_evidence` with `return_unit: "auto"`.
+
+### Itemized changes
+
+#### Evidence delivery: `auto` v2 is the default
+- `resolveEvidencePlan` resolves an omitted `return_unit` (and unset `search.return_unit` / `think.return_unit`) to `auto`. `auto` uses `search.return_budget_conversation` (new, default 24,000) when no budget is passed, with the same remote clamp. An implied `auto` stays on `chunk` under the subagent snippet cap, `query`'s `token_budget` and `recall`'s `budget_tokens` or `budget_policy`, because recall packs facts first and a whole session would lose to them.
+- `conversationSignal` detects conversation hits from page type or slug prefix. `effectivePlan` skips the stage when an implied `auto` sees no conversation hit, so those responses, image queries included, stay byte-identical. An explicit `auto` always runs and reports each decision.
+- In `deliverEvidence`, `auto` gives conversation pages the `page` unit and passes every other hit through as its unchanged row with `delivered: { unit: "chunk", reason: "not_conversation" }`. Those unchanged chunks are paid for first. Conversation pages then share the rest of the budget in rank order, each reserving its matching span first. A conversation whose span no longer fits keeps its ranked chunks (`conversation_over_budget`) instead of being dropped.
+- `delivered.reason` (auto only): `conversation_type`, `conversation_slug`, `not_conversation`, `conversation_over_budget`. `--explain` prints `evidence: <unit> (<reason>)` per result.
+- `think` renders conversation pages whole under `auto` and keeps its usual excerpts for every other page. `recall` applies the same default.
+- `assemble_evidence` accepts `auto`, so gbrain-evals can measure the product default on frozen hits.
+
+#### Evidence delivery fixes
+- **A fenced-code best hit gets the page.** Fenced-code chunks are indexed after every prose chunk, so a hit on the second or later code chunk had no text chunk within `return_window`. The assembler fell back to that code chunk even for `return_unit: "page"`. The hit is now placed in the page text by its code, and the fallback fires only when nothing can be placed.
+- **Delivered text never carries the code chunker's header.** A fenced-code chunk starts with a synthesized `[TypeScript] fence.ts:27-30 …` line that is not page text. It is now stripped before the chunk is placed or used as fallback text.
+- `SearchResult.chunk_source` now includes `fenced_code`, which search already returned at runtime.
+
+#### Tests
+- The leak suite's "subset of `get_page`" invariant now runs `search`, `query`, `recall` and `assemble_evidence` for every unit plus the implied default. Besides ranked hits, it uses frozen hits naming every chunk of every page, including fenced code, and a conversation page with its own protected rows. Whole-page blocks must be made of whole `get_page` lines, and `page` requests must not fall back. The old invariant compared only ranked `search` page-unit hits on a corpus with no fenced code, so ranking never reached the header case.
+- The off-path golden now pins `chunk` (explicit and config) to the pre-feature fixture. On a corpus without conversations the implied `auto` must match `chunk` byte for byte, and on the full corpus every non-conversation row must equal its frozen chunk row. The parity suite checks the default against `assemble_evidence` with `auto` on both engines.
+
## [0.60.22.0] - 2026-09-30
**Links now come back in the same order every time. `get_links`, backlinks and every caller that reads them return edges in the order the links were created, instead of whatever order the database happened to store them in.**
diff --git a/VERSION b/VERSION
index f325e224b8..3d8e958e4c 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.60.22.0
+0.60.23.0
diff --git a/docs/architecture/RETRIEVAL.md b/docs/architecture/RETRIEVAL.md
index 78d7653409..09bc5a9a1c 100644
--- a/docs/architecture/RETRIEVAL.md
+++ b/docs/architecture/RETRIEVAL.md
@@ -369,8 +369,8 @@ Each stage is testable in isolation. Each stage is replaceable. The whole pipeli
## Evidence delivery: whole evidence after ranking
Ranking decides which pages matter; the reader still needs enough of each page
-to answer. `return_unit` (`window`, `section`, `page`, `auto`; default `chunk`)
-adds an opt-in stage after ranking, cache and capture, and before output
+to answer. `return_unit` (`chunk`, `window`, `section`, `page`, `auto`; default `auto`)
+adds a stage after ranking, cache and capture, and before output
redaction and snippet capping, shared by `search`, `query`, `recall` and
`think` (via `think.return_unit`). It groups the ranked hits by page, reads
every needed neighbor chunk in ONE batched, page_id-keyed query that
@@ -380,12 +380,18 @@ overlap never duplicates text), cuts the requested unit around the hits,
and packs blocks by rank into the token budget with a per-page floor so lower
ranked sessions keep their matching span. The strict protected-body sanitizer
runs on the whole body first, so delivered evidence never contains more than
-`get_page` returns to the same caller. With the default `chunk` the stage does not run and responses are
-byte-identical. The measured motivation (full sessions 89/100 against
-top-5 chunks 65/100 on a fixed LongMemEval-S subset, reranker off) and the
-earlier failed lexical excerpt selector (`docs/eval/ANSWER_PACKET_RESULTS.md`)
-are why `page` is the reference and the default stays `chunk` until a matched
-study shows a benefit. Contract, algorithms and latency:
+`get_page` returns to the same caller. The default `auto` expands only
+conversation pages (by page type or `chat/` / `conversations/` slug) to the
+whole page and leaves every other hit its ranked chunk; with no conversation
+hit, or with `chunk`, the stage does not run and responses are byte-identical. The measured motivation: on 400 held-out
+LongMemEval questions whole sessions answered 361 against 253 for top-5
+chunks, while neighbor windows reached only 285–292, so `auto` gives
+conversations exactly the `page` unit. `auto` itself answered 445 of 500
+LongMemEval-S questions against 312 for chunks (development data), and the
+preregistered sealed check was inconclusive at a ceiling (149 against 147 of
+150); see `docs/evidence-delivery.md` for the numbers and the token cost. The
+earlier failed lexical excerpt selector is in
+`docs/eval/ANSWER_PACKET_RESULTS.md`. Contract, algorithms and latency:
[`docs/evidence-delivery.md`](../evidence-delivery.md).
## How to verify on your own brain
diff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.md
index 3bf43b170a..59ebcea875 100644
--- a/docs/architecture/key-files/core-search-2.md
+++ b/docs/architecture/key-files/core-search-2.md
@@ -3,7 +3,7 @@
[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
-- `src/core/search/evidence-delivery.ts` — the `return_unit` evidence assembler (opt-in; default `chunk` = inert, byte-identical off path). `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) 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 before slicing (`pageEvidenceText`: compiled truth + serializer timeline sentinel + timeline; frontmatter excluded), 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`, 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. 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; `evidenceFingerprint` hashes it (gbrain-evals E1/E3 parity). 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 before slicing (`pageEvidenceText`: compiled truth + serializer timeline sentinel + timeline; frontmatter excluded), 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. 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; `evidenceFingerprint` hashes it (gbrain-evals E1/E3 parity). 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/chunk-windows.ts` — request/response shapes and the row mapper for `BrainEngine.getChunkWindows`. The SQL lives once in `src/core/engine-sql/chunks.ts` (`getChunkWindows`): page rows (authorization + seal + max chunk index + raw body columns) and chunk rows (inside the requested chunk_index ranges, text modality, requested chunk sources, row cap) come back in one UNION so the row cap never hides a page's authorization; the predicate is the search legs' (source scope, deleted, current text projection, archived source, quarantine, private pages, safe chunks). Postgres runs it inside the scoped read transaction.
diff --git a/docs/evidence-delivery.md b/docs/evidence-delivery.md
index 2a5e7c694c..8f764fc905 100644
--- a/docs/evidence-delivery.md
+++ b/docs/evidence-delivery.md
@@ -1,12 +1,21 @@
# Evidence delivery (`return_unit`)
-> Status: shipped opt-in. The default stays `chunk` until the matched study in
-> gbrain-evals shows a benefit (full sessions 89/100 against top-5 chunks
-> 65/100 on a fixed LongMemEval-S subset, reranker off; an earlier lexical
-> excerpt selector lost 53/60 → 48/60, see
-> [`docs/eval/ANSWER_PACKET_RESULTS.md`](eval/ANSWER_PACKET_RESULTS.md)). If
-> only `page` recovers the gap, `page` stays a documented opt-in at its full
-> token cost.
+> Status: the default is `auto` (v0.60.23.0): conversation pages come back
+> whole, every other hit is its unchanged ranked chunk. On LongMemEval-S
+> (500 questions, development data) `auto` at a 16,000-token budget answered
+> 445 against 312 for chunks (+145 / −12, p = 4e-30) and 457 for whole pages,
+> at about 15,100 reader tokens per question against about 3,500. The
+> preregistered sealed confirmation set (150 new questions) returned `fail` at
+> a ceiling: chunks 147, `auto` 149 (+2 / −0), because its chats are short. It
+> showed no benefit and no harm. `auto` ships on the development-data evidence
+> while a harder sealed set is built. The default budget was then raised to
+> 24,000 tokens to cut session trimming (81 of 500 questions were trimmed at
+> 16,000), and a follow-up check measures it. Report:
+> [gbrain-evals PR #49](https://github.com/garrytan/gbrain-evals/pull/49)
+> (`docs/benchmarks/2026-09-30-evidence-auto-v2.md`). Earlier history: whole
+> sessions beat chunks 361/400 against 253/400 while neighbor windows reached
+> only 285–292, and a lexical excerpt selector lost 53/60 → 48/60 (see
+> [`docs/eval/ANSWER_PACKET_RESULTS.md`](eval/ANSWER_PACKET_RESULTS.md)).
Search returns ranked **chunks**. An agent that needs the surrounding
conversation or section has to call `get_page` for each hit. Evidence delivery
@@ -14,8 +23,12 @@ lets `search`, `query`, `recall` and `think` return the surrounding evidence in
the same call: a window of neighboring chunks, the enclosing section, or the
whole page, packed into a token budget.
-It is **opt-in**. With `return_unit` omitted and the config at its default
-(`chunk`), every response is byte-identical to earlier releases.
+With `return_unit` omitted the unit is `auto`: hits on conversation pages
+(see [Conversation detection](#conversation-detection)) come back as the whole
+page, every other hit stays the ranked chunk it was. A response with no
+conversation hit is byte-identical to earlier releases. `return_unit: "chunk"`
+(or `gbrain config set search.return_unit chunk`) turns the stage off
+entirely.
**Say to your agent:** *"Search my brain for what alice-example said about the
launch date, and read the whole conversation, not just the snippet."*
@@ -41,11 +54,11 @@ gbrain recall --query "renewal terms" --return-unit section --budget-tokens 4000
| `return_unit` | What each result's `chunk_text` holds | Typical cost |
|---|---|---|
-| `chunk` (default) | The ranked chunk only (today's behavior). | ~300–450 tokens per result |
+| `chunk` | The ranked chunk only (the pre-0.60.23 default). | ~300–450 tokens per result |
| `window` | The hit chunk plus `return_window` (1–3, default 1) neighbor chunks on each side, same page. Overlapping windows merge. | ~3× chunk per result |
| `section` | The enclosing markdown section (by ATX heading). On conversation pages: the user→assistant rounds that overlap the hit. No structure → falls back to `window`. | varies |
| `page` | The whole page or session, capped at 60,000 characters and by the budget. | whole page |
-| `auto` | `page` for conversation-shaped pages and short pages; `section` for long pages with headings; `window` otherwise. Each result's `delivered.unit` says which branch ran. | budget-bound |
+| `auto` (default) | Per hit: `page` for conversation pages, the unchanged ranked chunk for everything else. Each result's `delivered.unit` and `delivered.reason` say which, and why. | whole sessions, 24,000-token default budget |
Use `page` for multi-session / temporal questions where the answer depends on
the whole conversation. Use `window` when you only need local context.
@@ -55,22 +68,59 @@ the whole conversation. Use `window` when you only need local context.
Per-call params on `search`, `query`, `recall`:
- `return_unit`: `chunk` | `window` | `section` | `page` | `auto`. Default from
- config `search.return_unit` (default `chunk`).
+ config `search.return_unit` (default `auto`).
- `return_window`: integer 1–3, default from `search.return_window` (default 1).
- Used by `window` (and by the `section`/`auto` fallbacks to `window`).
+ Used by `window` (and by the `section` fallback to `window`).
- Budget: `token_budget` on `search` / `query`, `budget_tokens` on `recall`.
- When a non-`chunk` unit applies and no budget is given,
- `search.return_budget_default` (default 6,000) applies. Remote callers are
- clamped to `search.return_budget_max_remote` (default 32,000); the clamp is
- reported in `delivery.budget_clamped` and `delivery.fallbacks`, never raised.
-
-Think reads `think.return_unit` (default `chunk`) and never
-`search.return_unit`, so flipping search's default does not change `think`.
+ When no budget is given, `auto` uses `search.return_budget_conversation`
+ (default 24,000: chat sessions run about 15K tokens, and at 16,000 some
+ long sessions were still trimmed) and the other units use
+ `search.return_budget_default` (default 6,000). Remote callers are clamped to
+ `search.return_budget_max_remote` (default 32,000); the clamp is reported in
+ `delivery.budget_clamped` and `delivery.fallbacks`, never raised.
+- Legacy budget knobs keep their meaning: with `return_unit` omitted,
+ `query`'s `token_budget` still prunes chunks (chunk mode), and `recall`'s
+ `budget_tokens` / `budget_policy` still pack chunks (facts first), so any of
+ them keeps an implied `auto` on `chunk`.
+
+Think reads `think.return_unit` (default `auto`) and never
+`search.return_unit`, so changing search's default does not change `think`.
+Under `auto`, think renders conversation pages whole and keeps its usual
+excerpts for every other page.
Config keys: `search.return_unit`, `search.return_window`,
-`search.return_budget_default`, `search.return_budget_max_remote`,
-`think.return_unit`. Kill switch: `gbrain config set search.return_unit chunk`
-(or pass `return_unit: "chunk"` per call).
+`search.return_budget_default`, `search.return_budget_conversation`,
+`search.return_budget_max_remote`, `think.return_unit`. Kill switch:
+`gbrain config set search.return_unit chunk` and
+`gbrain config set think.return_unit chunk` (or pass `return_unit: "chunk"`
+per call).
+
+### Conversation detection
+
+`auto` decides per hit from fields every search row already carries, with no
+extra query and no model call:
+
+1. **Page type** is one of `conversation` (what `gbrain transcripts ingest` and
+ the chat connectors write), `transcript`, `chat`, `meeting`, `slack`,
+ `slack-dm-day`, `slack-thread`, `imessage` or `imessage-daily`
+ (case-insensitive). Reason: `conversation_type`.
+2. Otherwise the **slug** starts with `chat/` (chat imports and the LongMemEval
+ adapter) or `conversations/` (the transcripts and connectors ingest
+ directory). Reason: `conversation_slug`.
+3. Anything else keeps its ranked chunk unchanged. Reason: `not_conversation`.
+
+Pages the transcripts and connectors paths write carry both signals (type
+`conversation` under `conversations/`), so their `transcript_import`
+frontmatter is not read separately. Detection never looks at body text, so a
+curated note that happens to quote a dialogue stays on the chunk path.
+
+Conversation hits share the budget in rank order, after the unchanged chunks
+are paid for. Each conversation page first reserves its matching span, then
+the pages grow toward complete in rank order, so a lower-ranked session still
+keeps the part that matched. A conversation whose matching span no longer
+fits keeps its ranked chunks unchanged (reason `conversation_over_budget`), so
+`auto` never returns less than `chunk` would. `budget_used` exceeds
+`budget_tokens` only by such unchanged chunks.
### Precedence with `snippet_chars`
@@ -80,14 +130,16 @@ Config keys: `search.return_unit`, `search.return_window`,
2. Then an explicit `return_unit`: the subagent default snippet cap is skipped
for its blocks.
3. Then the subagent default snippet cap (`agent.search_snippet_chars`, 300):
- when it applies, a config-level `search.return_unit` does **not** expand.
-4. Then `search.return_unit` from config.
+ when it applies, neither the implied `auto` nor a config-level
+ `search.return_unit` expands.
+4. Then `search.return_unit` from config, else `auto`.
## Response shape (additive)
When a non-`chunk` unit is applied, each result's existing `chunk_text`
carries the delivered evidence (no duplicated body field), and each result
-gains `delivered`:
+gains `delivered`. An implied `auto` with no conversation hit is not applied,
+so those responses carry neither `delivered` nor `delivery`.
```jsonc
"delivered": {
@@ -101,16 +153,24 @@ gains `delivered`:
"truncated": false, // true when the unit was cut (budget, 60,000-char cap, fetch radius, snippet cap)
"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
+ "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
}
```
+Under `auto`, a `not_conversation` or `conversation_over_budget` result is the
+ranked row unchanged (same `chunk_text`, including a code chunk's header line)
+with `delivered: { unit: "chunk", chunk_ids: [its chunk_id], match_spans: [the
+whole text], tokens, truncated: false, reason }`. Those rows are not grouped
+by page. `gbrain search --explain` prints each result's unit and reason
+(`evidence: page (conversation_type)`).
+
`match_spans` are **UTF-16 code-unit offsets** (JavaScript string indices) into
the returned `chunk_text`, computed after every text transformation (sanitizing,
cuts, omission lines and secret redaction). The text carries no inline markers.
A hit whose chunk cannot be located is listed in `unmapped_chunk_ids` instead.
-One result is returned per page, at the page's best rank. `chunk_id`,
+One result is returned per expanded page, at the page's best rank. `chunk_id`,
`chunk_index`, `score` and the other ranking fields stay those of the page's
best-ranked hit (anchor provenance).
@@ -147,7 +207,7 @@ delivered text and each result gains `delivered`.
| `unsealed_page` | The page's chunks predate the protected-body index (`gbrain repair safe-chunks`). | The hit chunk, `fallback_reason` set. |
| `row_limit` | The request hit the budget-derived row cap before this page's rows. | The hit chunk, `fallback_reason` set. |
| `no_section_structure` | `section` found no headings or speaker turns. | A `window` block (`delivered.unit: "window"`). |
-| `no_text_chunks` / `anchor_not_fetched` | The page has no text chunks in reach, or none of its hits' chunks were read. | The hit chunk, `fallback_reason` set. |
+| `no_text_chunks` / `anchor_not_located` | No hit could be placed in the page text: no text chunk was in reach and the hit text itself was not found, or none of the located chunks overlap a hit. | The hit chunk (a code chunk without its synthesized header line), `fallback_reason` set. |
| `page_missing` | A hit carried no page id (cannot be re-authorized by id). | The hit chunk (live hits only), `fallback_reason` set. |
| `redaction_unmapped` | Secret redaction changed a block. | Redacted block; its spans move to `unmapped_chunk_ids`. |
| `image_query_unsupported` | `query` with `image`: image hits are never expanded. | Plain image results; meta says so. |
@@ -155,7 +215,7 @@ 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. |
| 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. |
-| drop `budget_floor` | Not even the block's matching span fits the remaining budget. | Result removed (rank one is instead cut to fit). |
+| 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` nothing is dropped for budget: the conversation keeps its ranked chunks. |
## Errors
@@ -206,7 +266,12 @@ warning naming the minimum server version.
`serializeMarkdown` writes). Each fetched chunk is located in that text in
`chunk_index` order: exact match first, then a whitespace-insensitive match
(the chunker trims chunks and folds some whitespace-only runs, so chunk text
- is not always verbatim). Overlapping chunks therefore never duplicate text:
+ is not always verbatim). A fenced-code hit is placed by its code without the
+ code chunker's synthesized `[Lang] fence.ts:N-M symbol` header line (its
+ `chunk_index` follows every prose chunk, so it carries no position; its
+ window grows from the prose chunk holding the fence, when fetched). Fallback
+ text for such a hit omits the header too, so delivered text is always page
+ text. Overlapping chunks therefore never duplicate text:
`page` evidence with an unlimited budget is byte-identical to the page text
(trailing whitespace trimmed). Non-contiguous selections join with the
omission line `\n\n[…]\n\n`.
@@ -215,8 +280,10 @@ warning naming the minimum server version.
hits. Conversation pages (≥ 4 speaker-turn lines such as `**user:**` /
`**assistant:**`, `User:`, `Speaker 2:`, with ≥ 2 distinct labels and ≥ 3
label changes; page `type` is ignored) use rounds: a round starts at each
- `user`/`human` turn (or the first label seen). `auto`: conversation → `page`;
- else ≤ 3 chunks → `page`; else headings present → `section`; else `window`.
+ `user`/`human` turn (or the first label seen). `auto`: per hit, a
+ conversation page (by type or slug, see
+ [Conversation detection](#conversation-detection)) → `page`; anything else
+ → its ranked chunk, unchanged and unbudgeted by this stage beyond its cost.
5. **Pieces.** The unit text is split into lines; lines over 400 characters
split at whitespace. Token counts are the sum of per-piece cl100k counts
(plus the omission line and the title), so the count is deterministic and
@@ -277,7 +344,7 @@ import { assembleEvidenceForHits, evidenceFingerprint } from 'gbrain/search/evid
const out = await assembleEvidenceForHits(engine, {
hits: [ { source_id: 'default', slug: 'chat/session-0412', chunk_id: 8812 }, /* rank order */ ],
- return_unit: 'page', // chunk | window | section | page | auto
+ return_unit: 'page', // chunk | window | section | page | auto (the product default)
return_window: 1, // optional
budget_tokens: 6000, // optional; same default/clamp rules as query
detail: 'medium', // optional, as query
@@ -298,7 +365,7 @@ unknown chunk ids are dropped and listed in `unresolved` (by input index).
### Op `assemble_evidence` (any transport: local CLI, MCP stdio, HTTP)
Read scope. Params: `hits` (array of `{ source_id, slug, chunk_id }`, rank
-order, max 50), `return_unit` (required), `return_window`, `token_budget`,
+order, max 50), `return_unit` (default `page`; pass `auto` to measure the product default), `return_window`, `token_budget`,
`detail`. Returns `{ results, delivery, unresolved }` with the same content as
the library call for that caller. Remote callers get the same filtering as
`query` (private pages hidden, sealed pages only, grants enforced).
@@ -309,7 +376,7 @@ the library call for that caller. Remote callers get the same filtering as
`JSON.stringify(results.map(r => [r.source_id ?? 'default', r.slug, r.chunk_text, r.delivered?.unit ?? 'chunk', r.delivered?.chunk_ids ?? [r.chunk_id]]))`.
It is identical for the `query` op's results and for `assemble_evidence` /
`assembleEvidenceForHits` given the same ordered hits, unit, window, budget and
-caller class, on both engines. `test/evidence-delivery-parity.test.ts` pins
+caller class, on both engines. `test/e2e/evidence-delivery-parity.test.ts` pins
this.
### Parity recipe for E3
@@ -323,6 +390,11 @@ this.
3. Fingerprints must match; any difference means the product path does not
deliver the evidence the experiment assumed.
+For the default, compare `query` with `return_unit` **omitted** (and no
+`token_budget`, which would keep the legacy chunk budget) against
+`assemble_evidence` with `return_unit: "auto"`. When no hit is a conversation
+the default returns plain rows; their fingerprint equals the `auto` one.
+
Always pass `expand: false` to `query` for E3. `query` otherwise runs LLM
multi-query expansion by default, which can change the ranked list from run to
run (retrieval drift, not a delivery difference). `assemble_evidence` does no
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 086db67640..22a8280eba 100644
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@ -1,7 +1,7 @@
{
"id": "gbrain-context-engine",
"name": "gbrain",
- "version": "0.60.22.0",
+ "version": "0.60.23.0",
"description": "Personal knowledge brain with Postgres + pgvector hybrid search",
"family": "bundle-plugin",
"kind": "context-engine",
diff --git a/package.json b/package.json
index 86bd2ff0d1..ec7afc209a 100644
--- a/package.json
+++ b/package.json
@@ -204,7 +204,7 @@
"bun": ">=1.3.11"
},
"license": "MIT",
- "version": "0.60.22.0",
+ "version": "0.60.23.0",
"overrides": {
"@ai-sdk/provider-utils": "4.0.33",
"@hono/node-server": "^2.0.5",
diff --git a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
index 2fcf10d47e..00b8b8fa70 100644
--- a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
+++ b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-coding",
- "version": "0.60.22.0",
+ "version": "0.60.23.0",
"description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
index e2c90ac3d4..52b8b9561e 100644
--- a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
+++ b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-coding",
- "version": "0.60.22.0",
+ "version": "0.60.23.0",
"description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-coding/README.md b/plugin-variants/gbrain-coding/README.md
index d641f6673e..21c283504e 100644
--- a/plugin-variants/gbrain-coding/README.md
+++ b/plugin-variants/gbrain-coding/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.60.22.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.60.23.0 -->
# gbrain-coding (generated persona variant — do not hand-edit)
Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant.
diff --git a/plugin-variants/gbrain-coding/skills/query/SKILL.md b/plugin-variants/gbrain-coding/skills/query/SKILL.md
index a9ff76f6db..a3b5422175 100644
--- a/plugin-variants/gbrain-coding/skills/query/SKILL.md
+++ b/plugin-variants/gbrain-coding/skills/query/SKILL.md
@@ -139,10 +139,13 @@ claiming activation; otherwise report adoption as unverified.
- `gbrain search` / `gbrain query` return ranked chunks with context snippets.
These are often enough to answer the question directly.
-- For multi-conversation or "when did X change" questions, where the answer
- depends on the surrounding conversation rather than one chunk, ask for whole
- evidence in the same call: `return_unit: "page"` (whole page or session,
- budgeted by `token_budget`, default 6,000) or `"window"` (neighbor chunks).
+- Hits on conversation pages (sessions, transcripts, meetings, chat logs)
+ already come back as the whole session by default (`return_unit: "auto"`,
+ 24,000-token default budget). For other multi-page or "when did X change"
+ questions, where the answer depends on the surrounding text rather than one
+ chunk, ask for whole evidence in the same call: `return_unit: "page"` (whole
+ page, budgeted by `token_budget`, default 6,000) or `"window"` (neighbor
+ chunks). `return_unit: "chunk"` opts out.
Each result then carries the evidence in `chunk_text` plus a `delivered`
block; see [evidence delivery](../../docs/evidence-delivery.md).
`gbrain query "when did the launch move?" --return-unit page --token-budget 6000`
diff --git a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
index 3c9cc0a6bd..dfc1a39128 100644
--- a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
+++ b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-daily",
- "version": "0.60.22.0",
+ "version": "0.60.23.0",
"description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
index 82d2cac050..1ab582b091 100644
--- a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
+++ b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-daily",
- "version": "0.60.22.0",
+ "version": "0.60.23.0",
"description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-daily/README.md b/plugin-variants/gbrain-daily/README.md
index 6e1599047f..2b71d69c51 100644
--- a/plugin-variants/gbrain-daily/README.md
+++ b/plugin-variants/gbrain-daily/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.60.22.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.60.23.0 -->
# gbrain-daily (generated persona variant — do not hand-edit)
Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant.
diff --git a/plugin-variants/gbrain-daily/skills/query/SKILL.md b/plugin-variants/gbrain-daily/skills/query/SKILL.md
index a9ff76f6db..a3b5422175 100644
--- a/plugin-variants/gbrain-daily/skills/query/SKILL.md
+++ b/plugin-variants/gbrain-daily/skills/query/SKILL.md
@@ -139,10 +139,13 @@ claiming activation; otherwise report adoption as unverified.
- `gbrain search` / `gbrain query` return ranked chunks with context snippets.
These are often enough to answer the question directly.
-- For multi-conversation or "when did X change" questions, where the answer
- depends on the surrounding conversation rather than one chunk, ask for whole
- evidence in the same call: `return_unit: "page"` (whole page or session,
- budgeted by `token_budget`, default 6,000) or `"window"` (neighbor chunks).
+- Hits on conversation pages (sessions, transcripts, meetings, chat logs)
+ already come back as the whole session by default (`return_unit: "auto"`,
+ 24,000-token default budget). For other multi-page or "when did X change"
+ questions, where the answer depends on the surrounding text rather than one
+ chunk, ask for whole evidence in the same call: `return_unit: "page"` (whole
+ page, budgeted by `token_budget`, default 6,000) or `"window"` (neighbor
+ chunks). `return_unit: "chunk"` opts out.
Each result then carries the evidence in `chunk_text` plus a `delivered`
block; see [evidence delivery](../../docs/evidence-delivery.md).
`gbrain query "when did the launch move?" --return-unit page --token-budget 6000`
diff --git a/plugin/README.md b/plugin/README.md
index 31365dfeb2..b0c7730bcb 100644
--- a/plugin/README.md
+++ b/plugin/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.60.22.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.60.23.0 -->
# gbrain plugin skill tree (generated — do not hand-edit)
This tree is the curated skill set for the gbrain Codex and Claude Code
diff --git a/plugin/skills/query/SKILL.md b/plugin/skills/query/SKILL.md
index a9ff76f6db..a3b5422175 100644
--- a/plugin/skills/query/SKILL.md
+++ b/plugin/skills/query/SKILL.md
@@ -139,10 +139,13 @@ claiming activation; otherwise report adoption as unverified.
- `gbrain search` / `gbrain query` return ranked chunks with context snippets.
These are often enough to answer the question directly.
-- For multi-conversation or "when did X change" questions, where the answer
- depends on the surrounding conversation rather than one chunk, ask for whole
- evidence in the same call: `return_unit: "page"` (whole page or session,
- budgeted by `token_budget`, default 6,000) or `"window"` (neighbor chunks).
+- Hits on conversation pages (sessions, transcripts, meetings, chat logs)
+ already come back as the whole session by default (`return_unit: "auto"`,
+ 24,000-token default budget). For other multi-page or "when did X change"
+ questions, where the answer depends on the surrounding text rather than one
+ chunk, ask for whole evidence in the same call: `return_unit: "page"` (whole
+ page, budgeted by `token_budget`, default 6,000) or `"window"` (neighbor
+ chunks). `return_unit: "chunk"` opts out.
Each result then carries the evidence in `chunk_text` plus a `delivered`
block; see [evidence delivery](../../docs/evidence-delivery.md).
`gbrain query "when did the launch move?" --return-unit page --token-budget 6000`
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 9fcd155f99..ee1a402795 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -36,7 +36,7 @@ src/core/embedding-migration.ts 1525 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 1903 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
src/core/chunkers/code.ts 1582 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
-src/core/config.ts 1804 ratchet 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
+src/core/config.ts 1805 ratchet 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)
src/core/bootstrap/harness.ts 2674 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)
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 618 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)
diff --git a/skills/query/SKILL.md b/skills/query/SKILL.md
index a9ff76f6db..a3b5422175 100644
--- a/skills/query/SKILL.md
+++ b/skills/query/SKILL.md
@@ -139,10 +139,13 @@ claiming activation; otherwise report adoption as unverified.
- `gbrain search` / `gbrain query` return ranked chunks with context snippets.
These are often enough to answer the question directly.
-- For multi-conversation or "when did X change" questions, where the answer
- depends on the surrounding conversation rather than one chunk, ask for whole
- evidence in the same call: `return_unit: "page"` (whole page or session,
- budgeted by `token_budget`, default 6,000) or `"window"` (neighbor chunks).
+- Hits on conversation pages (sessions, transcripts, meetings, chat logs)
+ already come back as the whole session by default (`return_unit: "auto"`,
+ 24,000-token default budget). For other multi-page or "when did X change"
+ questions, where the answer depends on the surrounding text rather than one
+ chunk, ask for whole evidence in the same call: `return_unit: "page"` (whole
+ page, budgeted by `token_budget`, default 6,000) or `"window"` (neighbor
+ chunks). `return_unit: "chunk"` opts out.
Each result then carries the evidence in `chunk_text` plus a `delivered`
block; see [evidence delivery](../../docs/evidence-delivery.md).
`gbrain query "when did the launch move?" --return-unit page --token-budget 6000`
diff --git a/skills/skills.lock.json b/skills/skills.lock.json
index 25b4e18c58..eb5249fb0d 100644
--- a/skills/skills.lock.json
+++ b/skills/skills.lock.json
@@ -169,7 +169,7 @@
"postgres-adopt/SKILL.md": "4c402527bd0d98aa4e7f1a341a25ac0d1bba5e98b3dd55bcc5e30ed2858fa0e0",
"postgres-adopt/routing-eval.jsonl": "db91c1fae408a45082979c402c11eff413277ace6cf746297cc86009dcaefe06",
"publish/SKILL.md": "e06b609db780a3cc93a1755a87b30ff08ffdc0fdbc834c1422b2ad2489b57497",
- "query/SKILL.md": "7c2eea23d789eeac82afe37ab85557cd92f7be3a409e8cceadc8ce03f448f73d",
+ "query/SKILL.md": "c754d882e7c851d02a221075eda6868987f3a52509eab4c84211dd5472b86da7",
"query/routing-eval.jsonl": "74f5a91e52fabc54e0e9403fa17db87ee26bb7ebb8ae8005148c51142abc62fe",
"remote-mcp/SKILL.md": "3021054e2b21fa589310181d5140bc6caae5a4d75e3f3aa2cdbddac272cd4873",
"remote-mcp/routing-eval.jsonl": "7287693135c9fe2d6495d81d22746ddf41b116254db4b6e683dbdee251e08f8e",
diff --git a/src/core/config.ts b/src/core/config.ts
index 4aff5ccfbd..6ca4fc9264 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1343,11 +1343,12 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
'search.metadata_boost_gate',
'search.crag_escalation',
'search.crag_think',
- // Evidence delivery (search/evidence-delivery.ts): default unit (chunk),
- // window radius, default/remote-max token budgets; think reads its own unit.
+ // Evidence delivery (search/evidence-delivery.ts): default unit (auto),
+ // window radius, default/auto/remote-max token budgets; think reads its own unit.
'search.return_unit',
'search.return_window',
'search.return_budget_default',
+ 'search.return_budget_conversation',
'search.return_budget_max_remote',
'think.return_unit',
// Models tier system (v0.31.12)
diff --git a/src/core/operations-descriptions.ts b/src/core/operations-descriptions.ts
index b8b6eb0033..1ec46b7cb1 100644
--- a/src/core/operations-descriptions.ts
+++ b/src/core/operations-descriptions.ts
@@ -76,7 +76,8 @@ export const QUERY_DESCRIPTION =
"description); pass `limit` explicitly for a stable count regardless of " +
"mode. When the answer needs the surrounding conversation or section, pass " +
"`return_unit` ('page' / 'section' / 'window') to get that evidence in one call " +
- "instead of get_page per hit. For exhaustive enumeration use list_pages; for exact known tokens " +
+ "instead of get_page per hit; conversation pages already come back whole by default (return_unit " +
+ "'auto'; 'chunk' opts out). For exhaustive enumeration use list_pages; for exact known tokens " +
"`search` is cheaper (no expansion LLM call). " +
"For personal/emotional questions ('what's going on with me', 'anything notable', " +
"'how am I feeling'), prefer get_recent_salience, find_anomalies, or " +
@@ -90,7 +91,8 @@ export const SEARCH_DESCRIPTION =
"result set is NOT proof of coverage — for concept / synonym / landscape " +
"questions use `query` (adds multi-query expansion); for exhaustive " +
"enumeration use list_pages pagination. " +
- "Pass `return_unit` ('window' / 'section' / 'page') for whole evidence instead of chunks. " +
+ "Pass `return_unit` ('window' / 'section' / 'page') for whole evidence instead of chunks; " +
+ "conversation pages already come back whole by default (return_unit 'auto'; 'chunk' opts out). " +
"For personal/emotional questions, " +
"prefer get_recent_salience or find_anomalies — they surface activity bursts " +
"without needing a search term. " +
diff --git a/src/core/ops/facts.ts b/src/core/ops/facts.ts
index b7cae99549..c933e51493 100644
--- a/src/core/ops/facts.ts
+++ b/src/core/ops/facts.ts
@@ -1,5 +1,5 @@
import { WRITE_REQUEST_PARAM } from '../persistence/params.ts';
-import { deliverEvidence, resolveEvidencePlan, type DeliveryMeta, type EvidencePlan } from '../search/evidence-delivery.ts';
+import { deliverEvidence, effectivePlan, resolveEvidencePlan, type DeliveryMeta, type EvidencePlan } from '../search/evidence-delivery.ts';
import { randomUUID } from 'node:crypto';
import { readHolders } from './context.ts';
/**
@@ -183,9 +183,15 @@ function packingArm<T>(candidates: T[], kept: T[], cost: (item: T) => number) {
return { candidates: candidates.length, kept: kept.length, dropped: candidates.length - kept.length, used: kept.reduce((sum, r) => sum + cost(r), 0) };
}
-/** recall's evidence plan: budget_tokens budgets the delivered blocks before recall's own packing. */
+/**
+ * recall's evidence plan: budget_tokens budgets the delivered blocks before
+ * recall's own packing. Without return_unit, budget_tokens or budget_policy
+ * keeps legacy chunk packing (facts pack first, so a whole session would
+ * otherwise lose to them).
+ */
function recallEvidencePlan(ctx: OperationContext, p: Record<string, unknown>): Promise<EvidencePlan | null> {
return resolveEvidencePlan(ctx.engine, {
+ legacyBudget: p.budget_policy !== undefined || (typeof p.budget_tokens === 'number' && Number.isFinite(p.budget_tokens) && p.budget_tokens > 0),
remote: ctx.remote, viaSubagent: ctx.viaSubagent, returnUnit: p.return_unit, returnWindow: p.return_window,
budget: p.budget_tokens, snippetChars: undefined, snippetCap: 0, op: 'recall',
});
@@ -208,7 +214,7 @@ const recall: Operation = {
limit: { type: 'number', description: 'Per-arm cap: max fact rows AND max search results. Default 50, cap 100.' },
grep: { type: 'string', description: 'Substring filter on fact text (case-insensitive). Applied in SQL before the limit, so matches on high-cardinality entities are found even outside the newest-N window.' },
include_pending: { type: 'boolean', description: 'v0.32: when true, response includes pending_consolidation_count (facts not yet promoted to takes by the dream-cycle consolidate phase). One round trip; backward-compatible (field omitted when false).' },
- return_unit: { type: 'string', enum: ['chunk', 'window', 'section', 'page', 'auto'], description: "Evidence unit for the results[] arm (needs `query`; default config search.return_unit = 'chunk'). 'window' adds neighbor chunks, 'section' the enclosing section or conversation rounds, 'page' the whole page/session (best for multi-session questions), 'auto' picks per page. Non-chunk units return one result per page with `delivered` metadata and a top-level `delivery` block; the evidence is budgeted by budget_tokens (default 6000) and then packed by recall's usual rules." },
+ return_unit: { type: 'string', enum: ['chunk', 'window', 'section', 'page', 'auto'], description: "Evidence unit for the results[] arm (needs `query`; default config search.return_unit = 'auto'). 'window' adds neighbor chunks, 'section' the enclosing section or conversation rounds, 'page' the whole page/session (best for multi-session questions), 'auto' the whole page for conversation pages and the ranked chunk unchanged for everything else (budget_tokens or budget_policy without return_unit keeps chunk packing). Non-chunk units return one result per page with `delivered` metadata and a top-level `delivery` block; the evidence is budgeted by budget_tokens (default 6000, auto 24000) and then packed by recall's usual rules." },
return_window: { type: 'number', description: "Neighbor chunks on each side for return_unit 'window' (integer 1-3, default 1)." },
},
scope: 'read',
@@ -447,7 +453,8 @@ const recall: Operation = {
});
}
bumpLastRetrievedAt(ctx.engine, searchResults.map(r => r.page_id));
- if (evidencePlan) ({ results: searchResults, delivery } = await deliverEvidence(ctx.engine, searchResults, evidencePlan, { ...searchScope, excludePrivate, requireSafeChunks: ctx.remote !== false }));
+ const applied = effectivePlan(evidencePlan, searchResults);
+ if (applied) ({ results: searchResults, delivery } = await deliverEvidence(ctx.engine, searchResults, applied, { ...searchScope, excludePrivate, requireSafeChunks: ctx.remote !== false }));
}
let packedFacts = rows;
diff --git a/src/core/ops/search.ts b/src/core/ops/search.ts
index 3fd5d0cc07..8ba6a6b2f5 100644
--- a/src/core/ops/search.ts
+++ b/src/core/ops/search.ts
@@ -25,7 +25,7 @@ import type { HybridSearchMeta, SearchResult } from '../types.ts';
import { bumpLastRetrievedAt } from '../last-retrieved.ts';
import { applySnippetCap, DEFAULT_AGENT_SNIPPET_CHARS } from '../search/snippet-cap.ts';
import { redactRetrievalOutput } from '../search/output-redaction.ts';
-import { assembleEvidenceForHits, capDeliveredSnippets, deliverEvidence, resolveEvidencePlan, unsupportedDelivery, type DeliveryMeta, type DeliveryScope, type EvidencePlan, type FrozenHit, type ReturnUnit } from '../search/evidence-delivery.ts';
+import { assembleEvidenceForHits, capDeliveredSnippets, deliverEvidence, effectivePlan, resolveEvidencePlan, unsupportedDelivery, type DeliveryMeta, type DeliveryScope, type EvidencePlan, type FrozenHit, type ReturnUnit } from '../search/evidence-delivery.ts';
import { resolveExcludePrivatePages } from '../search/private-visibility.ts';
import { SAFE_FENCE_CHUNKER_VERSION } from '../search/safe-chunks.ts';
import { expandEngineTypeFilters } from '../schema-pack/query-types.ts';
@@ -87,22 +87,27 @@ const RETURN_UNIT_PARAM = {
type: 'string' as const,
enum: ['chunk', 'window', 'section', 'page', 'auto'],
description:
- "Evidence unit returned in each result's chunk_text (default: config search.return_unit, which defaults to 'chunk').\n" +
+ "Evidence unit returned in each result's chunk_text (default: config search.return_unit, which defaults to 'auto').\n" +
" 'chunk' — the ranked chunk only (~300-450 tokens per result).\n" +
" 'window' — the hit chunk plus return_window neighbor chunks each side (local context, ~3x chunk).\n" +
" 'section' — the enclosing markdown section, or the conversation rounds around the hit.\n" +
" 'page' — the whole page/session, capped. Use for multi-session or temporal questions where the answer needs the whole conversation.\n" +
- " 'auto' — page for conversations and short pages, section or window for long curated pages.\n" +
- 'Non-chunk units return one result per page, packed into token_budget (default 6000; remote max 32000), with a `delivered` object (unit, chunk_ids, match_spans, tokens, truncated) per result and `delivery` in the response meta.',
+ " '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.\n" +
+ '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.',
};
const RETURN_WINDOW_PARAM = {
type: 'number' as const,
description: "Neighbor chunks on each side for return_unit 'window' (integer 1-3, default 1).",
};
-/** With a plan, `token_budget` budgets the delivered evidence, so query's chunk-level budget stays off. */
-async function evidencePlanFor(ctx: OperationContext, p: Record<string, unknown>, snippetCap: number, op: string): Promise<EvidencePlan | null> {
+/**
+ * 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.
+ */
+async function evidencePlanFor(ctx: OperationContext, p: Record<string, unknown>, snippetCap: number, op: 'search' | 'query'): Promise<EvidencePlan | null> {
return resolveEvidencePlan(ctx.engine, {
+ legacyBudget: op === 'query' && typeof p.token_budget === 'number',
remote: ctx.remote,
viaSubagent: ctx.viaSubagent,
returnUnit: p.return_unit,
@@ -121,8 +126,9 @@ 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 } }> {
- if (!plan) return { rows: results };
- const d = await deliverEvidence(ctx.engine, results, plan, { ...scope, requireSafeChunks: ctx.remote !== false }, { liveHits: meta?.cache?.status !== 'hit' });
+ const applied = effectivePlan(plan, results);
+ if (!applied) return { rows: results };
+ const d = await deliverEvidence(ctx.engine, results, applied, { ...scope, requireSafeChunks: ctx.remote !== false }, { liveHits: meta?.cache?.status !== 'hit' });
return { rows: d.results, evidence: { delivery: d.delivery, explicitSnippet: typeof p.snippet_chars === 'number' && Number.isFinite(p.snippet_chars) } };
}
@@ -317,7 +323,7 @@ const search: Operation = {
snippet_chars: { type: 'number', description: SNIPPET_CHARS_PARAM_DESCRIPTION },
return_unit: RETURN_UNIT_PARAM,
return_window: RETURN_WINDOW_PARAM,
- token_budget: { type: 'number', description: "Token budget for delivered evidence when return_unit is not 'chunk' (default search.return_budget_default = 6000). Ignored in chunk mode." },
+ token_budget: { type: 'number', description: "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." },
// #4415: explicit ranking-axis overrides (the same knobs `query` has had
// since v0.29.1). The auto-detect banks are English regex, so on a
// non-English brain the recency/salience stages never fire — these flags
@@ -468,7 +474,7 @@ const query: Operation = {
snippet_chars: { type: 'number', description: SNIPPET_CHARS_PARAM_DESCRIPTION },
return_unit: RETURN_UNIT_PARAM,
return_window: RETURN_WINDOW_PARAM,
- token_budget: { type: 'number', description: "Token budget. Chunk mode: caps the cumulative chunk payload (results that would overflow are skipped). Non-chunk return_unit: the budget for delivered evidence (default search.return_budget_default = 6000; remote max search.return_budget_max_remote = 32000)." },
+ token_budget: { type: 'number', description: "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)." },
expand: { type: 'boolean', description: 'Request multi-query expansion (default: true in every search mode, regardless of search.expansion). Set false to opt out. Requires configured embedding and expansion providers; a cloud expander receives the query and may charge for the call. Response metadata expansion_applied reports whether variants were actually used.' },
detail: { type: 'string', description: 'Result detail level: low (compiled truth only), medium (default, all with dedup), high (all chunks)' },
mode: { type: 'string', description: 'Search mode (conservative|balanced|tokenmax). Local callers only; remote uses configured mode.' },
@@ -631,7 +637,7 @@ const query: Operation = {
})).map(r => ({ ...r }));
stampDeepResearchIds(results);
imageMeta.retrieved_count = results.length;
- return searchOutput(ctx, results, { ...await buildRetrievalResponseMeta(ctx, querySourceScope, queryText ?? '', results, imageMeta, { types }), ...(plan ? { delivery: unsupportedDelivery(plan, 'image_query_unsupported') } : {}) }, snippetCap);
+ return searchOutput(ctx, results, { ...await buildRetrievalResponseMeta(ctx, querySourceScope, queryText ?? '', results, imageMeta, { types }), ...(plan && (plan.unit !== 'auto' || plan.explicitUnit) ? { delivery: unsupportedDelivery(plan, 'image_query_unsupported') } : {}) }, snippetCap);
}
if (!queryText) {
@@ -902,7 +908,7 @@ const assemble_evidence: Operation = {
hits: { type: 'array', required: true, items: { type: 'object' }, description: 'Ordered hits, best first (max 50): [{ "source_id": "default", "slug": "chat/session-0412", "chunk_id": 8812 }]. chunk_id 0 addresses the page\'s first chunk.' },
return_unit: { ...RETURN_UNIT_PARAM, description: "Evidence unit: 'chunk' | 'window' | 'section' | 'page' | 'auto' (default 'page')." },
return_window: RETURN_WINDOW_PARAM,
- token_budget: { type: 'number', description: 'Token budget for the delivered evidence (default search.return_budget_default = 6000; remote max 32000).' },
+ token_budget: { type: 'number', description: 'Token budget for the delivered evidence (default search.return_budget_default = 6000, auto search.return_budget_conversation = 24000; remote max 32000).' },
detail: { type: 'string', enum: ['low', 'medium', 'high'], description: "As query: 'low' delivers compiled truth only (no timeline text)." },
},
scope: 'read',
diff --git a/src/core/search/evidence-delivery.ts b/src/core/search/evidence-delivery.ts
index d7e0d7b2ef..4fbdfebe41 100644
--- a/src/core/search/evidence-delivery.ts
+++ b/src/core/search/evidence-delivery.ts
@@ -31,6 +31,7 @@ import { currentTextProjectionFilter, safeChunksFilter, requiresSafeChunks } fro
import { resolveExcludePrivatePages } from './private-visibility.ts';
import { safeSplitIndex } from '../text-safe.ts';
import { sanitizeRemoteBody } from '../remote-body.ts';
+import { stripChunkHeader } from '../chunkers/code.ts';
import { OperationError } from '../ops/contract.ts';
export const RETURN_UNITS = ['chunk', 'window', 'section', 'page', 'auto'] as const;
@@ -42,7 +43,10 @@ export const THINK_RETURN_UNIT_CONFIG_KEY = 'think.return_unit';
export const RETURN_WINDOW_CONFIG_KEY = 'search.return_window';
export const RETURN_BUDGET_DEFAULT_KEY = 'search.return_budget_default';
export const RETURN_BUDGET_MAX_REMOTE_KEY = 'search.return_budget_max_remote';
+export const RETURN_BUDGET_CONVERSATION_KEY = 'search.return_budget_conversation';
export const DEFAULT_RETURN_BUDGET = 6000;
+/** `auto`'s default budget: whole chat sessions run about 15K tokens, and 16K still trimmed some sessions. */
+export const DEFAULT_CONVERSATION_BUDGET = 24000;
export const DEFAULT_REMOTE_BUDGET_MAX = 32000;
export const EVIDENCE_BLOCK_CHAR_CAP = 60_000;
export const EVIDENCE_OMISSION = '\n\n[…]\n\n';
@@ -50,13 +54,20 @@ export const EVIDENCE_FETCH_TIMEOUT_MS = 5000;
/** First server release that understands `return_unit` (thin-client skew warning). */
export const EVIDENCE_DELIVERY_MIN_SERVER_VERSION = '0.60.13.0';
-const AUTO_SHORT_PAGE_CHUNKS = 3;
const PIECE_MAX_CHARS = 400;
const MAX_ROWS = 1024;
const MAX_WINDOW = 3;
export interface MatchSpan { chunk_id: number; start: number; end: number }
+/**
+ * Why `auto` chose a result's unit: a conversation page (by type or slug
+ * prefix) gets the whole page; anything else keeps its ranked chunk exactly;
+ * 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';
+
export interface DeliveredEvidence {
unit: DeliveredUnit;
chunk_ids: number[];
@@ -66,6 +77,8 @@ export interface DeliveredEvidence {
revision?: string;
unmapped_chunk_ids?: number[];
fallback_reason?: string;
+ /** Present only under `auto`: why this result got its unit. */
+ reason?: AutoReason;
}
export interface DeliveryMeta {
@@ -155,26 +168,35 @@ export interface ResolvePlanInput {
snippetCap: number;
configKey?: string;
op: string;
+ /**
+ * The caller passed a chunk-mode budget knob (query's token_budget, recall's
+ * budget_policy): an implied unit stays `chunk` so that legacy budgeting
+ * keeps its meaning.
+ */
+ legacyBudget?: boolean;
}
/**
* Resolve the per-call evidence plan, or null when the resolved unit is
- * `chunk` (the stage stays inert and the response is unchanged). Throws
+ * `chunk` (the stage stays inert and the response is unchanged). The unit is
+ * the call's `return_unit`, else the config unit, else `auto`. Throws
* invalid_params for a bad `return_unit` / `return_window`.
*/
export async function resolveEvidencePlan(engine: BrainEngine, input: ResolvePlanInput): Promise<EvidencePlan | null> {
const explicit = parseReturnUnit(input.returnUnit, input.op);
const explicitWindow = parseReturnWindow(input.returnWindow, input.op);
- let unit: ReturnUnit = explicit ?? 'chunk';
+ let unit: ReturnUnit = explicit ?? 'auto';
if (explicit === undefined) {
try {
const raw = await engine.getConfig(input.configKey ?? RETURN_UNIT_CONFIG_KEY);
if (typeof raw === 'string' && (RETURN_UNITS as readonly string[]).includes(raw)) unit = raw as ReturnUnit;
- } catch { /* config unreadable: stay on chunk */ }
- // Snippet precedence: a config-level unit never overrides an explicit
- // snippet cap or the subagent default token economy.
+ } catch { /* config unreadable: stay on the default */ }
+ // Snippet precedence: an implied or config-level unit never overrides an
+ // explicit snippet cap, the subagent default token economy, or a legacy
+ // chunk-mode budget knob.
const explicitSnippet = typeof input.snippetChars === 'number' && Number.isFinite(input.snippetChars);
if (unit !== 'chunk' && !explicitSnippet && input.viaSubagent === true && input.snippetCap > 0) unit = 'chunk';
+ if (input.legacyBudget === true) unit = 'chunk';
}
if (unit === 'chunk') return null;
let window = explicitWindow ?? 1;
@@ -182,10 +204,11 @@ export async function resolveEvidencePlan(engine: BrainEngine, input: ResolvePla
const w = await configNumber(engine, RETURN_WINDOW_CONFIG_KEY);
if (w !== null) window = Math.min(MAX_WINDOW, Math.max(1, Math.floor(w)));
}
+ const fallbackBudget = unit === 'auto' ? DEFAULT_CONVERSATION_BUDGET : DEFAULT_RETURN_BUDGET;
let budget = typeof input.budget === 'number' && Number.isFinite(input.budget) && input.budget > 0
? Math.floor(input.budget)
- : Math.floor((await configNumber(engine, RETURN_BUDGET_DEFAULT_KEY)) ?? DEFAULT_RETURN_BUDGET);
- if (budget <= 0) budget = DEFAULT_RETURN_BUDGET;
+ : Math.floor((await configNumber(engine, unit === 'auto' ? RETURN_BUDGET_CONVERSATION_KEY : RETURN_BUDGET_DEFAULT_KEY)) ?? fallbackBudget);
+ if (budget <= 0) budget = fallbackBudget;
let budgetClamped: EvidencePlan['budgetClamped'];
if (input.remote !== false) {
const cfgMax = await configNumber(engine, RETURN_BUDGET_MAX_REMOTE_KEY);
@@ -205,6 +228,43 @@ export async function resolveEvidencePlan(engine: BrainEngine, input: ResolvePla
};
}
+// ---------------------------------------------------------------------------
+// auto: conversation detection
+// ---------------------------------------------------------------------------
+
+/**
+ * Page types that hold conversations: imported sessions (`conversation`, what
+ * the transcripts and chat-connector ingest paths write), `transcript` and
+ * `chat` pages, meetings, and the Slack / iMessage chat-log types the
+ * conversation-facts pipeline reads (including the collector's granular
+ * Slack types before type consolidation).
+ */
+const CONVERSATION_PAGE_TYPES: ReadonlySet<string> = new Set([
+ 'conversation', 'transcript', 'chat', 'meeting',
+ 'slack', 'slack-dm-day', 'slack-thread', 'imessage', 'imessage-daily',
+]);
+
+/** `chat/` (LongMemEval and chat imports) and `conversations/` (transcripts + connectors ingest). */
+const CONVERSATION_SLUG_PREFIXES: readonly string[] = ['chat/', 'conversations/'];
+
+/** Deterministic, row-local conversation signal for `auto` (no query, no model). */
+export function conversationSignal(hit: { type?: string | null; slug: string }): 'conversation_type' | 'conversation_slug' | null {
+ if (typeof hit.type === 'string' && CONVERSATION_PAGE_TYPES.has(hit.type.toLowerCase())) return 'conversation_type';
+ if (CONVERSATION_SLUG_PREFIXES.some(prefix => hit.slug.startsWith(prefix))) return 'conversation_slug';
+ return null;
+}
+
+/**
+ * The plan to run for these hits: an implied or config-level `auto` with no
+ * conversation hit is the chunk path (null), so responses without
+ * conversations stay byte-identical. An explicit `auto` always runs and
+ * reports its per-result decision.
+ */
+export function effectivePlan(plan: EvidencePlan | null, hits: SearchResult[]): EvidencePlan | null {
+ if (!plan || plan.unit !== 'auto' || plan.explicitUnit) return plan;
+ return hits.some(h => conversationSignal(h) !== null) ? plan : null;
+}
+
// ---------------------------------------------------------------------------
// Tokens
// ---------------------------------------------------------------------------
@@ -421,10 +481,25 @@ interface Block {
selected: Set<number>;
cut: boolean;
title: string;
+ /** Index of the block's best hit in the ranked input. */
+ rank: number;
+ reason?: AutoReason;
}
-function fallbackBlock(hit: SearchResult, hits: SearchResult[], reason: string): Omit<Block, 'titleTok' | 'title'> {
+type PlannedBlock = Omit<Block, 'titleTok' | 'title' | 'rank' | 'reason'>;
+
+/**
+ * The hit's text as it appears in the page: a fenced_code chunk carries the
+ * code chunker's synthesized `[Lang] fence.ts:N-M symbol` header, which is
+ * not page text, so it is stripped before the chunk anchors or is delivered.
+ */
+function hitPageText(hit: SearchResult): string {
const text = hit.chunk_text ?? '';
+ return hit.chunk_source === 'fenced_code' ? stripChunkHeader(text) : text;
+}
+
+function fallbackBlock(hit: SearchResult, hits: SearchResult[], reason: string): PlannedBlock {
+ const text = hitPageText(hit);
const doc = buildDoc(text, []);
const all = doc.pieces.map((_, i) => i);
return {
@@ -454,10 +529,17 @@ export function pageEvidenceText(page: { compiled_truth: string; timeline: strin
function locateAnchor(doc: Doc, hit: SearchResult): Anchor {
const byId = hit.chunk_id > 0 ? doc.spans.find(x => x.id === hit.chunk_id) : undefined;
if (byId) return { chunk_id: hit.chunk_id, mapped: true, pieces: piecesOverlapping(doc, byId.start, byId.end), start: byId.start, end: byId.end, chunkIndex: byId.chunk_index };
- const text = (hit.chunk_text ?? '').trim();
+ const text = hitPageText(hit).trim();
if (text.length >= 16) {
const found = locateChunks(doc.text, [{ id: hit.chunk_id, chunk_index: hit.chunk_index, chunk_text: text }])[0];
- if (found) return { chunk_id: hit.chunk_id, mapped: true, pieces: piecesOverlapping(doc, found.start, found.end), start: found.start, end: found.end, chunkIndex: hit.chunk_index };
+ if (found) {
+ // A fenced_code chunk_index follows every prose chunk, so it says nothing
+ // about position: the window grows from the prose chunk holding the fence,
+ // or not at all when none was fetched.
+ const chunkIndex = hit.chunk_source !== 'fenced_code' ? hit.chunk_index
+ : doc.spans.find(sp => sp.start <= found.start && found.end <= sp.end)?.chunk_index ?? Number.NEGATIVE_INFINITY;
+ return { chunk_id: hit.chunk_id, mapped: true, pieces: piecesOverlapping(doc, found.start, found.end), start: found.start, end: found.end, chunkIndex };
+ }
}
// Positional anchor (the current revision no longer holds the hit chunk, or
// a synthetic chunk_id 0 row): the nearest located chunk drives the unit
@@ -507,10 +589,10 @@ 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): Omit<Block, 'titleTok' | 'title'> {
+function planBlock(page: ChunkWindowPage, hits: SearchResult[], plan: EvidencePlan, includeTimeline: boolean): PlannedBlock {
const best = hits[0];
if (!page.sealed) return fallbackBlock(best, hits, 'unsealed_page');
- if (page.chunks.length === 0) return fallbackBlock(best, hits, page.row_limited ? 'row_limit' : 'no_text_chunks');
+ if (page.chunks.length === 0 && page.row_limited) return fallbackBlock(best, hits, 'row_limit');
const { text, timelineAt } = pageEvidenceText(page, includeTimeline);
const truthChunks = page.chunks.filter(c => c.chunk_source === 'compiled_truth');
const timelineChunks = page.chunks.filter(c => c.chunk_source === 'timeline');
@@ -520,13 +602,13 @@ function planBlock(page: ChunkWindowPage, hits: SearchResult[], plan: EvidencePl
];
const doc = buildDoc(text, spans);
const anchors = hits.map(h => locateAnchor(doc, h));
- if (anchors.every(a => a.pieces.length === 0)) return fallbackBlock(best, hits, page.row_limited ? 'row_limit' : 'anchor_not_located');
+ if (anchors.every(a => a.pieces.length === 0)) {
+ return fallbackBlock(best, hits, page.row_limited ? 'row_limit' : page.chunks.length === 0 ? 'no_text_chunks' : 'anchor_not_located');
+ }
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'
- ? (conversation || page.max_chunk_index + 1 <= AUTO_SHORT_PAGE_CHUNKS ? 'page' : hasHeadings ? 'section' : 'window')
- : plan.unit;
+ let unit: DeliveredUnit = plan.unit === 'auto' ? 'page' : plan.unit;
let fallbackReason: string | undefined;
let candidates: number[];
if (unit === 'page') {
@@ -588,7 +670,11 @@ function enrichmentOrder(b: Block): number[] {
});
}
-function allocate(blocks: Block[], budget: number, tokenizer: 'cl100k' | 'heuristic', dropped: Record<string, number>): Block[] {
+/**
+ * Reserve each block's floor in rank order, then enrich. `spill` (auto) takes
+ * a block whose floor does not fit instead of dropping or cutting it.
+ */
+function allocate(blocks: Block[], budget: number, tokenizer: 'cl100k' | 'heuristic', dropped: Record<string, number>, spill?: (b: Block) => void): Block[] {
const omitTok = pieceTokens(EVIDENCE_OMISSION, tokenizer);
let remaining = budget;
const kept: Block[] = [];
@@ -603,6 +689,7 @@ function allocate(blocks: Block[], budget: number, tokenizer: 'cl100k' | 'heuris
kept.push(b);
continue;
}
+ if (spill) { spill(b); continue; }
if (kept.length === 0 && !droppedAny) {
// Rank one alone exceeds the budget: cut it to fit (minKeep).
if (b.titleTok > remaining) {
@@ -734,15 +821,23 @@ export async function deliverEvidence(
if (plan.budgetClamped) fallbacks.add('budget_clamped');
if (tokenizer === 'heuristic') fallbacks.add('tokenizer_heuristic');
- const groups: Array<{ pageId: number | null; hits: SearchResult[] }> = [];
- const byPage = new Map<number, { pageId: number; hits: SearchResult[] }>();
- for (const h of hits) {
+ // auto keeps every non-conversation hit as its ranked chunk, unchanged;
+ // conversation hits are grouped by page like every other unit.
+ const auto = plan.unit === 'auto';
+ const passthrough: Array<{ rank: number; hit: SearchResult; reason: AutoReason }> = [];
+ type Group = { pageId: number | null; hits: SearchResult[]; rank: number; reason?: AutoReason };
+ const groups: Group[] = [];
+ const byPage = new Map<number, Group>();
+ hits.forEach((h, rank) => {
+ const signal = auto ? conversationSignal(h) : null;
+ if (auto && !signal) { passthrough.push({ rank, hit: h, reason: 'not_conversation' }); return; }
const id = Number.isFinite(h.page_id) ? h.page_id : null;
- if (id === null) { groups.push({ pageId: null, hits: [h] }); continue; }
- const g = byPage.get(id);
- if (g) g.hits.push(h);
- else { const ng = { pageId: id, hits: [h] }; byPage.set(id, ng); groups.push(ng); }
- }
+ 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 } : {}) };
+ 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.
@@ -777,7 +872,7 @@ export async function deliverEvidence(
const planned: Block[] = [];
for (const g of groups) {
- let b: Omit<Block, 'titleTok' | 'title'>;
+ let b: PlannedBlock;
if (g.pageId === null) {
b = fallbackBlock(g.hits[0], g.hits, 'page_missing');
} else if (fetchFailure) {
@@ -790,10 +885,15 @@ export async function deliverEvidence(
}
if (b.fallbackReason) fallbacks.add(b.fallbackReason);
const title = b.hit.title ?? '';
- planned.push({ ...b, title, titleTok: countEvidenceTokens(title, tokenizer) });
+ planned.push({ ...b, title, titleTok: countEvidenceTokens(title, tokenizer), rank: g.rank, ...(g.reason ? { reason: g.reason } : {}) });
}
- const kept = allocate(planned, plan.budgetTokens, tokenizer, dropped);
+ // Unchanged chunks are paid for first; conversations share the rest, and one
+ // whose matching span no longer fits keeps its ranked chunks instead.
+ const reserved = passthrough.reduce((n, p) => n + countEvidenceTokens(p.hit.chunk_text ?? '', tokenizer) + countEvidenceTokens(p.hit.title ?? '', tokenizer), 0);
+ const 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' }); }
+ : undefined);
let results: DeliveredSearchResult[] = kept.map(b => {
const out = emit(b, tokenizer);
const truncated = b.cut || b.selected.size < b.candidates.length;
@@ -806,6 +906,7 @@ export async function deliverEvidence(
...(b.revision ? { revision: b.revision } : {}),
...(out.unmapped.length > 0 ? { unmapped_chunk_ids: out.unmapped } : {}),
...(b.fallbackReason && b.unit === 'chunk' ? { fallback_reason: b.fallbackReason } : {}),
+ ...(b.reason ? { reason: b.reason } : {}),
};
return { ...b.hit, title: b.title, chunk_text: out.text, delivered };
});
@@ -837,6 +938,22 @@ export async function deliverEvidence(
};
});
+ if (passthrough.length > 0) {
+ const ranked = results.map((r, i) => ({ rank: kept[i].rank, r }));
+ for (const p of passthrough) {
+ const text = p.hit.chunk_text ?? '';
+ ranked.push({ rank: p.rank, r: { ...p.hit, delivered: {
+ unit: 'chunk',
+ chunk_ids: [p.hit.chunk_id],
+ match_spans: text.length > 0 ? [{ chunk_id: p.hit.chunk_id, start: 0, end: text.length }] : [],
+ tokens: countEvidenceTokens(text, tokenizer),
+ truncated: false,
+ reason: p.reason,
+ } } });
+ }
+ results = ranked.sort((a, b) => a.rank - b.rank).map(x => x.r);
+ }
+
const tokensDelivered = results.reduce((n, r) => n + r.delivered.tokens, 0);
const budgetUsed = tokensDelivered + results.reduce((n, r) => n + countEvidenceTokens(r.title ?? '', tokenizer), 0);
const droppedTotal = Object.values(dropped).reduce((n, v) => n + v, 0);
diff --git a/src/core/search/explain-formatter.ts b/src/core/search/explain-formatter.ts
index 4940fcb884..78e3ea1793 100644
--- a/src/core/search/explain-formatter.ts
+++ b/src/core/search/explain-formatter.ts
@@ -106,6 +106,12 @@ export function formatResultExplain(
}
lines.push(` = final ${fmt(result.score)}`);
+ // Evidence delivery: the unit this result was delivered as, and under auto why.
+ const d = result.delivered;
+ if (d) {
+ const why = [d.reason, d.fallback_reason ? `fallback ${d.fallback_reason}` : null].filter(Boolean).join(', ');
+ lines.push(` evidence: ${d.unit}${why ? ` (${why})` : ''}${d.truncated ? ', truncated' : ''}`);
+ }
return lines.join('\n');
}
diff --git a/src/core/think/gather.ts b/src/core/think/gather.ts
index 8a4c9a61a2..2845ff1f0d 100644
--- a/src/core/think/gather.ts
+++ b/src/core/think/gather.ts
@@ -606,7 +606,7 @@ export function renderPagesBlock(
pages: SearchResult[],
excerptLen = 600,
query = '',
- opts: { verbatim?: boolean } = {},
+ opts: { verbatim?: boolean | ((p: SearchResult) => boolean); verbatimLen?: number } = {},
): string {
return pages.map((p, idx) => {
const page = p as unknown as {
@@ -622,7 +622,9 @@ export function renderPagesBlock(
const content = String(page.chunk_text ?? page.compiled_truth ?? page.snippet ?? '');
// Evidence delivery: the block was already budgeted and cut around its
// hits; render it whole (capped only by excerptLen).
- if (opts.verbatim) return `<page slug="${slug}" rank="${idx + 1}">\n${content.slice(0, excerptLen)}\n</page>`;
+ if (typeof opts.verbatim === 'function' ? opts.verbatim(p) : opts.verbatim) {
+ return `<page slug="${slug}" rank="${idx + 1}">\n${content.slice(0, opts.verbatimLen ?? excerptLen)}\n</page>`;
+ }
const excerpt = selectRelevantExcerptDetailed(
content,
query,
diff --git a/src/core/think/index.ts b/src/core/think/index.ts
index 48cbd2fef6..5422fa1f33 100644
--- a/src/core/think/index.ts
+++ b/src/core/think/index.ts
@@ -33,7 +33,7 @@ import { normalizeModelId } from '../model-id.ts';
import { hasAnthropicKey } from '../ai/anthropic-key.ts';
import { parseTemporalWindow } from './temporal-window.ts';
import { resolveExcludePrivatePages } from '../search/private-visibility.ts';
-import { deliverEvidence, resolveEvidencePlan, EVIDENCE_BLOCK_CHAR_CAP, THINK_RETURN_UNIT_CONFIG_KEY, type DeliveryMeta } from '../search/evidence-delivery.ts';
+import { deliverEvidence, effectivePlan, resolveEvidencePlan, EVIDENCE_BLOCK_CHAR_CAP, THINK_RETURN_UNIT_CONFIG_KEY, type DeliveryMeta } from '../search/evidence-delivery.ts';
/** Anthropic Messages client interface — same shape used by subagent.ts so test stubs can be shared. */
export interface ThinkLLMClient {
@@ -478,21 +478,27 @@ async function persistCitations(
/**
* Render the <pages> block. Evidence delivery (think.return_unit, default
- * chunk) replaces the gathered pages with budgeted delivered blocks, which
- * the renderer passes through whole instead of cutting its own excerpts.
+ * auto) replaces the gathered pages with budgeted delivered blocks, which
+ * the renderer passes through whole instead of cutting its own excerpts;
+ * auto's unchanged chunks keep the usual excerpts.
*/
async function renderThinkPages(engine: BrainEngine, opts: RunThinkOpts, pages: SearchResult[]): Promise<{ pagesBlock: string; evidenceDelivery?: DeliveryMeta }> {
const plan = await resolveEvidencePlan(engine, {
remote: opts.remote, returnUnit: undefined, returnWindow: undefined, budget: undefined,
snippetChars: undefined, snippetCap: 0, configKey: THINK_RETURN_UNIT_CONFIG_KEY, op: 'think',
});
- if (!plan) return { pagesBlock: renderPagesBlock(pages, pagesBlockExcerptLen(pages.length), opts.question) };
- const delivered = await deliverEvidence(engine, pages, plan, {
+ const applied = effectivePlan(plan, pages);
+ if (!applied) return { pagesBlock: renderPagesBlock(pages, pagesBlockExcerptLen(pages.length), opts.question) };
+ const delivered = await deliverEvidence(engine, pages, applied, {
...(opts.allowedSources !== undefined && opts.allowedSources.length > 0 ? { sourceIds: opts.allowedSources } : opts.sourceId !== undefined ? { sourceId: opts.sourceId } : {}),
excludePrivate: opts.excludePrivate ?? await resolveExcludePrivatePages(engine, opts.remote),
requireSafeChunks: opts.remote !== false,
});
- return { pagesBlock: renderPagesBlock(delivered.results, EVIDENCE_BLOCK_CHAR_CAP, opts.question, { verbatim: true }), evidenceDelivery: delivered.delivery };
+ const pagesBlock = applied.unit === 'auto'
+ ? renderPagesBlock(delivered.results, pagesBlockExcerptLen(pages.length), opts.question,
+ { verbatim: r => r.delivered?.reason !== 'not_conversation' && r.delivered?.reason !== 'conversation_over_budget', verbatimLen: EVIDENCE_BLOCK_CHAR_CAP })
+ : renderPagesBlock(delivered.results, EVIDENCE_BLOCK_CHAR_CAP, opts.question, { verbatim: true });
+ return { pagesBlock, evidenceDelivery: delivered.delivery };
}
/**
diff --git a/src/core/types.ts b/src/core/types.ts
index a4ba0060de..b97d4ed616 100644
--- a/src/core/types.ts
+++ b/src/core/types.ts
@@ -798,7 +798,7 @@ export interface SearchResult {
title: string;
type: PageType;
chunk_text: string;
- chunk_source: 'compiled_truth' | 'timeline';
+ chunk_source: 'compiled_truth' | 'timeline' | 'fenced_code';
chunk_id: number;
chunk_index: number;
score: number;
diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.md
index 68dd48f33a..e16057ce0d 100644
--- a/templates/bootstrap/template-repo/README.md
+++ b/templates/bootstrap/template-repo/README.md
@@ -1,6 +1,6 @@
# gbrain agent workspace — template
-<!-- gbrain-template-stamp: 0.60.22.0 -->
+<!-- gbrain-template-stamp: 0.60.23.0 -->
This repository is the **"Use this template"** distribution artifact for a
[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the same
diff --git a/test/config-search-registry.test.ts b/test/config-search-registry.test.ts
index 6be3c76b9b..d513085d8a 100644
--- a/test/config-search-registry.test.ts
+++ b/test/config-search-registry.test.ts
@@ -37,6 +37,7 @@ const DIRECTLY_READ_SINGLETONS = [
'search.return_unit', // search/evidence-delivery.ts
'search.return_window',
'search.return_budget_default',
+ 'search.return_budget_conversation',
'search.return_budget_max_remote',
];
diff --git a/test/e2e/evidence-delivery-leak.test.ts b/test/e2e/evidence-delivery-leak.test.ts
index a8834f8569..dbff06fba5 100644
--- a/test/e2e/evidence-delivery-leak.test.ts
+++ b/test/e2e/evidence-delivery-leak.test.ts
@@ -10,7 +10,16 @@
* protected tail, timeline fact rows, a `visibility: private` page, a derived
* atom (private by default), and the same slug in an ungranted source. The
* mid-flight cases re-authorize stale hits: grant revocation, a page turning
- * private, and an edit between ranking and expansion.
+ * private, and an edit between ranking and expansion. A conversation page
+ * (with its own protected rows) covers the implied `auto` default, which
+ * delivers conversation pages whole.
+ *
+ * The subset invariant runs every op and unit, including the auto default,
+ * over ranked hits AND over frozen hits naming every chunk of every page, so
+ * anchor paths ranking rarely reaches (a fenced-code chunk as the best hit,
+ * whose synthesized `[Lang] fence.ts:N-M` header is not page text) are
+ * exercised. It once ran only ranked `search` page-unit hits on a corpus with
+ * no fenced code, so that header slipped through.
*
* Postgres arm runs when DATABASE_URL is set.
*/
@@ -43,13 +52,16 @@ import { withEnv } from '../helpers/with-env.ts';
const BOUND = 'evd-bound';
const FOREIGN = 'evd-foreign';
const UNITS = ['window', 'section', 'page', 'auto'] as const;
+const CODE_HEADER_LINE = /^\[[^\]]+\] fence\.\w+:\d+-\d+ /m;
// Public presence controls (must appear in page-unit evidence).
const PRESENT = ['PUBLICMARKALPHA', 'PUBLICMARKOMEGA', 'WORLDFACTKESTREL', 'TIMELINEPUBLICWREN', 'TIMELINEWORLDFINCH'];
+// Must appear when the auto default (or page) delivers the conversation whole.
+const CONVERSATION_PRESENT = ['SESSIONOPENERHERON', 'SESSIONCLOSERHERON'];
// Protected for remote callers.
const REMOTE_CANARIES = ['PRIVATEPAGECANARY', 'ATOMCANARY'];
// Protected for every caller (whole-body sanitizing) plus other-source text.
-const ALWAYS_CANARIES = ['FACTCANARYPRIVATE', 'TAKECANARYPRIVATE', 'WITHDRAWNCANARY', 'MALFORMEDTAILCANARY', 'TIMELINEFACTCANARY', 'FOREIGNSOURCECANARY', 'EDITSECRETCANARY'];
+const ALWAYS_CANARIES = ['FACTCANARYPRIVATE', 'TAKECANARYPRIVATE', 'WITHDRAWNCANARY', 'MALFORMEDTAILCANARY', 'TIMELINEFACTCANARY', 'FOREIGNSOURCECANARY', 'EDITSECRETCANARY', 'SESSIONTAKECANARY'];
const filler = (n: number) => Array.from({ length: n }, (_, i) => `Heron field notes paragraph ${i} describing ordinary public observations of the marsh and the weather that day.`).join('\n\n');
@@ -66,12 +78,22 @@ function heronPage(): string {
return `---\ntitle: heron\ntype: note\n---\n\nheron PUBLICMARKALPHA introduction.\n\n## Field notes\n\n${filler(30)}\n\n${facts}\n\n${TAKES_FENCE_BEGIN}\n| # | claim | kind | who | weight | since | source |\n|---|-------|------|-----|--------|-------|--------|\n| 1 | TAKECANARYPRIVATE heron opinion | take | owner-example | 0.8 | | |\n${TAKES_FENCE_END}\n\n## Closing\n\n${filler(8)}\n\nheron PUBLICMARKOMEGA closing line.\n\n<!-- timeline -->\n\n- 2026-01-01 heron TIMELINEPUBLICWREN sighting\n\n${timelineFacts}\n\n${TAKES_FENCE_BEGIN}\nMALFORMEDTAILCANARY heron unterminated protected tail\n`;
}
+function heronSession(): string {
+ const turns = Array.from({ length: 24 }, (_, i) =>
+ `**user:** heron question ${i} about the marsh walk ${'and the tide tables '.repeat(8)}\n\n**assistant:** heron answer ${i} ${'about the nesting season '.repeat(8)}`).join('\n\n');
+ return `---\ntitle: heron session\ntype: conversation\n---\n\n**user:** SESSIONOPENERHERON heron opening question.\n\n${turns}\n\n${TAKES_FENCE_BEGIN}\n| # | claim | kind | who | weight | since | source |\n|---|-------|------|-----|--------|-------|--------|\n| 1 | SESSIONTAKECANARY heron session opinion | take | owner-example | 0.8 | | |\n${TAKES_FENCE_END}\n\n**assistant:** SESSIONCLOSERHERON heron closing answer.\n`;
+}
+
+const codeFn = (name: string) => `export function ${name}(heron: number): number {\n${Array.from({ length: 12 }, (_, i) => ` const step${i} = heron * ${i + 2} + ${name.length};`).join('\n')}\n return heron;\n}`;
+
const FIXTURES: Array<[slug: string, source: string, body: string]> = [
['notes/heron', BOUND, heronPage()],
['notes/heron-private', BOUND, `---\ntitle: heron private\ntype: note\nvisibility: private\n---\n\nheron PRIVATEPAGECANARY private memo.\n`],
['atoms/heron-atom', BOUND, `---\ntitle: heron atom\ntype: atom\nsource_slug: notes/heron\n---\n\nheron ATOMCANARY derived atom.\n`],
['notes/heron-edit', BOUND, `---\ntitle: heron edit\ntype: note\n---\n\nheron editable page. EDITSECRETCANARY line to be removed.\n\n${filler(6)}\n`],
['notes/heron', FOREIGN, `---\ntitle: heron\ntype: note\n---\n\nheron FOREIGNSOURCECANARY other source page.\n\n${filler(4)}\n`],
+ ['conversations/sessions/heron-session', BOUND, heronSession()],
+ ['notes/heron-code', BOUND, `---\ntitle: heron code\ntype: note\n---\n\nThe heron tracker module.\n\n\`\`\`ts\n${codeFn('heronAlpha')}\n\n${codeFn('heronBeta')}\n\n${codeFn('heronGamma')}\n\`\`\`\n\nheron tracker closing note.\n`],
];
const backends = process.env.DATABASE_URL ? ['pglite', 'postgres'] as const : ['pglite'] as const;
@@ -248,19 +270,22 @@ for (const backend of backends) describe(`evidence delivery leak canaries (${bac
await mutate(async () => {
for (const remote of [false, true]) {
const canaries = remote ? [...ALWAYS_CANARIES.filter(c => c !== 'EDITSECRETCANARY'), ...REMOTE_CANARIES] : ALWAYS_CANARIES.filter(c => c !== 'EDITSECRETCANARY');
- for (const unit of UNITS) {
+ for (const unit of [...UNITS, undefined]) {
const meta: { value?: Record<string, unknown> } = {};
const search = await operations.find(o => o.name === 'search')!.handler(ctxOf(remote, meta), { query: 'heron', return_unit: unit, token_budget: 32000, source_id: BOUND, limit: 50 });
assertNoLeak(`local remote=${remote} search ${unit}`, search, canaries);
expect(meta.value?.delivery, `delivery meta for ${unit}`).toBeDefined();
if (unit === 'page') assertPresent(`local remote=${remote} search page`, search);
+ if (unit === 'page' || unit === 'auto' || unit === undefined) {
+ for (const c of CONVERSATION_PRESENT) expect(JSON.stringify(search), `${unit} remote=${remote} missing ${c}`).toContain(c);
+ }
const query = await operations.find(o => o.name === 'query')!.handler(ctxOf(remote), { query: 'heron', return_unit: unit, token_budget: 32000, source_id: BOUND, expand: false });
assertNoLeak(`local remote=${remote} query ${unit}`, query, canaries);
- const recall = await operations.find(o => o.name === 'recall')!.handler(ctxOf(remote), { query: 'heron', return_unit: unit, budget_tokens: 32000, source_id: BOUND });
+ const recall = await operations.find(o => o.name === 'recall')!.handler(ctxOf(remote), { query: 'heron', return_unit: unit, ...(unit ? { budget_tokens: 32000 } : {}), source_id: BOUND });
assertNoLeak(`local remote=${remote} recall ${unit}`, recall, canaries);
const hits = (search as SearchResult[]).map(h => ({ source_id: h.source_id, slug: h.slug, chunk_id: h.chunk_id }));
const assembled = await operations.find(o => o.name === 'assemble_evidence')!.handler(ctxOf(remote), {
- hits: [...hits, { source_id: FOREIGN, slug: 'notes/heron', chunk_id: 0 }], return_unit: unit, token_budget: 32000,
+ hits: [...hits, { source_id: FOREIGN, slug: 'notes/heron', chunk_id: 0 }], return_unit: unit ?? 'auto', token_budget: 32000,
});
assertNoLeak(`local remote=${remote} assemble ${unit}`, assembled, remote ? canaries : canaries.filter(c => c !== 'FOREIGNSOURCECANARY'));
}
@@ -272,23 +297,63 @@ for (const backend of backends) describe(`evidence delivery leak canaries (${bac
});
}, 120_000);
- test('delivered text is a subset of get_page for the same caller', async () => {
+ test('delivered text is a subset of get_page for the same caller, for every op, unit and anchor', async () => {
await mutate(async () => {
+ const allChunks = await engine.executeRaw<{ slug: string; id: number; chunk_source: string }>(
+ `SELECT p.slug, cc.id, cc.chunk_source FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.source_id = $1 ORDER BY p.slug, cc.chunk_index`, [BOUND]);
+ expect(allChunks.some(c => c.chunk_source === 'fenced_code')).toBe(true);
+ let checked = 0;
for (const remote of [false, true]) {
- const rows = await operations.find(o => o.name === 'search')!.handler(ctxOf(remote), { query: 'heron', return_unit: 'page', token_budget: 32000, source_id: BOUND, limit: 50 }) as SearchResult[];
- expect(rows.length).toBeGreaterThan(0);
- for (const row of rows) {
- const page = await operations.find(o => o.name === 'get_page')!.handler(ctxOf(remote), { slug: row.slug, source_id: row.source_id, include_content: true }) as { content: string };
- const reference = page.content;
- for (const line of row.chunk_text.split('\n')) {
- const t = line.trim();
- if (!t || t === '[…]') continue;
- expect(reference.includes(t), `${row.slug} remote=${remote}: delivered line not in get_page: ${t.slice(0, 80)}`).toBe(true);
+ const refs = new Map<string, { content: string; lines: Set<string> } | null>();
+ const reference = async (slug: string) => {
+ if (!refs.has(slug)) {
+ try {
+ const page = await operations.find(o => o.name === 'get_page')!.handler(ctxOf(remote), { slug, source_id: BOUND, include_content: true }) as { content: string };
+ refs.set(slug, { content: page.content, lines: new Set(page.content.split('\n').map(l => l.trim())) });
+ } catch { refs.set(slug, null); }
+ }
+ return refs.get(slug)!;
+ };
+ const check = async (label: string, unit: string, rows: Array<{ slug: string; chunk_text?: string; chunk?: string; delivered?: { unit: string; truncated: boolean; reason?: string; fallback_reason?: string } }>) => {
+ for (const row of rows) {
+ const text = row.chunk_text ?? row.chunk ?? '';
+ // auto's unchanged rows are the chunk response itself (raw chunk text), not delivered evidence.
+ if (!row.delivered || row.delivered.reason === 'not_conversation' || row.delivered.reason === 'conversation_over_budget') continue;
+ const ref = await reference(row.slug);
+ expect(ref, `${label}: ${row.slug} delivered but not readable via get_page`).not.toBeNull();
+ expect(text, `${label}: ${row.slug} carries a code-chunk header`).not.toMatch(CODE_HEADER_LINE);
+ if (unit === 'page') expect(row.delivered?.fallback_reason, `${label}: ${row.slug} fell back to a chunk`).toBeUndefined();
+ const whole = row.delivered?.unit === 'page' && !row.delivered.truncated;
+ for (const segment of text.split('\n\n[…]\n\n')) {
+ for (const line of segment.split('\n')) {
+ const t = line.trim();
+ if (!t) continue;
+ if (whole) expect(ref!.lines.has(t), `${label}: ${row.slug} page line is not a get_page line: ${t.slice(0, 80)}`).toBe(true);
+ else expect(ref!.content.includes(t), `${label}: ${row.slug} delivered line not in get_page: ${t.slice(0, 80)}`).toBe(true);
+ }
+ }
+ checked++;
+ }
+ };
+ for (const unit of [...UNITS, undefined]) {
+ const label = `remote=${remote} ${unit ?? 'default'}`;
+ const search = await operations.find(o => o.name === 'search')!.handler(ctxOf(remote), { query: 'heron', return_unit: unit, token_budget: 32000, source_id: BOUND, limit: 50 }) as SearchResult[];
+ await check(`${label} search`, unit ?? 'auto', search);
+ const query = await operations.find(o => o.name === 'query')!.handler(ctxOf(remote), { query: 'heron tracker', return_unit: unit, source_id: BOUND, expand: false }) as SearchResult[];
+ await check(`${label} query`, unit ?? 'auto', query);
+ const recall = await operations.find(o => o.name === 'recall')!.handler(ctxOf(remote), { query: 'heron', return_unit: unit, ...(unit ? { budget_tokens: 32000 } : {}), source_id: BOUND }) as { results: Array<{ slug: string; chunk: string }> };
+ await check(`${label} recall`, unit ?? 'auto', recall.results);
+ for (const chunk of allChunks) {
+ const assembled = await operations.find(o => o.name === 'assemble_evidence')!.handler(ctxOf(remote), {
+ hits: [{ source_id: BOUND, slug: chunk.slug, chunk_id: chunk.id }], return_unit: unit ?? 'auto', token_budget: 32000,
+ }) as { results: SearchResult[] };
+ await check(`${label} assemble ${chunk.slug}#${chunk.id} (${chunk.chunk_source})`, unit ?? 'auto', assembled.results);
}
}
}
+ expect(checked).toBeGreaterThan(100);
});
- }, 60_000);
+ }, 180_000);
test('stdio and HTTP transports deliver presence controls and no canaries', async () => {
const canaries = [...ALWAYS_CANARIES.filter(c => c !== 'EDITSECRETCANARY'), ...REMOTE_CANARIES];
@@ -357,6 +422,7 @@ for (const backend of backends) describe(`evidence delivery leak canaries (${bac
test('the fixture canaries are protected content, not absent content', () => {
expect(heronPage()).toContain(FACTS_FENCE_BEGIN);
- for (const c of [...ALWAYS_CANARIES.filter(c => !['FOREIGNSOURCECANARY', 'EDITSECRETCANARY'].includes(c))]) expect(heronPage()).toContain(c);
+ expect(heronSession()).toContain(TAKES_FENCE_BEGIN);
+ for (const c of [...ALWAYS_CANARIES.filter(c => !['FOREIGNSOURCECANARY', 'EDITSECRETCANARY'].includes(c))]) expect(heronPage() + heronSession()).toContain(c);
});
});
diff --git a/test/e2e/evidence-delivery-parity.test.ts b/test/e2e/evidence-delivery-parity.test.ts
index 1befc773b8..34ab19ef2a 100644
--- a/test/e2e/evidence-delivery-parity.test.ts
+++ b/test/e2e/evidence-delivery-parity.test.ts
@@ -1,13 +1,15 @@
/**
* Evidence delivery engine parity (PGLite vs Postgres) and product-path
* parity (plan amendment 8 / E3):
- * - the off-path golden holds on Postgres too (byte-identical to the
- * pre-feature release fixture);
+ * - the off-path golden holds on Postgres too (a config-level chunk unit is
+ * byte-identical to the pre-feature release fixture);
* - getChunkWindows returns the same windows, authorization and seal
* decisions on both engines;
* - for the same ordered hits, `query`/`search` and `assemble_evidence`
* produce the same evidence fingerprint, and both engines deliver the
- * same text for every unit.
+ * same text for every unit;
+ * - the implied `auto` default (return_unit omitted) delivers exactly what
+ * `assemble_evidence` with `auto` delivers for the same hits.
*
* Postgres arm runs when DATABASE_URL is set.
*/
@@ -59,9 +61,39 @@ afterAll(async () => {
describe('evidence delivery parity', () => {
for (const backend of backends) {
test(`off-path output is byte-identical to the pre-feature release (${backend})`, async () => {
+ const engine = engines[backend]!;
const want = JSON.parse(readFileSync(FIXTURE, 'utf8')) as Record<string, string>;
- const got = await captureOffPath(engines[backend]!);
- for (const key of Object.keys(want)) expect(`${key}: ${got[key]}`).toBe(`${key}: ${want[key]}`);
+ await engine.setConfig('search.return_unit', 'chunk');
+ await engine.setConfig('think.return_unit', 'chunk');
+ try {
+ const got = await captureOffPath(engine);
+ for (const key of Object.keys(want)) expect(`${key}: ${got[key]}`).toBe(`${key}: ${want[key]}`);
+ } finally {
+ await engine.executeRaw(`DELETE FROM config WHERE key IN ('search.return_unit', 'think.return_unit')`);
+ }
+ }, 120_000);
+
+ test(`the implied auto default matches assemble_evidence auto for the same hits (${backend})`, async () => {
+ const engine = engines[backend]!;
+ let expanded = 0;
+ for (const remote of [false, true]) {
+ for (const query of ['ocelot', 'ocelot renewal roadmap']) {
+ const hits = await op('search').handler(ctxOf(engine, remote), { query, return_unit: 'chunk' }) as SearchResult[];
+ const viaDefault = await op('search').handler(ctxOf(engine, remote), { query }) as SearchResult[];
+ const viaAssemble = await op('assemble_evidence').handler(ctxOf(engine, remote), {
+ hits: hits.map(h => ({ source_id: h.source_id, slug: h.slug, chunk_id: h.chunk_id })), return_unit: 'auto',
+ }) as { results: SearchResult[] };
+ expect(evidenceFingerprint(viaAssemble.results)).toBe(evidenceFingerprint(viaDefault));
+ const chat = viaDefault.filter(r => r.slug === 'chat/session-a');
+ for (const r of chat) {
+ const [page] = await engine.executeRaw<{ compiled_truth: string; timeline: string }>('SELECT compiled_truth, timeline FROM pages WHERE id = $1', [r.page_id]);
+ expect(r.delivered).toMatchObject({ unit: 'page', reason: 'conversation_slug' });
+ expect(r.chunk_text).toBe(pageEvidenceText(page, true).text.trimEnd());
+ expanded++;
+ }
+ }
+ }
+ expect(expanded).toBeGreaterThan(0);
}, 120_000);
test(`page evidence is byte-identical to the stored body minus frontmatter and protected content (${backend})`, async () => {
@@ -102,7 +134,7 @@ describe('evidence delivery parity', () => {
test('both engines deliver the same windows and the same text for every unit', async () => {
const [a, b] = [engines.pglite!, engines.postgres!];
const textOf = (rows: SearchResult[]) => rows.map(r => [r.slug, r.chunk_text, r.delivered?.unit, r.delivered?.tokens, r.delivered?.truncated]);
- for (const unit of UNITS) {
+ for (const unit of [...UNITS, undefined]) {
const ra = await op('search').handler(ctxOf(a), { query: 'ocelot', return_unit: unit, token_budget: 2500 }) as SearchResult[];
const rb = await op('search').handler(ctxOf(b), { query: 'ocelot', return_unit: unit, token_budget: 2500 }) as SearchResult[];
expect(textOf(rb)).toEqual(textOf(ra));
diff --git a/test/evidence-delivery-golden.test.ts b/test/evidence-delivery-golden.test.ts
index f8e1f9e9b1..5e4e995097 100644
--- a/test/evidence-delivery-golden.test.ts
+++ b/test/evidence-delivery-golden.test.ts
@@ -1,40 +1,58 @@
/**
- * Evidence delivery off-path golden: with `return_unit` omitted (or `chunk`,
- * explicit or from config) search, query, recall, think's prompt and the MCP
- * serialization are byte-identical to the pre-feature release.
+ * Evidence delivery off-path golden: with `return_unit: chunk` (explicit or
+ * from config) search, query, recall, think's prompt and the MCP
+ * serialization are byte-identical to the pre-feature release, and the
+ * implied `auto` default is byte-identical wherever no hit is a conversation.
*
- * Authoring gate: protects the frozen off-path contract (plan amendment 6).
- * Regression: any stage/param/meta change that leaks into default responses
- * (a `delivery` key, a changed result count, recall field order, think
- * excerpting). The fixture was generated by this same file on the release
- * before evidence delivery (refactor wave 1, 9a0e01b4) and must not be
- * regenerated on a branch that changes the off path.
+ * Authoring gate: protects the frozen off-path contract (plan amendment 6)
+ * and auto's "unchanged elsewhere" promise. Regression: any stage/param/meta
+ * change that leaks into chunk responses (a `delivery` key, a changed result
+ * count, recall field order, think excerpting), or auto touching a
+ * non-conversation hit. The fixture was generated by this same file on the
+ * release before evidence delivery (refactor wave 1, 9a0e01b4) and must not
+ * be regenerated on a branch that changes the off path.
*
* The Postgres arm lives in test/e2e/evidence-delivery-parity.test.ts.
*/
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
-import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
-import { captureOffPath, seedOffPath } from './helpers/evidence-delivery-fixture.ts';
+import type { SearchResult } from '../src/core/types.ts';
+import { captureOffPath, OFF_PATH_PAGES, seedOffPath } from './helpers/evidence-delivery-fixture.ts';
const FIXTURE = join(import.meta.dir, 'fixtures/goldens/evidence-delivery/off-path.json');
+const CONVERSATION = 'chat/session-a';
let engine: PGLiteEngine;
+let plain: PGLiteEngine;
+
+async function withChunkConfig<T>(e: PGLiteEngine, run: () => Promise<T>): Promise<T> {
+ await e.setConfig('search.return_unit', 'chunk');
+ await e.setConfig('think.return_unit', 'chunk');
+ try { return await run(); } finally {
+ await e.executeRaw(`DELETE FROM config WHERE key IN ('search.return_unit', 'think.return_unit')`);
+ }
+}
beforeAll(async () => {
engine = new PGLiteEngine();
await engine.connect({});
await engine.initSchema();
await seedOffPath(engine);
+ plain = new PGLiteEngine();
+ await plain.connect({});
+ await plain.initSchema();
+ await seedOffPath(plain, OFF_PATH_PAGES.filter(p => p.slug !== CONVERSATION));
}, 240_000);
afterAll(async () => {
await engine.disconnect();
+ await plain.disconnect();
}, 240_000);
describe('evidence delivery off path', () => {
- test('omitted / chunk return_unit is byte-identical to the pre-feature release', async () => {
- const got = await captureOffPath(engine);
+ test('a config-level chunk unit is byte-identical to the pre-feature release', async () => {
+ const got = await withChunkConfig(engine, () => captureOffPath(engine));
if (process.env.GBRAIN_TEST_UPDATE_GOLDENS === '1') {
mkdirSync(dirname(FIXTURE), { recursive: true });
writeFileSync(FIXTURE, JSON.stringify(got, null, 2) + '\n');
@@ -44,15 +62,43 @@ describe('evidence delivery off path', () => {
for (const key of Object.keys(want)) expect(`${key}: ${got[key]}`).toBe(`${key}: ${want[key]}`);
});
- test('a config-level chunk unit is also byte-identical', async () => {
+ test('an explicit return_unit chunk is byte-identical to the pre-feature release', async () => {
const want = JSON.parse(readFileSync(FIXTURE, 'utf8')) as Record<string, string>;
- await engine.setConfig('search.return_unit', 'chunk');
- await engine.setConfig('think.return_unit', 'chunk');
- try {
- const got = await captureOffPath(engine);
- for (const key of Object.keys(want)) expect(`${key}: ${got[key]}`).toBe(`${key}: ${want[key]}`);
- } finally {
- await engine.executeRaw(`DELETE FROM config WHERE key IN ('search.return_unit', 'think.return_unit')`);
+ const got = await captureOffPath(engine);
+ const keys = Object.keys(want).filter(k => k.endsWith(':chunk'));
+ expect(keys.length).toBeGreaterThan(5);
+ for (const key of keys) expect(`${key}: ${got[key]}`).toBe(`${key}: ${want[key]}`);
+ });
+
+ test('the implied auto default is byte-identical to chunk on a corpus without conversations', async () => {
+ const chunk = await withChunkConfig(plain, () => captureOffPath(plain));
+ const auto = await captureOffPath(plain);
+ expect(Object.keys(auto).sort()).toEqual(Object.keys(chunk).sort());
+ for (const key of Object.keys(chunk)) expect(`${key}: ${auto[key]}`).toBe(`${key}: ${chunk[key]}`);
+ expect(Object.values(auto).some(v => v.includes('"delivery"') || v.includes('"delivered"'))).toBe(false);
+ });
+
+ test('the implied auto default expands only the conversation page; every other row is the frozen chunk row', async () => {
+ const want = JSON.parse(readFileSync(FIXTURE, 'utf8')) as Record<string, string>;
+ const got = await captureOffPath(engine);
+ let expanded = 0;
+ for (const key of ['search', 'search-remote', 'query', 'query-low']) {
+ const frozen = (JSON.parse(want[key]) as { result: SearchResult[] }).result;
+ const auto = JSON.parse(got[key]) as { result: SearchResult[] };
+ if (!auto.result.some(r => r.slug === CONVERSATION)) {
+ expect(`${key}: ${got[key]}`).toBe(`${key}: ${want[key]}`);
+ continue;
+ }
+ const others = auto.result.filter(r => r.slug !== CONVERSATION).map(({ delivered, ...r }) => {
+ expect(delivered, key).toMatchObject({ unit: 'chunk', reason: 'not_conversation' });
+ return r;
+ });
+ expect(others, key).toEqual(frozen.filter(r => r.slug !== CONVERSATION));
+ for (const r of auto.result.filter(r => r.slug === CONVERSATION)) {
+ expect(r.delivered, key).toMatchObject({ unit: 'page', reason: 'conversation_slug' });
+ expanded++;
+ }
}
+ expect(expanded).toBeGreaterThan(0);
});
});
diff --git a/test/evidence-delivery.test.ts b/test/evidence-delivery.test.ts
index 00bc032e1f..0bca0096a7 100644
--- a/test/evidence-delivery.test.ts
+++ b/test/evidence-delivery.test.ts
@@ -6,8 +6,8 @@
* docs/evidence-delivery.md (the bytes gbrain-evals measures). Regressions it
* catches: page text that differs from the body (lost paragraph breaks, duplicated overlap), budget overrun, spans that
* point at the wrong text, a config flip overriding the subagent snippet cap,
- * mutated shared hit rows, recall/think consumers dropping the evidence.
- * Existing search tests never exercise the stage (it is opt-in). No seams:
+ * mutated shared hit rows, recall/think consumers dropping the evidence, and
+ * the auto default touching anything but conversation pages. No seams:
* the property half drives `deliverEvidence` through a stub engine that only
* answers `getChunkWindows`; the op half runs the real ops on PGLite.
*/
@@ -22,8 +22,9 @@ import { prepareMarkdownChunks } from '../src/core/markdown-chunks.ts';
import { installFixtureChunks } from './helpers/page-projection.ts';
import { renderPagesBlock } from '../src/core/think/gather.ts';
import { runThink } from '../src/core/think/index.ts';
-import { formatDeliverySummary } from '../src/core/search/explain-formatter.ts';
+import { formatDeliverySummary, formatResultsExplain } from '../src/core/search/explain-formatter.ts';
import {
+ conversationSignal,
countEvidenceTokens,
deliverEvidence,
deliveryVersionSkewWarning,
@@ -179,7 +180,7 @@ function randomCorpus(r: () => number, pageCount: number): FakePage[] {
const body = conversational
? Array.from({ length: 6 + Math.floor(r() * 30) }, (_, t) => `**${t % 2 ? 'assistant' : 'user'}:** ${prose(r, 1)}`).join('\n\n')
: Array.from({ length: 1 + Math.floor(r() * 4) }, (_, s) => `## Section ${s}\n\n${prose(r, 2 + Math.floor(r() * 8))}`).join('\n\n');
- return { page_id: i + 1, slug: `pages/p${i + 1}`, title: `Page ${i + 1}`, body, chunks: chunkText(body).map(c => c.text) };
+ return { page_id: i + 1, slug: `${conversational ? 'chat' : 'pages'}/p${i + 1}`, title: `Page ${i + 1}`, body, chunks: chunkText(body).map(c => c.text) };
});
}
@@ -193,7 +194,7 @@ describe('allocation and boundary properties', () => {
const p = pages[Math.floor(r() * pages.length)];
hits.push(hitFor(p, Math.floor(r() * p.chunks.length)));
}
- const unit = (['window', 'section', 'page', 'auto'] as const)[Math.floor(r() * 4)];
+ const unit = (['window', 'section', 'page'] as const)[Math.floor(r() * 3)];
const budget = [40, 200, 800, 3000, 12000][Math.floor(r() * 5)];
const snapshot = JSON.stringify(hits);
const engine = fakeEngine(pages);
@@ -221,6 +222,69 @@ describe('allocation and boundary properties', () => {
}
});
+ test('auto: conversation pages whole, every other hit its unchanged chunk, nothing lost, expansion within budget', async () => {
+ const r = rng(20261001);
+ let sawPage = 0;
+ let sawChunk = 0;
+ for (let trial = 0; trial < 60; trial++) {
+ const pages = randomCorpus(r, 1 + Math.floor(r() * 8));
+ const hits: SearchResult[] = [];
+ for (let k = 0; k < 1 + Math.floor(r() * 10); k++) {
+ const p = pages[Math.floor(r() * pages.length)];
+ const h = hitFor(p, Math.floor(r() * p.chunks.length));
+ if (!hits.some(x => x.chunk_id === h.chunk_id)) hits.push(h);
+ }
+ const budget = [40, 200, 800, 3000, 24000][Math.floor(r() * 5)];
+ const snapshot = JSON.stringify(hits);
+ const engine = fakeEngine(pages);
+ const { results, delivery } = await deliverEvidence(engine, hits, planOf('auto', budget), {});
+ expect(JSON.stringify(hits)).toBe(snapshot);
+ expect(engine.calls).toBe(hits.some(h => h.slug.startsWith('chat/')) ? 1 : 0);
+ expect(delivery.dropped).toBe(0);
+ const cost = (x: SearchResult) => countEvidenceTokens(x.chunk_text) + countEvidenceTokens(x.title);
+ for (const h of hits) expect(results.some(x => x.delivered.chunk_ids.includes(h.chunk_id)), `hit ${h.chunk_id} lost`).toBe(true);
+ const firstRank = (x: SearchResult) => Math.min(...x.delivered!.chunk_ids.map(id => hits.findIndex(h => h.chunk_id === id)));
+ expect(results.map(firstRank)).toEqual(results.map(firstRank).sort((a, b) => a - b));
+ for (const res of results) {
+ if (res.delivered.reason === 'not_conversation' || res.delivered.reason === 'conversation_over_budget') {
+ sawChunk++;
+ const { delivered, ...row } = res;
+ expect(row).toEqual(hits.find(h => h.chunk_id === delivered.chunk_ids[0])!);
+ expect(delivered).toMatchObject({ unit: 'chunk', truncated: false, match_spans: [{ chunk_id: delivered.chunk_ids[0], start: 0, end: row.chunk_text.length }] });
+ expect(delivered.reason === 'not_conversation').toBe(!row.slug.startsWith('chat/'));
+ } else {
+ sawPage++;
+ expect(res.slug.startsWith('chat/')).toBe(true);
+ expect(res.delivered).toMatchObject({ unit: 'page', reason: 'conversation_slug' });
+ expect(res.delivered.match_spans.length).toBeGreaterThan(0);
+ }
+ }
+ const unchanged = results.filter(x => x.delivered.reason === 'not_conversation');
+ const expanded = results.filter(x => x.delivered.unit === 'page');
+ expect(new Set(expanded.map(x => x.page_id)).size).toBe(expanded.length);
+ expect(expanded.reduce((n, x) => n + cost(x), 0)).toBeLessThanOrEqual(Math.max(0, budget - unchanged.reduce((n, x) => n + cost(x), 0)));
+ }
+ expect(sawPage).toBeGreaterThan(10);
+ expect(sawChunk).toBeGreaterThan(10);
+ });
+
+ test('auto gives lower-ranked sessions their matching span, and spills a session that cannot fit to its chunks', async () => {
+ const pages = randomCorpus(rng(5), 12).filter(p => p.slug.startsWith('chat/')).slice(0, 3);
+ expect(pages).toHaveLength(3);
+ const hits = pages.map(p => hitFor(p, Math.floor(p.chunks.length / 2)));
+ const floors = hits.reduce((n, h) => n + countEvidenceTokens(h.chunk_text) + countEvidenceTokens(h.title), 0);
+ const roomy = await deliverEvidence(fakeEngine(pages), hits, planOf('auto', Math.ceil(floors * 1.5)), {});
+ expect(roomy.results.map(x => x.delivered.unit)).toEqual(['page', 'page', 'page']);
+ for (const res of roomy.results) expect(res.delivered.match_spans.length).toBeGreaterThan(0);
+ // The smallest budget that still gives rank one its page leaves no room for the others' spans.
+ let budget = countEvidenceTokens(hits[0].chunk_text);
+ let tight = await deliverEvidence(fakeEngine(pages), hits, planOf('auto', budget), {});
+ while (tight.results[0].delivered.unit !== 'page') tight = await deliverEvidence(fakeEngine(pages), hits, planOf('auto', ++budget), {});
+ expect(tight.results.map(x => x.delivered.reason)).toEqual(['conversation_slug', 'conversation_over_budget', 'conversation_over_budget']);
+ expect(tight.results.slice(1).map(x => x.chunk_text)).toEqual(hits.slice(1).map(h => h.chunk_text));
+ expect(tight.delivery.dropped).toBe(0);
+ });
+
test('a budget below every floor cuts rank one to fit and drops the rest', async () => {
const [a, b] = randomCorpus(rng(3), 2);
const { results, delivery } = await deliverEvidence(fakeEngine([a, b]), [hitFor(a, 0), hitFor(b, 0)], planOf('page', 12), {});
@@ -345,12 +409,18 @@ const SESSION = Array.from({ length: 24 }, (_, i) =>
`**user:** question ${i} ${'about the renewal and the widget roadmap '.repeat(6)}\n\n**assistant:** reply ${i} ${'we discussed timelines and owners '.repeat(6)}${i === 13 ? ' the launch moved to march narwhal' : ''}`,
).join('\n\n');
const HANDBOOK = `## Overview\n\n${prose(rng(21), 6)}\n\n## Pricing\n\n${prose(rng(22), 6)} narwhal pricing note.\n\n## Support\n\n${prose(rng(23), 6)}`;
+const codeFn = (name: string) => `export function ${name}(input: number): number {\n${Array.from({ length: 12 }, (_, i) => ` const step${i} = input * ${i + 2} + ${name.length};`).join('\n')}\n return input;\n}`;
+// One prose chunk (index 0) holding the whole fence, then one fenced_code
+// chunk per function (indices 1-3): a hit on index 2 or 3 has no prose chunk
+// within return_window, and every code chunk carries a synthesized header.
+const CODE_PAGE = `## Setup\n\nThe quokka service boots from this module.\n\n\`\`\`ts\n${codeFn('alpha')}\n\n${codeFn('beta')}\n\n${codeFn('gamma')}\n\`\`\`\n\nClosing prose about the quokka service.`;
+const CHUNK_HEADER_LINE = /^\[[^\]]+\] fence\.\w+:\d+-\d+ /m;
beforeAll(async () => {
engine = new PGLiteEngine();
await engine.connect({});
await engine.initSchema();
- for (const [slug, body] of [['chat/session-1', SESSION], ['notes/handbook', HANDBOOK]] as const) {
+ for (const [slug, body] of [['chat/session-1', SESSION], ['notes/handbook', HANDBOOK], ['notes/quokka-code', CODE_PAGE]] as const) {
await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: body, timeline: slug === 'notes/handbook' ? '- 2026-01-02 narwhal timeline entry' : '', frontmatter: {} });
await installFixtureChunks(engine, slug, await prepareMarkdownChunks({ compiled_truth: body, timeline: slug === 'notes/handbook' ? '- 2026-01-02 narwhal timeline entry' : '' }));
}
@@ -362,12 +432,91 @@ afterAll(async () => {
}, 240_000);
describe('ops', () => {
- test('omitted return_unit leaves search output without delivery fields', async () => {
+ test('omitted return_unit with no conversation hit is exactly the chunk response', async () => {
lastMeta = null;
- const rows = await op('search').handler(ctxOf(), { query: 'narwhal' }) as SearchResult[];
+ const rows = await op('search').handler(ctxOf(), { query: 'pricing' }) as SearchResult[];
expect(rows.length).toBeGreaterThan(0);
+ expect(rows.every(r => !r.slug.startsWith('chat/'))).toBe(true);
expect(rows.every(r => r.delivered === undefined)).toBe(true);
expect((lastMeta as Record<string, unknown> | null)?.delivery).toBeUndefined();
+ const offMeta = lastMeta;
+ const chunk = await op('search').handler(ctxOf(), { query: 'pricing', return_unit: 'chunk' }) as SearchResult[];
+ expect(JSON.stringify(rows)).toBe(JSON.stringify(chunk));
+ expect(JSON.stringify(offMeta)).toBe(JSON.stringify(lastMeta));
+ });
+
+ test('omitted return_unit delivers conversation pages whole and keeps other hits as their chunks', async () => {
+ lastMeta = null;
+ const chunk = await op('search').handler(ctxOf(), { query: 'narwhal', return_unit: 'chunk' }) as SearchResult[];
+ const rows = await op('search').handler(ctxOf(), { query: 'narwhal' }) as SearchResult[];
+ expect(lastMeta!.delivery).toMatchObject({ requested_unit: 'auto', applied_unit: 'auto', budget_tokens: 24000 });
+ const chat = rows.find(r => r.slug === 'chat/session-1')!;
+ expect(chat.delivered).toMatchObject({ unit: 'page', reason: 'conversation_slug', truncated: false });
+ const [page] = await engine.executeRaw<{ compiled_truth: string; timeline: string }>('SELECT compiled_truth, timeline FROM pages WHERE id = $1', [chat.page_id]);
+ expect(chat.chunk_text).toBe(pageEvidenceText(page, true).text.trimEnd());
+ expect(rows.filter(r => r.slug === 'chat/session-1')).toHaveLength(1);
+ const others = rows.filter(r => r.slug !== 'chat/session-1');
+ expect(others.length).toBeGreaterThan(0);
+ expect(others.map(({ delivered, ...r }) => { expect(delivered).toMatchObject({ unit: 'chunk', reason: 'not_conversation' }); return r; }))
+ .toEqual(chunk.filter(r => r.slug !== 'chat/session-1'));
+ const typed = await op('search').handler(ctxOf(), { query: 'quokka' }) as SearchResult[];
+ expect(typed.every(r => r.delivered === undefined)).toBe(true);
+ });
+
+ test('auto detects conversations by type or slug, deterministically', () => {
+ const at = (type: string, slug: string) => conversationSignal({ type, slug });
+ for (const t of ['conversation', 'transcript', 'chat', 'meeting', 'slack', 'slack-thread', 'imessage', 'Conversation']) expect(at(t, 'notes/x')).toBe('conversation_type');
+ expect(at('note', 'chat/s-1')).toBe('conversation_slug');
+ expect(at('note', 'conversations/sessions/2026-01-01-codex-abc')).toBe('conversation_slug');
+ for (const [t, slug] of [['note', 'notes/chat'], ['email', 'emails/a'], ['code', 'src/chat.ts'], ['person', 'people/meeting-maker']]) expect(at(t, slug)).toBeNull();
+ });
+
+ test('query token_budget, recall budget_tokens/budget_policy and an explicit chunk keep the legacy chunk path under the auto default', async () => {
+ lastMeta = null;
+ await op('query').handler(ctxOf(), { query: 'narwhal', expand: false, token_budget: 900 });
+ expect(lastMeta!.delivery).toBeUndefined();
+ await op('search').handler(ctxOf(), { query: 'narwhal', return_unit: 'chunk' });
+ expect(lastMeta!.delivery).toBeUndefined();
+ const legacy = await op('recall').handler(ctxOf(), { query: 'narwhal', budget_tokens: 5000, budget_policy: 'query_first' }) as Record<string, any>;
+ expect(legacy.delivery).toBeUndefined();
+ const packed = await op('recall').handler(ctxOf(), { query: 'narwhal', budget_tokens: 5000 }) as Record<string, any>;
+ expect(packed.delivery).toBeUndefined();
+ const auto = await op('recall').handler(ctxOf(), { query: 'narwhal' }) as Record<string, any>;
+ expect(auto.delivery.requested_unit).toBe('auto');
+ expect(auto.results.find((r: Record<string, any>) => r.slug === 'chat/session-1').delivered).toMatchObject({ unit: 'page', reason: 'conversation_slug' });
+ await engine.setConfig('search.return_unit', 'chunk');
+ try {
+ await op('search').handler(ctxOf(), { query: 'narwhal' });
+ expect(lastMeta!.delivery).toBeUndefined();
+ } finally {
+ await engine.executeRaw(`DELETE FROM config WHERE key = 'search.return_unit'`);
+ }
+ });
+
+ test('auto keeps the subagent snippet economy, the remote cap and its own budget key', async () => {
+ const sub = await op('search').handler(ctxOf({ viaSubagent: true } as Partial<OperationContext>), { query: 'narwhal' }) as SearchResult[];
+ expect(sub.every(r => r.delivered === undefined && r.chunk_text.length <= 300 + 80)).toBe(true);
+ await op('search').handler(ctxOf({ remote: true }), { query: 'narwhal', token_budget: 90000 });
+ expect(lastMeta!.delivery).toMatchObject({ applied_unit: 'auto', budget_tokens: 32000, budget_clamped: { requested: 90000, max: 32000 } });
+ await engine.setConfig('search.return_budget_conversation', '40000');
+ try {
+ await op('search').handler(ctxOf({ remote: true }), { query: 'narwhal' });
+ expect(lastMeta!.delivery.budget_tokens).toBe(32000);
+ await op('search').handler(ctxOf(), { query: 'narwhal' });
+ expect(lastMeta!.delivery.budget_tokens).toBe(40000);
+ } finally {
+ await engine.executeRaw(`DELETE FROM config WHERE key = 'search.return_budget_conversation'`);
+ }
+ const capped = await op('search').handler(ctxOf(), { query: 'narwhal', snippet_chars: 120 }) as SearchResult[];
+ expect(capped.every(r => r.chunk_text.length <= 120 + 200)).toBe(true);
+ });
+
+ test('explain names each result\'s unit and the auto reason', async () => {
+ const rows = await op('search').handler(ctxOf(), { query: 'narwhal' }) as SearchResult[];
+ const text = formatResultsExplain(rows, { delivery: lastMeta!.delivery } as never);
+ expect(text).toContain('evidence: auto — ');
+ expect(text).toContain('evidence: page (conversation_slug)');
+ expect(text).toContain('evidence: chunk (not_conversation)');
});
test('every unit delivers through search with delivered + delivery meta', async () => {
@@ -435,7 +584,7 @@ describe('ops', () => {
const human = await op('search').handler(ctxOf(), { query: 'narwhal' }) as SearchResult[];
expect(human[0].delivered).toBeDefined();
} finally {
- await engine.setConfig('search.return_unit', 'chunk');
+ await engine.executeRaw(`DELETE FROM config WHERE key = 'search.return_unit'`);
}
});
@@ -447,7 +596,7 @@ describe('ops', () => {
});
test('recall keeps legacy fields and packing, adding delivered/delivery only when on', async () => {
- const off = await op('recall').handler(ctxOf(), { query: 'narwhal', budget_tokens: 5000 }) as Record<string, any>;
+ const off = await op('recall').handler(ctxOf(), { query: 'narwhal', budget_tokens: 5000, return_unit: 'chunk' }) as Record<string, any>;
expect(off.delivery).toBeUndefined();
expect(off.results.every((r: Record<string, unknown>) => Object.keys(r).join(',') === 'slug,title,chunk,evidence,create_safety,provenance')).toBe(true);
const on = await op('recall').handler(ctxOf(), { query: 'narwhal', budget_tokens: 5000, return_unit: 'page' }) as Record<string, any>;
@@ -476,25 +625,83 @@ describe('ops', () => {
expect(bad.unresolved).toEqual([0]);
});
+ test('a fenced-code best hit delivers the page text for return_unit page, not the code chunk', async () => {
+ const [page] = await engine.executeRaw<{ compiled_truth: string; timeline: string }>(`SELECT compiled_truth, timeline FROM pages WHERE slug = 'notes/quokka-code'`);
+ const code = await engine.executeRaw<{ id: number; chunk_index: number; chunk_text: string }>(
+ `SELECT cc.id, cc.chunk_index, cc.chunk_text FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.slug = 'notes/quokka-code' AND cc.chunk_source = 'fenced_code' ORDER BY cc.chunk_index`);
+ expect(code.map(c => c.chunk_index)).toEqual([1, 2, 3]);
+ const text = pageEvidenceText(page, true).text;
+ for (const c of code) {
+ const out = await op('assemble_evidence').handler(ctxOf(), {
+ hits: [{ source_id: 'default', slug: 'notes/quokka-code', chunk_id: c.id }], return_unit: 'page', token_budget: 32000,
+ }) as { results: SearchResult[]; delivery: { fallbacks: string[] } };
+ const [r] = out.results;
+ expect(r.delivered!.unit, `chunk_index ${c.chunk_index}`).toBe('page');
+ expect(r.delivered!.fallback_reason).toBeUndefined();
+ expect(r.delivered!.unmapped_chunk_ids).toBeUndefined();
+ expect(r.chunk_text).toBe(text.trimEnd());
+ const [span] = r.delivered!.match_spans;
+ expect(span.chunk_id).toBe(c.id);
+ expect(norm(r.chunk_text.slice(span.start, span.end))).toBe(norm(c.chunk_text.replace(/^[^\n]*\n\n/, '')));
+ }
+ });
+
+ test('fenced-code evidence never carries the chunker header, in any expanding unit or fallback', async () => {
+ const [page] = await engine.executeRaw<{ compiled_truth: string; timeline: string }>(`SELECT compiled_truth, timeline FROM pages WHERE slug = 'notes/quokka-code'`);
+ const text = pageEvidenceText(page, true).text;
+ const code = await engine.executeRaw<{ id: number }>(
+ `SELECT cc.id FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.slug = 'notes/quokka-code' AND cc.chunk_source = 'fenced_code'`);
+ for (const unit of ['window', 'section', 'page']) {
+ for (const budget of [32000, 60]) {
+ const out = await op('assemble_evidence').handler(ctxOf(), {
+ hits: code.map(c => ({ source_id: 'default', slug: 'notes/quokka-code', chunk_id: c.id })), return_unit: unit, token_budget: budget,
+ }) as { results: SearchResult[] };
+ for (const r of out.results) {
+ expect(r.chunk_text, `${unit}/${budget}`).not.toMatch(CHUNK_HEADER_LINE);
+ for (const seg of r.chunk_text.split(EVIDENCE_OMISSION)) expect(text.includes(seg), `${unit}/${budget}: ${seg.slice(0, 60)}`).toBe(true);
+ }
+ }
+ }
+ // auto leaves a non-conversation page on the chunk path: the ranked rows, unchanged.
+ const auto = await op('assemble_evidence').handler(ctxOf(), {
+ hits: code.map(c => ({ source_id: 'default', slug: 'notes/quokka-code', chunk_id: c.id })), return_unit: 'auto',
+ }) as { results: SearchResult[] };
+ expect(auto.results.map(r => r.delivered!.reason)).toEqual(['not_conversation', 'not_conversation', 'not_conversation']);
+ const plain = await op('assemble_evidence').handler(ctxOf(), {
+ hits: code.map(c => ({ source_id: 'default', slug: 'notes/quokka-code', chunk_id: c.id })), return_unit: 'chunk',
+ }) as { results: SearchResult[] };
+ expect(auto.results.map(r => r.chunk_text)).toEqual(plain.results.map(r => r.chunk_text));
+ const hits = await op('search').handler(ctxOf(), { query: 'quokka' }) as SearchResult[];
+ const codeHit = { ...hits.find(h => h.slug === 'notes/quokka-code')!, chunk_id: code[1].id, chunk_index: 2, chunk_source: 'fenced_code' as const,
+ chunk_text: (await engine.executeRaw<{ chunk_text: string }>('SELECT chunk_text FROM content_chunks WHERE id = $1', [code[1].id]))[0].chunk_text };
+ expect(codeHit.chunk_text).toMatch(CHUNK_HEADER_LINE);
+ const failing = { getChunkWindows: async () => { throw new Error('synthetic fetch failure'); } } as unknown as BrainEngine;
+ const fallback = await deliverEvidence(failing, [codeHit], planOf('page', 5000), {});
+ expect(fallback.results[0].delivered).toMatchObject({ unit: 'chunk', fallback_reason: 'fetch_failed' });
+ expect(fallback.results[0].chunk_text).not.toMatch(CHUNK_HEADER_LINE);
+ expect(text.includes(fallback.results[0].chunk_text)).toBe(true);
+ });
+
test('think renders delivered blocks whole under think.return_unit, and only then', async () => {
const prompts: string[] = [];
const client = { create: async (params: { messages: Array<{ content: unknown }> }) => {
prompts.push(JSON.stringify(params.messages));
return { content: [{ type: 'text', text: '{"answer":"ok","citations":[],"gaps":[]}' }], usage: { input_tokens: 1, output_tokens: 1 } };
} };
- await runThink(engine, { question: 'narwhal launch march', client: client as never, remote: false });
- expect(prompts[0]).not.toContain('reply 23 ');
- await engine.setConfig('search.return_unit', 'page');
+ const auto = await runThink(engine, { question: 'narwhal launch march', client: client as never, remote: false });
+ expect(prompts[0]).toContain('reply 23 ');
+ expect(auto.evidence_delivery?.requested_unit).toBe('auto');
+ await engine.setConfig('think.return_unit', 'chunk');
try {
await runThink(engine, { question: 'narwhal launch march', client: client as never, remote: false });
expect(prompts[1]).not.toContain('reply 23 ');
+ await engine.setConfig('search.return_unit', 'chunk');
await engine.setConfig('think.return_unit', 'page');
const r = await runThink(engine, { question: 'narwhal launch march', client: client as never, remote: false });
expect(prompts[2]).toContain('reply 23 ');
expect(r.evidence_delivery?.requested_unit).toBe('page');
} finally {
- await engine.setConfig('search.return_unit', 'chunk');
- await engine.setConfig('think.return_unit', 'chunk');
+ await engine.executeRaw(`DELETE FROM config WHERE key IN ('search.return_unit', 'think.return_unit')`);
}
});
diff --git a/test/fixtures/goldens/cli/help-and-errors.json b/test/fixtures/goldens/cli/help-and-errors.json
index 6762591713..42111c9dfb 100644
--- a/test/fixtures/goldens/cli/help-and-errors.json
+++ b/test/fixtures/goldens/cli/help-and-errors.json
@@ -653,7 +653,7 @@
"stdout": [
"Usage: gbrain query <query> [options]",
"",
- "Hybrid search with vector + keyword + multi-query expansion. Prefer `query` for concept / synonym / landscape questions ('all the X that do Y', 'the landscape of Z') — expansion recovers synonym- and outcome-phrased matches a single embedding misses. Still top-K, and the default count when `limit` is omitted depends on the configured search mode (10 conservative / 25 balanced / 50 tokenmax — see the `limit` param description); pass `limit` explicitly for a stable count regardless of mode. When the answer needs the surrounding conversation or section, pass `return_unit` ('page' / 'section' / 'window') to get that evidence in one call instead of get_page per hit. For exhaustive enumeration use list_pages; for exact known tokens `search` is cheaper (no expansion LLM call). For personal/emotional questions ('what's going on with me', 'anything notable', 'how am I feeling'), prefer get_recent_salience, find_anomalies, or get_recent_transcripts. Semantic search returns polished pages and misses recent activity bursts. Do NOT assume words like 'crazy', 'notable', or 'big' mean impressive — they often mean difficult or emotionally charged.",
+ "Hybrid search with vector + keyword + multi-query expansion. Prefer `query` for concept / synonym / landscape questions ('all the X that do Y', 'the landscape of Z') — expansion recovers synonym- and outcome-phrased matches a single embedding misses. Still top-K, and the default count when `limit` is omitted depends on the configured search mode (10 conservative / 25 balanced / 50 tokenmax — see the `limit` param description); pass `limit` explicitly for a stable count regardless of mode. When the answer needs the surrounding conversation or section, pass `return_unit` ('page' / 'section' / 'window') to get that evidence in one call instead of get_page per hit; conversation pages already come back whole by default (return_unit 'auto'; 'chunk' opts out). For exhaustive enumeration use list_pages; for exact known tokens `search` is cheaper (no expansion LLM call). For personal/emotional questions ('what's going on with me', 'anything notable', 'how am I feeling'), prefer get_recent_salience, find_anomalies, or get_recent_transcripts. Semantic search returns polished pages and misses recent activity bursts. Do NOT assume words like 'crazy', 'notable', or 'big' mean impressive — they often mean difficult or emotionally charged.",
"",
"Options:",
" <query> Question or topic text for hybrid retrieval with expansion (e.g. 'agents that do web research'). This is the search text param — there is no `text` or `q` param. Optional ONLY because `image` is the alternative entry point; a call with neither fails with invalid_params.",
@@ -663,15 +663,15 @@
" --offset Skip first N results (for pagination)",
" --types 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 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. (#3800)",
- " --return-unit Evidence unit returned in each result's chunk_text (default: config search.return_unit, which defaults to 'chunk').",
+ " --return-unit Evidence unit returned in each result's chunk_text (default: config search.return_unit, which defaults to 'auto').",
" 'chunk' — the ranked chunk only (~300-450 tokens per result).",
" 'window' — the hit chunk plus return_window neighbor chunks each side (local context, ~3x chunk).",
" 'section' — the enclosing markdown section, or the conversation rounds around the hit.",
" 'page' — the whole page/session, capped. Use for multi-session or temporal questions where the answer needs the whole conversation.",
- " 'auto' — page for conversations and short pages, section or window for long curated pages.",
- "Non-chunk units return one result per page, packed into token_budget (default 6000; remote max 32000), with a `delivered` object (unit, chunk_ids, match_spans, tokens, truncated) per result and `delivery` in the response meta.",
+ " '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.",
+ "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 Neighbor chunks on each side for return_unit 'window' (integer 1-3, default 1).",
- " --token-budget Token budget. Chunk mode: caps the cumulative chunk payload (results that would overflow are skipped). Non-chunk return_unit: the budget for delivered evidence (default search.return_budget_default = 6000; remote max search.return_budget_max_remote = 32000).",
+ " --token-budget 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).",
" --expand Request multi-query expansion (default: true in every search mode, regardless of search.expansion). Set false to opt out. Requires configured embedding and expansion providers; a cloud expander receives the query and may charge for the call. Response metadata expansion_applied reports whether variants were actually used.",
" --detail Result detail level: low (compiled truth only), medium (default, all with dedup), high (all chunks)",
" --mode Search mode (conservative|balanced|tokenmax). Local callers only; remote uses configured mode.",
diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.json
index a254f12a99..ef539d5501 100644
--- a/test/fixtures/goldens/cli/tools-json.json
+++ b/test/fixtures/goldens/cli/tools-json.json
@@ -2,8 +2,8 @@
"golden": {
"exitCode": 0,
"stderr": "",
- "stdoutBytes": 199477,
- "stdoutSha256": "f786702cc5f72f442c7e10fba6df96f06ff3e1bef9726aeea28a96a908b5c72f",
+ "stdoutBytes": 200378,
+ "stdoutSha256": "c23df35de49ce6ca01006bf4db2ce92fb57d2f37f089f82fef292c047982b00e",
"toolNames": [
"remember",
"entity",
@@ -745,7 +745,7 @@
}
},
{
- "description": "Cheap hybrid search (vector + keyword + RRF) with no LLM expansion. Best for exact known tokens, names, and structured-field lookups. A populated result set is NOT proof of coverage — for concept / synonym / landscape questions use `query` (adds multi-query expansion); for exhaustive enumeration use list_pages pagination. Pass `return_unit` ('window' / 'section' / 'page') for whole evidence instead of chunks. For personal/emotional questions, prefer get_recent_salience or find_anomalies — they surface activity bursts without needing a search term. For code-symbol questions (callers, callees, definitions, blast radius), use code_callers / code_callees / code_def / code_refs instead — those return structural graph data, not text chunks. For agent memory reads (saved facts + budget-packed retrieval), prefer the `recall` verb.",
+ "description": "Cheap hybrid search (vector + keyword + RRF) with no LLM expansion. Best for exact known tokens, names, and structured-field lookups. A populated result set is NOT proof of coverage — for concept / synonym / landscape questions use `query` (adds multi-query expansion); for exhaustive enumeration use list_pages pagination. Pass `return_unit` ('window' / 'section' / 'page') for whole evidence instead of chunks; conversation pages already come back whole by default (return_unit 'auto'; 'chunk' opts out). For personal/emotional questions, prefer get_recent_salience or find_anomalies — they surface activity bursts without needing a search term. For code-symbol questions (callers, callees, definitions, blast radius), use code_callers / code_callees / code_def / code_refs instead — those return structural graph data, not text chunks. For agent memory reads (saved facts + budget-packed retrieval), prefer the `recall` verb.",
"name": "search",
"parameters": {
"limit": "number?",
@@ -789,7 +789,7 @@
"type": "string"
},
"return_unit": {
- "description": "Evidence unit returned in each result's chunk_text (default: config search.return_unit, which defaults to 'chunk').\n 'chunk' — the ranked chunk only (~300-450 tokens per result).\n 'window' — the hit chunk plus return_window neighbor chunks each side (local context, ~3x chunk).\n 'section' — the enclosing markdown section, or the conversation rounds around the hit.\n 'page' — the whole page/session, capped. Use for multi-session or temporal questions where the answer needs the whole conversation.\n 'auto' — page for conversations and short pages, section or window for long curated pages.\nNon-chunk units return one result per page, packed into token_budget (default 6000; remote max 32000), with a `delivered` object (unit, chunk_ids, match_spans, tokens, truncated) per result and `delivery` in the response meta.",
+ "description": "Evidence unit returned in each result's chunk_text (default: config search.return_unit, which defaults to 'auto').\n 'chunk' — the ranked chunk only (~300-450 tokens per result).\n 'window' — the hit chunk plus return_window neighbor chunks each side (local context, ~3x chunk).\n 'section' — the enclosing markdown section, or the conversation rounds around the hit.\n 'page' — the whole page/session, capped. Use for multi-session or temporal questions where the answer needs the whole conversation.\n '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.\nNon-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.",
"enum": [
"chunk",
"window",
@@ -821,7 +821,7 @@
"type": "string"
},
"token_budget": {
- "description": "Token budget for delivered evidence when return_unit is not 'chunk' (default search.return_budget_default = 6000). Ignored in chunk mode.",
+ "description": "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.",
"type": "number"
},
"types": {
@@ -839,7 +839,7 @@
}
},
{
- "description": "Hybrid search with vector + keyword + multi-query expansion. Prefer `query` for concept / synonym / landscape questions ('all the X that do Y', 'the landscape of Z') — expansion recovers synonym- and outcome-phrased matches a single embedding misses. Still top-K, and the default count when `limit` is omitted depends on the configured search mode (10 conservative / 25 balanced / 50 tokenmax — see the `limit` param description); pass `limit` explicitly for a stable count regardless of mode. When the answer needs the surrounding conversation or section, pass `return_unit` ('page' / 'section' / 'window') to get that evidence in one call instead of get_page per hit. For exhaustive enumeration use list_pages; for exact known tokens `search` is cheaper (no expansion LLM call). For personal/emotional questions ('what's going on with me', 'anything notable', 'how am I feeling'), prefer get_recent_salience, find_anomalies, or get_recent_transcripts. Semantic search returns polished pages and misses recent activity bursts. Do NOT assume words like 'crazy', 'notable', or 'big' mean impressive — they often mean difficult or emotionally charged.",
+ "description": "Hybrid search with vector + keyword + multi-query expansion. Prefer `query` for concept / synonym / landscape questions ('all the X that do Y', 'the landscape of Z') — expansion recovers synonym- and outcome-phrased matches a single embedding misses. Still top-K, and the default count when `limit` is omitted depends on the configured search mode (10 conservative / 25 balanced / 50 tokenmax — see the `limit` param description); pass `limit` explicitly for a stable count regardless of mode. When the answer needs the surrounding conversation or section, pass `return_unit` ('page' / 'section' / 'window') to get that evidence in one call instead of get_page per hit; conversation pages already come back whole by default (return_unit 'auto'; 'chunk' opts out). For exhaustive enumeration use list_pages; for exact known tokens `search` is cheaper (no expansion LLM call). For personal/emotional questions ('what's going on with me', 'anything notable', 'how am I feeling'), prefer get_recent_salience, find_anomalies, or get_recent_transcripts. Semantic search returns polished pages and misses recent activity bursts. Do NOT assume words like 'crazy', 'notable', or 'big' mean impressive — they often mean difficult or emotionally charged.",
"name": "query",
"parameters": {
"adaptive_return": "boolean?",
@@ -948,7 +948,7 @@
"type": "boolean"
},
"return_unit": {
- "description": "Evidence unit returned in each result's chunk_text (default: config search.return_unit, which defaults to 'chunk').\n 'chunk' — the ranked chunk only (~300-450 tokens per result).\n 'window' — the hit chunk plus return_window neighbor chunks each side (local context, ~3x chunk).\n 'section' — the enclosing markdown section, or the conversation rounds around the hit.\n 'page' — the whole page/session, capped. Use for multi-session or temporal questions where the answer needs the whole conversation.\n 'auto' — page for conversations and short pages, section or window for long curated pages.\nNon-chunk units return one result per page, packed into token_budget (default 6000; remote max 32000), with a `delivered` object (unit, chunk_ids, match_spans, tokens, truncated) per result and `delivery` in the response meta.",
+ "description": "Evidence unit returned in each result's chunk_text (default: config search.return_unit, which defaults to 'auto').\n 'chunk' — the ranked chunk only (~300-450 tokens per result).\n 'window' — the hit chunk plus return_window neighbor chunks each side (local context, ~3x chunk).\n 'section' — the enclosing markdown section, or the conversation rounds around the hit.\n 'page' — the whole page/session, capped. Use for multi-session or temporal questions where the answer needs the whole conversation.\n '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.\nNon-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.",
"enum": [
"chunk",
"window",
@@ -988,7 +988,7 @@
"type": "string"
},
"token_budget": {
- "description": "Token budget. Chunk mode: caps the cumulative chunk payload (results that would overflow are skipped). Non-chunk return_unit: the budget for delivered evidence (default search.return_budget_default = 6000; remote max search.return_budget_max_remote = 32000).",
+ "description": "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).",
"type": "number"
},
"types": {
@@ -1055,7 +1055,7 @@
"type": "number"
},
"token_budget": {
- "description": "Token budget for the delivered evidence (default search.return_budget_default = 6000; remote max 32000).",
+ "description": "Token budget for the delivered evidence (default search.return_budget_default = 6000, auto search.return_budget_conversation = 24000; remote max 32000).",
"type": "number"
}
},
@@ -4281,7 +4281,7 @@
"type": "string"
},
"return_unit": {
- "description": "Evidence unit for the results[] arm (needs `query`; default config search.return_unit = 'chunk'). 'window' adds neighbor chunks, 'section' the enclosing section or conversation rounds, 'page' the whole page/session (best for multi-session questions), 'auto' picks per page. Non-chunk units return one result per page with `delivered` metadata and a top-level `delivery` block; the evidence is budgeted by budget_tokens (default 6000) and then packed by recall's usual rules.",
+ "description": "Evidence unit for the results[] arm (needs `query`; default config search.return_unit = 'auto'). 'window' adds neighbor chunks, 'section' the enclosing section or conversation rounds, 'page' the whole page/session (best for multi-session questions), 'auto' the whole page for conversation pages and the ranked chunk unchanged for everything else (budget_tokens or budget_policy without return_unit keeps chunk packing). Non-chunk units return one result per page with `delivered` metadata and a top-level `delivery` block; the evidence is budgeted by budget_tokens (default 6000, auto 24000) and then packed by recall's usual rules.",
"enum": [
"chunk",
"window",
diff --git a/test/fixtures/goldens/exports/runtime.json b/test/fixtures/goldens/exports/runtime.json
index 74773882c0..1b2f411cff 100644
--- a/test/fixtures/goldens/exports/runtime.json
+++ b/test/fixtures/goldens/exports/runtime.json
@@ -719,6 +719,7 @@
"releaseLock"
],
"./search/evidence-delivery": [
+ "DEFAULT_CONVERSATION_BUDGET",
"DEFAULT_REMOTE_BUDGET_MAX",
"DEFAULT_RETURN_BUDGET",
"EVIDENCE_BLOCK_CHAR_CAP",
@@ -726,6 +727,7 @@
"EVIDENCE_FETCH_TIMEOUT_MS",
"EVIDENCE_OMISSION",
"MAX_ASSEMBLE_HITS",
+ "RETURN_BUDGET_CONVERSATION_KEY",
"RETURN_BUDGET_DEFAULT_KEY",
"RETURN_BUDGET_MAX_REMOTE_KEY",
"RETURN_UNITS",
@@ -735,9 +737,11 @@
"TIMELINE_SEPARATOR",
"assembleEvidenceForHits",
"capDeliveredSnippets",
+ "conversationSignal",
"countEvidenceTokens",
"deliverEvidence",
"deliveryVersionSkewWarning",
+ "effectivePlan",
"evidenceFingerprint",
"evidenceTokenizer",
"isConversationLabels",
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index 4bdc6b479a..59972271c6 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -1288,7 +1288,7 @@
"chronicle_boost?: number | undefined",
"chunk_id: number",
"chunk_index: number",
- "chunk_source: \"compiled_truth\" | \"timeline\"",
+ "chunk_source: \"compiled_truth\" | \"timeline\" | \"fenced_code\"",
"chunk_text: string",
"content_flag?: { reason: string; detail: string; } | undefined",
"cosine?: number | undefined",
@@ -5988,6 +5988,20 @@
],
"name": "AssembleEvidenceOutput"
},
+ {
+ "kind": "type",
+ "name": "AutoReason",
+ "signature": [
+ "\"conversation_type\" | \"conversation_slug\" | \"not_conversation\" | \"conversation_over_budget\""
+ ]
+ },
+ {
+ "kind": "variable",
+ "name": "DEFAULT_CONVERSATION_BUDGET",
+ "signature": [
+ "24000"
+ ]
+ },
{
"kind": "variable",
"name": "DEFAULT_REMOTE_BUDGET_MAX",
@@ -6016,6 +6030,7 @@
"chunk_ids: number[]",
"fallback_reason?: string | undefined",
"match_spans: MatchSpan[]",
+ "reason?: AutoReason | undefined",
"revision?: string | undefined",
"tokens: number",
"truncated: boolean",
@@ -6133,6 +6148,13 @@
],
"name": "MatchSpan"
},
+ {
+ "kind": "variable",
+ "name": "RETURN_BUDGET_CONVERSATION_KEY",
+ "signature": [
+ "\"search.return_budget_conversation\""
+ ]
+ },
{
"kind": "variable",
"name": "RETURN_BUDGET_DEFAULT_KEY",
@@ -6173,6 +6195,7 @@
"members": [
"budget: unknown",
"configKey?: string | undefined",
+ "legacyBudget?: boolean | undefined",
"op: string",
"remote: boolean | undefined",
"returnUnit: unknown",
@@ -6218,6 +6241,13 @@
"<T extends SearchResult & { delivered?: DeliveredEvidence; }>(results: T[], cap: number, delivery: DeliveryMeta) => T[]"
]
},
+ {
+ "kind": "function",
+ "name": "conversationSignal",
+ "signature": [
+ "(hit: { type?: string | null; slug: string; }) => \"conversation_type\" | \"conversation_slug\" | null"
+ ]
+ },
{
"kind": "function",
"name": "countEvidenceTokens",
@@ -6239,6 +6269,13 @@
"(opName: string, params: Record<string, unknown>, retrievalMeta: Record<string, unknown> | null | undefined, result: unknown) => string | null"
]
},
+ {
+ "kind": "function",
+ "name": "effectivePlan",
+ "signature": [
+ "(plan: EvidencePlan | null, hits: SearchResult[]) => EvidencePlan | null"
+ ]
+ },
{
"kind": "function",
"name": "evidenceFingerprint",
@@ -7817,7 +7854,7 @@
"chronicle_boost?: number | undefined",
"chunk_id: number",
"chunk_index: number",
- "chunk_source: \"compiled_truth\" | \"timeline\"",
+ "chunk_source: \"compiled_truth\" | \"timeline\" | \"fenced_code\"",
"chunk_text: string",
"content_flag?: { reason: string; detail: string; } | undefined",
"cosine?: number | undefined",
diff --git a/test/helpers/evidence-delivery-fixture.ts b/test/helpers/evidence-delivery-fixture.ts
index c732694797..84356cfeef 100644
--- a/test/helpers/evidence-delivery-fixture.ts
+++ b/test/helpers/evidence-delivery-fixture.ts
@@ -2,6 +2,8 @@
* Shared fixture for the evidence-delivery off-path golden (PGLite unit arm
* and Postgres e2e arm). The captured bytes were generated on the release
* before evidence delivery; do not change the corpus or the captured calls.
+ * `chat/session-a` is the corpus's one conversation page (the `auto` default
+ * expands it); every other page is off the conversation path.
*/
import type { BrainEngine } from '../../src/core/engine.ts';
import { operations, type OperationContext } from '../../src/core/operations.ts';
@@ -74,8 +76,8 @@ export async function captureOffPath(engine: BrainEngine): Promise<Record<string
return out;
}
-export async function seedOffPath(engine: BrainEngine): Promise<void> {
- for (const p of OFF_PATH_PAGES) {
+export async function seedOffPath(engine: BrainEngine, pages = OFF_PATH_PAGES): Promise<void> {
+ for (const p of pages) {
await engine.putPage(p.slug, { type: 'note', title: p.slug, compiled_truth: p.body, timeline: p.timeline ?? '', frontmatter: p.frontmatter ?? {} });
await installFixtureChunks(engine, p.slug, await prepareMarkdownChunks({ compiled_truth: p.body, timeline: p.timeline ?? '' }));
}