Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(evidence): explicit token_budget is a hard cap under auto; three packings; frozen-hit effective_date

garrytan20eb1ed29b8f
diff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.md
index c03f2ec2f4..2b8d31c9df 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 (default `auto`: conversation pages by type or `chat/`/`conversations/` slug come back whole under `search.return_budget_conversation` (24,000), every other hit is its unchanged chunk; `effectivePlan` skips the stage when an implied `auto` sees no conversation hit, so that path and `chunk` stay byte-identical). `resolveEvidencePlan` validates `return_unit` / `return_window` (invalid_params naming the allowed values and an example), reads `search.return_unit` / `think.return_unit`, `search.return_window`, `search.return_budget_default` (6,000), `search.return_budget_conversation` (24,000) and clamps remote budgets to `search.return_budget_max_remote` (32,000, reported). Snippet precedence: explicit `snippet_chars` > explicit `return_unit` > subagent default cap > config unit. `deliverEvidence` groups hits by page_id (one block per page at its best rank), makes ONE `engine.getChunkWindows` call (re-authorizes every page; unauthorized pages are dropped, never served from hit text), builds the page text from the stored body sanitized whole and passed through `credentialSafeProjection` before slicing (`pageEvidenceText`: compiled truth + serializer timeline sentinel + timeline; frontmatter excluded; private-key spans become newline-padded `<REDACTED:private_key_pem>` tokens, the same text the chunkers cut from), locates the hit chunks in it (`locateChunks`: exact, then whitespace-insensitive, since the chunker trims and folds whitespace), cuts `window` / `section` (ATX headings outside code fences, or conversation rounds detected structurally, never by page type) / `page` / `auto` (fenced-code hits are placed by their code minus the chunker's synthesized header), counts tokens as the sum of per-line cl100k counts, reserves each page's matching span before enriching by rank, caps blocks at 60,000 characters, redacts secrets before final accounting, and returns NEW rows with `delivered` plus a `delivery` meta. 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 and passed through `credentialSafeProjection` before slicing (`pageEvidenceText`: compiled truth + serializer timeline sentinel + timeline; frontmatter excluded; private-key spans become newline-padded `<REDACTED:private_key_pem>` tokens, the same text the chunkers cut from), locates the hit chunks in it (`locateChunks`: exact, then whitespace-insensitive, since the chunker trims and folds whitespace), cuts `window` / `section` (ATX headings outside code fences, or conversation rounds detected structurally, never by page type) / `page` / `auto` (fenced-code hits are placed by their code minus the chunker's synthesized header), counts tokens as the sum of per-line cl100k counts, reserves each page's matching span before enriching by rank, caps blocks at 60,000 characters, redacts secrets before final accounting, and returns NEW rows with `delivered` plus a `delivery` meta. The plan records `budgetExplicit` (the caller passed the budget) and the resolved `packing` (`search.auto_packing` or the library override); `capEngaged` (unit `auto`, explicit budget, packing not `off`) routes allocation to `allocateCapped`: global rank one first (cut with `EVIDENCE_CUT_MARKER` when it alone exceeds the budget), the rank-order prefix of other non-conversation chunks that fits (rest `budget_note`), then conversations by `cap_only` (floors, then enrichment), `breadth_capped` (longest prefix whose title + floor + `return_window` target window fits; rest `breadth_cap`) or `depth_first` (each session grown in turn); nothing spills. `capEvidenceToBudget` recounts title + `chunk_text` at the final boundary (after redaction and `capDeliveredSnippets`, whose marker is paid from the row's own allocation) and rewrites `budget_used`. Without an explicit budget none of this runs and the bytes are the pre-cap path's. Fetch failure/timeout (5 s) falls back to the hit chunk only for live hits. `assembleEvidenceForHits` / op `assemble_evidence` deliver the exact evidence `query` returns for a frozen `(source_id, slug, chunk_id)` list, `effective_date` included (`applyEffectiveDate`, the live rows' normalizer); `evidenceFingerprint` hashes it (gbrain-evals E1/E3 parity). 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.
@@ -28,6 +28,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/search/vector-legacy-guard.ts` — one-release rollback for the #5824 statement change. `readVectorLegacyGuard(cfg, env)` reports the setting (`GBRAIN_VECTOR_LEGACY_GUARD` wins over `search.vector_legacy_guard`); `resolveVectorLegacyGuard(cfg)` latches it once per process for `hybrid/request.ts`, which passes `SearchOpts.vectorLegacyGuard` to the engines (they never read config), and prints `[gbrain] vector legacy guard active` to stderr once when on. A changed setting takes effect when the owning service restarts.
+- `src/core/search/evidence-packing.ts` — the explicit-budget packing surface of evidence delivery: `AUTO_PACKINGS` (`off`, `cap_only` default, `breadth_capped`, `depth_first`) for `search.auto_packing`, `MIN_EXPLICIT_AUTO_BUDGET` (32; an explicit `auto` budget below it, or non-finite, is refused with `invalid_params` naming it), `parseAutoPacking` (the library override, unknown values refused), `configPacking` (unknown stored values read as the default) and `autoPackingValueProblem` (the `config set` refusal wired through `search/config-values.ts`). Tests: `test/evidence-delivery.test.ts`.
- `src/core/search/hnsw-iterative-scan.ts` — the pgvector `hnsw.iterative_scan` mode for filtered vector search (#6132 idea): `relaxed_order` by default, `strict_order` or `off` through `GBRAIN_HNSW_ITERATIVE_SCAN` (wins) or `search.hnsw_iterative_scan` (file > DB via loadConfigWithEngine). `resolveHnswIterativeScan(cfg)` latches once per process (hybrid `request.ts` passes it as `SearchOpts.hnswIterativeScan`; engines hand it to `withVectorSettings`), logging once when an override is active. `hnswIterativeScanValueProblem` backs the `config set` refusal through `search/config-values.ts` (`searchConfigValueRefusal`: enum/range rules for `search.*` keys, exit 2 `invalid_params`, nothing written). Pinned by `test/search/hnsw-iterative-scan.test.ts` and the Postgres recall fixture `test/e2e/hnsw-iterative-scan-recall-postgres.test.ts`; bench `scripts/bench/hnsw-iterative-scan.ts`.
- `src/core/search/cjk-keyword-sql.ts` + `src/core/engine-sql/cjk-search.ts` + `src/core/search/cjk-keyword-deadline.ts` — the CJK keyword fallback shared by both engines. `buildCJKKeywordSql(query, ctx, variant)` keeps today's strict-AND SQL byte-identical by default; `match: 'any'` (the OR fallback, #6043) qualifies a chunk on any term and orders by matched-term count, then the TF score (the count enters the score as 1000 x matched outside the source factor, so a boosted partial match never outranks an all-term chunk); `candidateIds` scores only a candidate set by joining `unnest($n::bigint[])` to `content_chunks` (an `= ANY` filter was a sequential scan). `buildCJKCandidateSql` is the unordered capped LIKE scan for ids (all-term, or any-term excluding ids already taken). `searchKeywordCJK(scoped, query, ctx, engine)` runs strict AND and, with `opts.orFallback` and 2+ terms, the OR pass only when strict AND returns fewer than `limit` rows; with `opts.cjkKeyword` (hybrid only, deadline from `search.cjk_keyword_deadline_ms`, integer ms 500..30000, default 3000) it bounds the arm: Postgres runs full scoring in its own scoped read transaction within 2/3 of the deadline (counted from before the pool wait; every statement of an attempt gets `statement_timeout` = what is left of that attempt, minus a 40 ms rollback margin), and on SQLSTATE 57014 a capped retry (`CJK_CANDIDATE_CAP` = 2000; all-term ids first, partial ids only when the all-term rows fall short) in a fresh scoped transaction with the remaining third (a fresh transaction, not a savepoint, because the driver rethrows any failed statement at the end of its transaction scope); PGLite runs the capped stage whenever `pg_class.reltuples` exceeds `PGLITE_CJK_CAPPED_CHUNKS` = 50,000. `onMeta` gets `{ incomplete, reason (timeout | candidate_budget), capped, arm_ms }` (test seams: `candidateCap`, `pgliteCappedChunks`, `fullBudgetMs`); hybrid `request.ts` turns `incomplete` into degraded `keyword_candidates_incomplete` and `emitHybridMeta` adds `keyword_candidates` (keyword-arm wall time, separate from total hybrid latency) to every return path's meta. Pinned by `test/cjk-keyword-fallback.test.ts`, `test/e2e/cjk-keyword-deadline-postgres.test.ts` and `test/cjk-keyword-sql.test.ts`; bench `scripts/bench/cjk-keyword-deadline.ts`.
diff --git a/docs/evidence-delivery.md b/docs/evidence-delivery.md
index 04d6bc82df..b76a200088 100644
--- a/docs/evidence-delivery.md
+++ b/docs/evidence-delivery.md
@@ -30,12 +30,20 @@ conversation hit is byte-identical to earlier releases. `return_unit: "chunk"`
(or `gbrain config set search.return_unit chunk`) turns the stage off
entirely.
+A budget you pass under `auto` is a hard cap: everything delivered (titles,
+evidence text and every marker in it) fits inside it, on `query`, `search`,
+`recall`'s results and `assemble_evidence`. A call that passes no budget gets
+exactly what earlier releases returned. See [Explicit budgets](#explicit-budgets-the-cap).
+
**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."*
**Say to your agent:** *"Find every session where we discussed the acme-example
renewal and give me the full sessions within about 6,000 tokens."*
+**Say to your agent:** *"What did we decide about the widget-co launch? Keep the
+evidence under 8,000 tokens."*
+
## Quick start
```bash
@@ -78,6 +86,9 @@ Per-call params on `search`, `query`, `recall`:
`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.
+- An explicit budget under `auto` (`return_unit: "auto"`, or `auto` from config
+ on `search`) is a hard cap, packed by `search.auto_packing` (see
+ [Explicit budgets](#explicit-budgets-the-cap)); it must be at least 32 tokens.
- 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
@@ -90,7 +101,7 @@ excerpts for every other page.
Config keys: `search.return_unit`, `search.return_window`,
`search.return_budget_default`, `search.return_budget_conversation`,
-`search.return_budget_max_remote`, `think.return_unit`. Kill switch:
+`search.return_budget_max_remote`, `search.auto_packing`, `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).
@@ -114,13 +125,69 @@ Pages the transcripts and connectors paths write carry both signals (type
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.
+With no budget passed (the 24,000-token default), 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` without an
+explicit budget never returns less than `chunk` would, and `budget_used`
+exceeds `budget_tokens` only by such unchanged chunks. An explicit budget
+changes this; see the next section.
+
+### Explicit budgets (the cap)
+
+When the caller passes a budget (`token_budget` on `query`, `search` and
+`assemble_evidence`, `budget_tokens` on `recall`) and the unit is `auto`, the
+budget is a hard cap on the delivered evidence: the recount of every result's
+title plus `chunk_text` (the evidence, its omission lines, cut markers and
+snippet markers) never exceeds it. JSON fields outside those two (`delivered`,
+spans, scores, the `delivery` meta) are not counted. The four operations share
+one rule:
+
+1. **Rank one first.** The best-ranked hit, note or conversation, is reserved
+ first. If it alone exceeds the budget it is cut at a piece boundary (a
+ line, or a 400-character run of a long line) and ends with the cut marker
+ `\n\n[…]`; it is never dropped.
+2. **Notes get a prefix.** The other non-conversation chunks, in rank order,
+ are kept while they fit; the first that does not fit and every one after
+ it are dropped (`budget_note`). A lower-ranked note never crowds out a
+ leading conversation.
+3. **No spill.** A conversation that does not fit is dropped (`budget_floor`,
+ or `breadth_cap` under `breadth_capped`), never appended outside the
+ budget as chunks.
+4. **The cap holds at the final boundary.** Secret redaction and an explicit
+ `snippet_chars` run before the last recount. A snippet's recovery marker is
+ paid from the row's own allocation (the body shrinks to make room, or the
+ marker is left out with fallback `snippet_marker_omitted` when even it does
+ not fit). A row that would still cross the budget is cut with the marker,
+ or dropped as `budget_recount`. `budget_used` is that recount.
+
+How conversations share what is left is `search.auto_packing`:
+
+| Value | Conversations |
+|---|---|
+| `cap_only` (default) | Every conversation's matching span first, in rank order, then pages grow toward complete in rank order: the no-budget order, with the four rules above. |
+| `breadth_capped` | Keeps the longest rank-order prefix of conversations whose title, matching span and target window (the `window` unit's neighbor chunks at `return_window`) all fit; the rest are dropped as `breadth_cap`. What is left grows those pages toward complete, in rank order. |
+| `depth_first` | Takes conversations in rank order, each whole if it fits what is left, else as much around its matching span as fits; one whose matching span no longer fits is skipped, and later ones are still tried. |
+| `off` | The no-budget behavior, even with an explicit budget (unchanged chunks paid first, conversations that do not fit spill as chunks, no minimum). |
+
+`gbrain config set search.auto_packing <value>` refuses any other value.
+`delivery.auto_packing` names the packing that ran; it is present only when
+the cap engaged. The packing reads nothing but the plan, so `think` (which
+passes no budget) and every call without a budget are byte-identical whatever
+it is set to.
+
+The smallest explicit `auto` budget is **32 tokens** (room for a cut marker, a
+shortened title and a non-empty body). A smaller, zero, negative or
+non-finite budget fails with `invalid_params` naming the minimum; above it, a
+non-empty, readable hit list always returns non-empty evidence. A remote
+budget is clamped first (`search.return_budget_max_remote`), and the cap
+applies to the clamped value.
+
+`query`'s `token_budget` **without** `return_unit` still selects legacy chunk
+budgeting (and `recall`'s `budget_tokens` / `budget_policy` legacy packing),
+so a bare budget does not engage the cap.
### Precedence with `snippet_chars`
@@ -191,7 +258,8 @@ Response meta (`_meta.retrieval.delivery` over MCP; top-level `delivery` on
"dropped": 1, // hits/pages not delivered
"dropped_reasons": { "budget_floor": 1 },
"fallbacks": ["budget_clamped"], // distinct non-fatal problem codes, never silent
- "budget_clamped": { "requested": 50000, "max": 32000 }
+ "budget_clamped": { "requested": 50000, "max": 32000 },
+ "auto_packing": "cap_only" // explicit auto budgets only: the packing that ran
}
```
@@ -215,7 +283,11 @@ 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). Under `auto` nothing is dropped for budget: the conversation keeps its ranked chunks. |
+| `snippet_marker_omitted` | Under an explicit `auto` budget, a row's allocation could not hold the snippet recovery marker. | Capped block without the marker, `truncated: true`. |
+| drop `budget_floor` | Not even the block's matching span fits the remaining budget. | Result removed (rank one is instead cut to fit). Under `auto` without an explicit budget nothing is dropped for budget: the conversation keeps its ranked chunks. |
+| drop `budget_note` | Explicit `auto` budget: a non-conversation chunk after rank one did not fit, or came after one that did not. | Result removed. |
+| drop `breadth_cap` | `breadth_capped`: the conversation is past the prefix whose target windows fit. | Result removed. |
+| drop `budget_recount` | Explicit `auto` budget: the final recount (after redaction and snippet markers) left no room for the row's title and a body. | Result removed. |
## Errors
@@ -226,6 +298,13 @@ An unknown `return_unit` or an out-of-range `return_window` fails with
return_window must be an integer from 1 to 3 (got 7). Example: {"query": "launch date", "return_unit": "window", "return_window": 2}
```
+An explicit `auto` budget below 32 tokens (or zero, negative or non-finite)
+fails with `invalid_params`, e.g.
+
+```
+token_budget must be at least 32 tokens under return_unit auto (got 10): an explicit budget is a hard cap, and a smaller one cannot hold a title, a cut marker and any evidence.
+```
+
A thin client talking to an older server that ignores `return_unit` prints one
warning naming the minimum server version.
@@ -305,7 +384,12 @@ warning naming the minimum server version.
distance to the nearest hit piece, earlier position first on ties) until
the unit is complete or the budget is spent. Selected pieces are emitted in
document order; gaps become the omission line. The 60,000-character cap
- applies the same selection.
+ applies the same selection. Under an explicit `auto` budget the order is
+ [Explicit budgets](#explicit-budgets-the-cap): rank one, the note prefix,
+ then the packing's conversation rule; `breadth_capped` prices each
+ conversation as title + matching span + its `window` candidates at
+ `return_window` (pieces in priority order, omission lines counted) and
+ keeps the longest prefix that fits.
7. **Redact.** Blocks pass through the same secret redaction as every search
response before spans and tokens are computed.
@@ -354,18 +438,26 @@ 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 (the product default)
return_window: 1, // optional
- budget_tokens: 6000, // optional; same default/clamp rules as query
+ budget_tokens: 6000, // optional; same default/clamp rules as query (explicit: the cap under auto)
detail: 'medium', // optional, as query
caller: { remote: false }, // optional; { remote: true, sourceIds: [...] } emulates a remote caller
+ auto_packing: 'breadth_capped', // optional, library only: wins over search.auto_packing for this call
});
// out.results — the redacted result array (JSON-serializable), same objects the query op returns
// for these hits: { slug, source_id, page_id, title, type, chunk_id, chunk_index,
-// chunk_source, chunk_text, delivered, ... }
+// chunk_source, chunk_text, effective_date, effective_date_source, delivered, ... }
// out.delivery — the delivery meta block
// out.unresolved — hits that could not be resolved in the caller's scope (dropped)
const fp = evidenceFingerprint(out.results); // sha256 hex
```
+Each result carries the page's `effective_date` (`YYYY-MM-DD`) and
+`effective_date_source` exactly as the live `query` row does, `null` for a
+page without a date, so a frozen delivery hands a reader the same dates.
+`auto_packing` exists only on the library call (never an MCP parameter), so an
+evaluation can compare packings on one frozen hit list without switching the
+brain's config between calls.
+
`chunk_id: 0` addresses the page's first chunk (the synthetic rows exact-slug
and alias hits carry). Hits outside the caller's scope, deleted pages and
unknown chunk ids are dropped and listed in `unresolved` (by input index).
diff --git a/scripts/bench-evidence-delivery.ts b/scripts/bench-evidence-delivery.ts
index 1f607705c0..0d3464d420 100644
--- a/scripts/bench-evidence-delivery.ts
+++ b/scripts/bench-evidence-delivery.ts
@@ -145,7 +145,7 @@ async function main() {
};
},
}) as BrainEngine;
- const plan = (unit: EvidencePlan['unit']): EvidencePlan => ({ requestedUnit: unit, unit, window: 1, budgetTokens: BUDGET, explicitUnit: true });
+ const plan = (unit: EvidencePlan['unit']): EvidencePlan => ({ requestedUnit: unit, unit, window: 1, budgetTokens: BUDGET, explicitUnit: true, budgetExplicit: false, packing: 'cap_only' });
const scope = { excludePrivate: true, requireSafeChunks: true };
const results: Record<string, unknown>[] = [];
const large = pages.filter(p => p.kind === 'large');
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 2c366a6794..ed3df6ed94 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -36,7 +36,7 @@ src/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0
src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refresh
src/commands/hook.ts 1926 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + import; +2 fix wave 11 integration: W1 router help guard import beside the W2 managed-root import
src/core/chunkers/code.ts 1588 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts)
-src/core/config.ts 1923 ratchet +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts)
+src/core/config.ts 1924 ratchet +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts)
src/core/bootstrap/harness.ts 2610 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts)
src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option
src/core/ops/pages.ts 675 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts)
diff --git a/src/core/config.ts b/src/core/config.ts
index f9cf377ea1..f949e019af 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1405,6 +1405,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
'search.return_budget_default',
'search.return_budget_conversation',
'search.return_budget_max_remote',
+ 'search.auto_packing',
'think.return_unit',
// Models tier system (v0.31.12)
'models.default',
diff --git a/src/core/ops/search.ts b/src/core/ops/search.ts
index bf010a07ab..ca2da3a35c 100644
--- a/src/core/ops/search.ts
+++ b/src/core/ops/search.ts
@@ -31,7 +31,7 @@ import { redactRetrievalOutput } from '../search/output-redaction.ts';
import { projectRows, resultRowsFor } from '../search/lean-rows.ts';
import { buildScoreDetails } from '../search/explain-formatter.ts';
import { TargetTrace, diagnoseProbe, diagnoseTrace, probeTarget, type ExplainTargetDiagnosis } from '../search/explain-target.ts';
-import { assembleEvidenceForHits, capDeliveredSnippets, deliverEvidence, effectivePlan, resolveEvidencePlan, unsupportedDelivery, type DeliveryMeta, type DeliveryScope, type EvidencePlan, type FrozenHit, type ReturnUnit } from '../search/evidence-delivery.ts';
+import { assembleEvidenceForHits, capDeliveredSnippets, capEvidenceToBudget, deliverEvidence, effectivePlan, resolveEvidencePlan, unsupportedDelivery, type DeliveryMeta, type DeliveryScope, type EvidencePlan, type FrozenHit, type ReturnUnit } from '../search/evidence-delivery.ts';
import { privateProvenanceFilterFragment, resolveExcludePrivatePages } from '../search/private-visibility.ts';
import { AUDIT_ROW_SOURCES } from '../facts/audit-sources.ts';
import { SAFE_FENCE_CHUNKER_VERSION } from '../search/safe-chunks.ts';
@@ -98,7 +98,9 @@ function searchOutput(ctx: OperationContext, p: Record<string, unknown>, results
// otherwise the blocks are returned whole (their budget already bounds
// them). The cap runs before the meta is emitted so it can report itself.
const output = redactRetrievalOutput(results, { ...meta, delivery: evidence.delivery, ...shown });
- const capped = evidence.explicitSnippet ? capDeliveredSnippets(output.results, snippetCap, output.meta.delivery) : output.results;
+ // An explicit budget's cap holds at this final boundary too (snippet
+ // markers and redaction recounted); without one both are no-ops.
+ const capped = evidence.explicitSnippet ? capDeliveredSnippets(output.results, snippetCap, output.meta.delivery) : capEvidenceToBudget(output.results, output.meta.delivery);
ctx.emitResponseMeta?.('retrieval', output.meta);
return projectRows(capped, rows);
}
diff --git a/src/core/search/config-values.ts b/src/core/search/config-values.ts
index cb48c117be..476b0c7e0e 100644
--- a/src/core/search/config-values.ts
+++ b/src/core/search/config-values.ts
@@ -5,6 +5,7 @@
*/
import { HNSW_ITERATIVE_SCAN_KEY, HNSW_ITERATIVE_SCAN_MODES, hnswIterativeScanValueProblem } from './hnsw-iterative-scan.ts';
import { CJK_KEYWORD_DEADLINE_DEFAULT_MS, CJK_KEYWORD_DEADLINE_KEY, cjkKeywordDeadlineValueProblem } from './cjk-keyword-deadline.ts';
+import { AUTO_PACKING_CONFIG_KEY, DEFAULT_AUTO_PACKING, autoPackingValueProblem } from './evidence-packing.ts';
interface SearchValueRule {
problem: (value: string) => string | null;
@@ -15,6 +16,7 @@ interface SearchValueRule {
export const SEARCH_VALUE_RULES: Readonly<Record<string, SearchValueRule>> = {
[HNSW_ITERATIVE_SCAN_KEY]: { problem: hnswIterativeScanValueProblem, example: HNSW_ITERATIVE_SCAN_MODES[0] },
[CJK_KEYWORD_DEADLINE_KEY]: { problem: cjkKeywordDeadlineValueProblem, example: String(CJK_KEYWORD_DEADLINE_DEFAULT_MS) },
+ [AUTO_PACKING_CONFIG_KEY]: { problem: autoPackingValueProblem, example: DEFAULT_AUTO_PACKING },
};
/** The refusal for an invalid value of a validated `search.*` key, or null. */
diff --git a/src/core/search/evidence-delivery.ts b/src/core/search/evidence-delivery.ts
index 92c60f569c..c99ddc772f 100644
--- a/src/core/search/evidence-delivery.ts
+++ b/src/core/search/evidence-delivery.ts
@@ -34,6 +34,10 @@ import { sanitizeRemoteBody } from '../remote-body.ts';
import { credentialSafeProjection } from '../credential-projection.ts';
import { stripChunkHeader } from '../chunkers/code.ts';
import { OperationError } from '../ops/contract.ts';
+import { applyEffectiveDate } from '../utils.ts';
+import { configPacking, MIN_EXPLICIT_AUTO_BUDGET, parseAutoPacking, type AutoPacking } from './evidence-packing.ts';
+
+export { AUTO_PACKINGS, AUTO_PACKING_CONFIG_KEY, DEFAULT_AUTO_PACKING, MIN_EXPLICIT_AUTO_BUDGET, autoPackingValueProblem, parseAutoPacking, type AutoPacking } from './evidence-packing.ts';
export const RETURN_UNITS = ['chunk', 'window', 'section', 'page', 'auto'] as const;
export type ReturnUnit = typeof RETURN_UNITS[number];
@@ -55,6 +59,11 @@ 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';
+/** Ends a block or chunk the cap cut short (the omission line, as emitted at a block's end). */
+export const EVIDENCE_CUT_MARKER = EVIDENCE_OMISSION.trimEnd();
+/** Body tokens a cut always keeps: a cut title never takes them. */
+const CUT_BODY_MIN = 8;
+
const PIECE_MAX_CHARS = 400;
const MAX_ROWS = 1024;
const MAX_WINDOW = 3;
@@ -96,6 +105,8 @@ export interface DeliveryMeta {
dropped_reasons: Record<string, number>;
fallbacks: string[];
budget_clamped?: { requested: number; max: number };
+ /** Present only when an explicit budget engaged the cap: the packing that ran. */
+ auto_packing?: AutoPacking;
}
export type DeliveredSearchResult = SearchResult & { delivered: DeliveredEvidence };
@@ -107,9 +118,18 @@ export interface EvidencePlan {
budgetTokens: number;
/** return_unit came from the call, not config (snippet precedence). */
explicitUnit: boolean;
+ /** The caller passed the budget; a config or default budget never engages the cap. */
+ budgetExplicit: boolean;
+ /** search.auto_packing (or the library override), resolved once; allocation never rereads config. */
+ packing: AutoPacking;
budgetClamped?: { requested: number; max: number };
}
+/** The cap runs only under `auto`, with a budget the caller passed and a packing other than `off`. */
+export function capEngaged(plan: EvidencePlan): boolean {
+ return plan.unit === 'auto' && plan.budgetExplicit && plan.packing !== 'off';
+}
+
export interface DeliveryScope extends PageReadScope {
detail?: 'low' | 'medium' | 'high';
}
@@ -175,6 +195,8 @@ export interface ResolvePlanInput {
* keeps its meaning.
*/
legacyBudget?: boolean;
+ /** Library-only per-call packing (gbrain-evals); wins over search.auto_packing. Never an MCP param. */
+ autoPacking?: unknown;
}
/**
@@ -200,6 +222,19 @@ export async function resolveEvidencePlan(engine: BrainEngine, input: ResolvePla
if (input.legacyBudget === true) unit = 'chunk';
}
if (unit === 'chunk') return null;
+ const budgetExplicit = typeof input.budget === 'number';
+ const packing = parseAutoPacking(input.autoPacking) ?? await configPacking(engine);
+ if (unit === 'auto' && budgetExplicit && packing !== 'off') {
+ const raw = input.budget as number;
+ if (!Number.isFinite(raw) || Math.floor(raw) < MIN_EXPLICIT_AUTO_BUDGET) {
+ const name = input.op === 'recall' ? 'budget_tokens' : 'token_budget';
+ throw new OperationError(
+ 'invalid_params',
+ `${name} must be at least ${MIN_EXPLICIT_AUTO_BUDGET} tokens under return_unit auto (got ${String(raw)}): an explicit budget is a hard cap, and a smaller one cannot hold a title, a cut marker and any evidence.`,
+ `${exampleCall(input.op, 'auto', `, "${name}": ${MIN_EXPLICIT_AUTO_BUDGET * 50}`)}. Omit ${name} for the default budget.`,
+ );
+ }
+ }
let window = explicitWindow ?? 1;
if (explicitWindow === undefined) {
const w = await configNumber(engine, RETURN_WINDOW_CONFIG_KEY);
@@ -225,6 +260,8 @@ export async function resolveEvidencePlan(engine: BrainEngine, input: ResolvePla
window,
budgetTokens: budget,
explicitUnit: explicit !== undefined,
+ budgetExplicit,
+ packing,
...(budgetClamped ? { budgetClamped } : {}),
};
}
@@ -258,11 +295,12 @@ export function conversationSignal(hit: { type?: string | null; slug: string }):
/**
* 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.
+ * conversations stay byte-identical. An explicit `auto`, or an `auto` under
+ * an explicit budget the cap enforces, 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;
+ if (!plan || plan.unit !== 'auto' || plan.explicitUnit || capEngaged(plan)) return plan;
return hits.some(h => conversationSignal(h) !== null) ? plan : null;
}
@@ -485,9 +523,11 @@ interface Block {
/** Index of the block's best hit in the ranked input. */
rank: number;
reason?: AutoReason;
+ /** The cap cut this block: its text ends with EVIDENCE_CUT_MARKER. */
+ capMarker?: boolean;
}
-type PlannedBlock = Omit<Block, 'titleTok' | 'title' | 'rank' | 'reason'>;
+type PlannedBlock = Omit<Block, 'titleTok' | 'title' | 'rank' | 'reason' | 'capMarker'>;
/**
* The hit's text as it appears in the page: a fenced_code chunk carries the
@@ -673,6 +713,62 @@ function enrichmentOrder(b: Block): number[] {
});
}
+/** Rank one alone exceeds the budget: cut its title to `titleMax`, then keep core pieces (slicing the first) to fit. */
+function cutToFit(b: Block, remaining: number, titleMax: number, tokenizer: 'cl100k' | 'heuristic'): number {
+ const core = b.anchors[0]?.pieces ?? [];
+ if (b.titleTok > titleMax) {
+ b.title = sliceToTokenCount(b.title, titleMax, tokenizer);
+ b.titleTok = countEvidenceTokens(b.title, tokenizer);
+ }
+ remaining -= b.titleTok;
+ let chars = 0;
+ for (const i of core) {
+ const t = tok(b, i, tokenizer);
+ const len = b.doc.pieces[i].text.length;
+ if (t <= remaining && chars + len <= EVIDENCE_BLOCK_CHAR_CAP) {
+ b.selected.add(i);
+ remaining -= t;
+ chars += len;
+ continue;
+ }
+ if (b.selected.size === 0) {
+ const p = b.doc.pieces[i];
+ p.text = sliceToTokenCount(p.text.slice(0, EVIDENCE_BLOCK_CHAR_CAP), remaining, tokenizer);
+ p.end = p.start + p.text.length;
+ p.tok = pieceTokens(p.text, tokenizer);
+ b.selected.add(i);
+ remaining -= p.tok;
+ }
+ break;
+ }
+ b.cut = true;
+ return remaining;
+}
+
+/** Grow a kept block in enrichment order until the next piece does not fit; returns what is left. */
+function enrichBlock(b: Block, remaining: number, tokenizer: 'cl100k' | 'heuristic', omitTok: number): number {
+ let chars = [...b.selected].reduce((n, i) => n + b.doc.pieces[i].text.length, 0);
+ for (const i of enrichmentOrder(b)) {
+ if (b.selected.has(i)) continue;
+ const adj = adjacent(b, i);
+ const cost = tok(b, i, tokenizer) + (adj ? 0 : omitTok);
+ const len = b.doc.pieces[i].text.length + (adj ? 0 : EVIDENCE_OMISSION.length);
+ if (cost > remaining || chars + len > EVIDENCE_BLOCK_CHAR_CAP) break;
+ b.selected.add(i);
+ remaining -= cost;
+ chars += len;
+ }
+ return remaining;
+}
+
+function floorOf(b: Block, tokenizer: 'cl100k' | 'heuristic'): { tokens: number; chars: number } {
+ const core = b.anchors[0]?.pieces ?? [];
+ return {
+ tokens: b.titleTok + core.reduce((n, i) => n + tok(b, i, tokenizer), 0),
+ chars: core.reduce((n, i) => n + b.doc.pieces[i].text.length, 0),
+ };
+}
+
/**
* 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.
@@ -684,43 +780,17 @@ function allocate(blocks: Block[], budget: number, tokenizer: 'cl100k' | 'heuris
let droppedAny = false;
for (const b of blocks) {
const core = b.anchors[0]?.pieces ?? [];
- const floor = b.titleTok + core.reduce((n, i) => n + tok(b, i, tokenizer), 0);
- const floorChars = core.reduce((n, i) => n + b.doc.pieces[i].text.length, 0);
- if (floor <= remaining && floorChars <= EVIDENCE_BLOCK_CHAR_CAP) {
+ const floor = floorOf(b, tokenizer);
+ if (floor.tokens <= remaining && floor.chars <= EVIDENCE_BLOCK_CHAR_CAP) {
for (const i of core) b.selected.add(i);
- remaining -= floor;
+ remaining -= floor.tokens;
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) {
- b.title = sliceToTokenCount(b.title, remaining, tokenizer);
- b.titleTok = countEvidenceTokens(b.title, tokenizer);
- }
- remaining -= b.titleTok;
- let chars = 0;
- for (const i of core) {
- const t = tok(b, i, tokenizer);
- const len = b.doc.pieces[i].text.length;
- if (t <= remaining && chars + len <= EVIDENCE_BLOCK_CHAR_CAP) {
- b.selected.add(i);
- remaining -= t;
- chars += len;
- continue;
- }
- if (b.selected.size === 0) {
- const p = b.doc.pieces[i];
- p.text = sliceToTokenCount(p.text.slice(0, EVIDENCE_BLOCK_CHAR_CAP), remaining, tokenizer);
- p.end = p.start + p.text.length;
- p.tok = pieceTokens(p.text, tokenizer);
- b.selected.add(i);
- remaining -= p.tok;
- }
- break;
- }
- b.cut = true;
+ remaining = cutToFit(b, remaining, remaining, tokenizer);
kept.push(b);
continue;
}
@@ -729,20 +799,143 @@ function allocate(blocks: Block[], budget: number, tokenizer: 'cl100k' | 'heuris
}
for (const b of kept) {
if (b.cut) continue;
- let chars = [...b.selected].reduce((n, i) => n + b.doc.pieces[i].text.length, 0);
- for (const i of enrichmentOrder(b)) {
- const adj = adjacent(b, i);
- const cost = tok(b, i, tokenizer) + (adj ? 0 : omitTok);
- const len = b.doc.pieces[i].text.length + (adj ? 0 : EVIDENCE_OMISSION.length);
- if (cost > remaining || chars + len > EVIDENCE_BLOCK_CHAR_CAP) break;
- b.selected.add(i);
- remaining -= cost;
- chars += len;
- }
+ remaining = enrichBlock(b, remaining, tokenizer, omitTok);
}
return kept;
}
+/** A non-conversation hit under `auto`: its ranked chunk, or a cut prefix of it under the cap. */
+interface ChunkItem { rank: number; hit: SearchResult; reason: AutoReason; title: string; text: string; cut: boolean }
+
+/** A selection as emit writes it: the pieces plus one omission line per gap. */
+function selectionCost(b: Block, sel: Set<number>, tokenizer: 'cl100k' | 'heuristic', omitTok: number): { tokens: number; chars: number } {
+ const order = [...sel].sort((x, y) => x - y);
+ let tokens = 0;
+ let chars = 0;
+ order.forEach((i, k) => {
+ const gap = k > 0 && order[k - 1] !== i - 1;
+ tokens += tok(b, i, tokenizer) + (gap ? omitTok : 0);
+ chars += b.doc.pieces[i].text.length + (gap ? EVIDENCE_OMISSION.length : 0);
+ });
+ return { tokens, chars };
+}
+
+/**
+ * The cap (explicit budget under `auto`, docs/evidence-delivery.md
+ * "Explicit budgets"): global rank one first, cut to fit if it alone exceeds
+ * the budget; then the rank-order prefix of the other non-conversation chunks
+ * that fits; then conversations by the plan's packing. Nothing is spilled
+ * outside the budget; what does not fit is counted in `dropped`.
+ */
+function allocateCapped(blocks: Block[], chunks: ChunkItem[], plan: EvidencePlan, tokenizer: 'cl100k' | 'heuristic', dropped: Record<string, number>): { kept: Block[]; chunks: ChunkItem[] } {
+ const omitTok = pieceTokens(EVIDENCE_OMISSION, tokenizer);
+ const cutTok = countEvidenceTokens(EVIDENCE_CUT_MARKER, tokenizer);
+ const drop = (reason: string) => { dropped[reason] = (dropped[reason] ?? 0) + 1; };
+ const chunkCost = (c: ChunkItem) => countEvidenceTokens(c.title, tokenizer) + countEvidenceTokens(c.text, tokenizer);
+ let remaining = plan.budgetTokens;
+ const keptChunks: ChunkItem[] = [];
+ const kept: Block[] = [];
+ let lead: Block | null = null;
+
+ const firstChunk = chunks[0];
+ const firstBlock = blocks[0];
+ let rest = chunks;
+ let others = blocks;
+ if (firstChunk && (!firstBlock || firstChunk.rank < firstBlock.rank)) {
+ rest = chunks.slice(1);
+ const cost = chunkCost(firstChunk);
+ if (cost <= remaining) remaining -= cost;
+ else {
+ const room = remaining - cutTok;
+ let title = firstChunk.title;
+ if (countEvidenceTokens(title, tokenizer) > room - CUT_BODY_MIN) title = sliceToTokenCount(title, Math.max(0, room - CUT_BODY_MIN), tokenizer);
+ const bodyRoom = room - countEvidenceTokens(title, tokenizer);
+ const source = firstChunk.text.slice(0, EVIDENCE_BLOCK_CHAR_CAP);
+ let end = 0;
+ let used = 0;
+ for (const piece of splitPieces(source)) {
+ const t = pieceTokens(source.slice(piece.start, piece.end), tokenizer);
+ if (used + t > bodyRoom) break;
+ used += t;
+ end = piece.end;
+ }
+ const body = end > 0 ? source.slice(0, end).replace(/\s+$/, '') : sliceToTokenCount(source, Math.max(0, bodyRoom), tokenizer);
+ Object.assign(firstChunk, { title, text: body + EVIDENCE_CUT_MARKER, cut: true });
+ remaining -= chunkCost(firstChunk);
+ }
+ keptChunks.push(firstChunk);
+ } else if (firstBlock) {
+ others = blocks.slice(1);
+ const floor = floorOf(firstBlock, tokenizer);
+ if (floor.tokens <= remaining && floor.chars <= EVIDENCE_BLOCK_CHAR_CAP) {
+ for (const i of firstBlock.anchors[0]?.pieces ?? []) firstBlock.selected.add(i);
+ remaining -= floor.tokens;
+ lead = firstBlock;
+ } else {
+ remaining = cutToFit(firstBlock, remaining - cutTok, Math.max(0, remaining - cutTok - CUT_BODY_MIN), tokenizer);
+ firstBlock.capMarker = true;
+ }
+ kept.push(firstBlock);
+ }
+
+ let stopped = false;
+ for (const c of rest) {
+ const cost = chunkCost(c);
+ if (!stopped && cost <= remaining) { remaining -= cost; keptChunks.push(c); continue; }
+ stopped = true;
+ drop('budget_note');
+ }
+
+ const reserveFloor = (b: Block): boolean => {
+ const floor = floorOf(b, tokenizer);
+ if (floor.tokens > remaining || floor.chars > EVIDENCE_BLOCK_CHAR_CAP) return false;
+ for (const i of b.anchors[0]?.pieces ?? []) b.selected.add(i);
+ remaining -= floor.tokens;
+ return true;
+ };
+
+ if (plan.packing === 'depth_first') {
+ if (lead) remaining = enrichBlock(lead, remaining, tokenizer, omitTok);
+ for (const b of others) {
+ if (!reserveFloor(b)) { drop('budget_floor'); continue; }
+ kept.push(b);
+ remaining = enrichBlock(b, remaining, tokenizer, omitTok);
+ }
+ } else if (plan.packing === 'breadth_capped') {
+ // k: the longest rank-order prefix of conversations whose title, floor
+ // and target window (the window unit's candidates at return_window) fit.
+ let capped = false;
+ for (const b of lead ? [lead, ...others] : others) {
+ if (capped) { drop('breadth_cap'); continue; }
+ const window = new Set(windowCandidates(b.doc, b.anchors, plan.window));
+ const target = new Set(b.anchors[0]?.pieces ?? []);
+ for (const i of enrichmentOrder(b)) {
+ if (!window.has(i)) continue;
+ target.add(i);
+ if (selectionCost(b, target, tokenizer, omitTok).chars > EVIDENCE_BLOCK_CHAR_CAP) { target.delete(i); break; }
+ }
+ const sel = selectionCost(b, target, tokenizer, omitTok);
+ const cost = b.titleTok + sel.tokens - (b === lead ? floorOf(b, tokenizer).tokens : 0);
+ if (cost <= remaining && sel.chars <= EVIDENCE_BLOCK_CHAR_CAP) {
+ for (const i of target) b.selected.add(i);
+ remaining -= cost;
+ if (b !== lead) kept.push(b);
+ continue;
+ }
+ capped = true;
+ if (b !== lead) drop('breadth_cap');
+ }
+ for (const b of kept) if (!b.cut) remaining = enrichBlock(b, remaining, tokenizer, omitTok);
+ } else {
+ for (const b of others) {
+ if (reserveFloor(b)) kept.push(b);
+ else drop('budget_floor');
+ }
+ for (const b of kept) if (!b.cut) remaining = enrichBlock(b, remaining, tokenizer, omitTok);
+ }
+ return { kept, chunks: keptChunks };
+}
+
function emit(b: Block, tokenizer: 'cl100k' | 'heuristic'): { text: string; spans: MatchSpan[]; unmapped: number[]; tokens: number } {
const order = [...b.selected].sort((x, y) => x - y);
const emitStart = new Map<number, number>();
@@ -891,35 +1084,98 @@ export async function deliverEvidence(
planned.push({ ...b, title, titleTok: countEvidenceTokens(title, tokenizer), rank: g.rank, ...(g.reason ? { reason: g.reason } : {}) });
}
- // 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);
+ const capped = capEngaged(plan);
+ let kept: Block[];
+ let chunkItems: ChunkItem[] = [];
+ if (capped) {
+ ({ kept, chunks: chunkItems } = allocateCapped(planned,
+ passthrough.map(p => ({ ...p, title: p.hit.title ?? '', text: p.hit.chunk_text ?? '', cut: false })), plan, tokenizer, dropped));
+ } else {
+ // 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);
+ 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 text = b.capMarker ? out.text + EVIDENCE_CUT_MARKER : out.text;
const truncated = b.cut || b.selected.size < b.candidates.length;
const delivered: DeliveredEvidence = {
unit: b.unit,
chunk_ids: b.hits.map(h => h.chunk_id),
match_spans: out.spans,
- tokens: out.tokens,
+ tokens: b.capMarker ? countEvidenceTokens(text, tokenizer) : out.tokens,
truncated,
...(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 };
+ return { ...b.hit, title: b.title, chunk_text: text, delivered };
});
- // Budget after redaction: blocks pass through the same secret redaction as
- // every search response before spans and tokens are final. A block the
- // redactor changed loses its spans (explicit unmapped state) and is
- // re-counted, never allowed to grow past its allocation.
+ // Under the cap the kept chunks join before redaction, so every evidence
+ // field is redacted and recounted inside the budget.
+ if (capped) {
+ const ranked = results.map((r, i) => ({ rank: kept[i].rank, r }));
+ for (const c of chunkItems) ranked.push({ rank: c.rank, r: chunkResult(c, tokenizer) });
+ results = ranked.sort((a, b) => a.rank - b.rank).map(x => x.r);
+ }
+ results = redactDelivered(results, tokenizer, fallbacks);
+
+ if (!capped && passthrough.length > 0) {
+ const ranked = results.map((r, i) => ({ rank: kept[i].rank, r }));
+ for (const p of passthrough) ranked.push({ rank: p.rank, r: chunkResult({ ...p, title: p.hit.title ?? '', text: p.hit.chunk_text ?? '', cut: false }, tokenizer) });
+ 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);
+ const delivery: DeliveryMeta = {
+ requested_unit: plan.requestedUnit,
+ applied_unit: fetchFailure ? 'chunk' : plan.unit,
+ return_window: plan.window,
+ budget_tokens: plan.budgetTokens,
+ budget_used: budgetUsed,
+ tokens_delivered: tokensDelivered,
+ tokenizer,
+ coordinates: 'utf16',
+ blocks: results.length,
+ dropped: droppedTotal,
+ dropped_reasons: dropped,
+ fallbacks: [...fallbacks].sort(),
+ ...(plan.budgetClamped ? { budget_clamped: plan.budgetClamped } : {}),
+ ...(capped ? { auto_packing: plan.packing } : {}),
+ };
+ return { results: capped ? capEvidenceToBudget(results, delivery) : results, delivery };
+}
+
+/** A non-conversation hit's delivered row: the ranked chunk unchanged, or the cap's cut prefix of it. */
+function chunkResult(c: ChunkItem, tokenizer: 'cl100k' | 'heuristic'): DeliveredSearchResult {
+ const text = c.cut ? c.text : c.hit.chunk_text ?? '';
+ const matched = c.cut ? text.length - EVIDENCE_CUT_MARKER.length : text.length;
+ return { ...c.hit, ...(c.cut ? { title: c.title, chunk_text: text } : {}), delivered: {
+ unit: 'chunk',
+ chunk_ids: [c.hit.chunk_id],
+ match_spans: matched > 0 ? [{ chunk_id: c.hit.chunk_id, start: 0, end: matched }] : [],
+ tokens: countEvidenceTokens(text, tokenizer),
+ truncated: c.cut,
+ reason: c.reason,
+ } };
+}
+
+/**
+ * Budget after redaction: blocks pass through the same secret redaction as
+ * every search response before spans and tokens are final. A block the
+ * redactor changed loses its spans (explicit unmapped state) and is
+ * re-counted, never allowed to grow past its allocation.
+ */
+function redactDelivered(results: DeliveredSearchResult[], tokenizer: 'cl100k' | 'heuristic', fallbacks: Set<string>): DeliveredSearchResult[] {
const redacted = redactRetrievalOutput(results, {}).results;
- results = results.map((r, i) => {
+ return results.map((r, i) => {
const rr = redacted[i];
if (rr.chunk_text === r.chunk_text && rr.title === r.title) return r;
fallbacks.add('redaction_unmapped');
@@ -940,44 +1196,55 @@ 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,
- } } });
+/**
+ * The cap's final evidence boundary: recount every row's evidence fields
+ * (title and chunk_text, with every marker in it) and keep the rank-order
+ * rows that fit `budget_tokens`. A row that would cross it is cut with
+ * EVIDENCE_CUT_MARKER when a body still fits (rank one always is), otherwise
+ * dropped as `budget_recount`. `budget_used`, `tokens_delivered`, `blocks`
+ * and `dropped` are rewritten from the recount. Runs only when the delivery
+ * carries `auto_packing`; everything else is returned as is.
+ */
+export function capEvidenceToBudget<T extends SearchResult & { delivered?: DeliveredEvidence }>(results: T[], delivery: DeliveryMeta): T[] {
+ if (!delivery.auto_packing) return results;
+ const tokenizer = delivery.tokenizer;
+ const count = (text: string | undefined) => countEvidenceTokens(text ?? '', tokenizer);
+ const cutTok = count(EVIDENCE_CUT_MARKER);
+ let remaining = delivery.budget_tokens;
+ let lost = 0;
+ const out: T[] = [];
+ for (const r of results) {
+ const titleTok = count(r.title);
+ const textTok = count(r.chunk_text);
+ if (titleTok + textTok <= remaining) {
+ remaining -= titleTok + textTok;
+ out.push(!r.delivered || r.delivered.tokens === textTok ? r : { ...r, delivered: { ...r.delivered, tokens: textTok } });
+ continue;
}
- results = ranked.sort((a, b) => a.rank - b.rank).map(x => x.r);
+ if (out.length > 0 && remaining - titleTok - cutTok < CUT_BODY_MIN) { lost++; continue; }
+ const title = titleTok > Math.max(0, remaining - cutTok - CUT_BODY_MIN) ? sliceToTokenCount(r.title ?? '', Math.max(0, remaining - cutTok - CUT_BODY_MIN), tokenizer) : r.title ?? '';
+ const source = (r.chunk_text ?? '').endsWith(EVIDENCE_CUT_MARKER) ? (r.chunk_text ?? '').slice(0, -EVIDENCE_CUT_MARKER.length) : r.chunk_text ?? '';
+ const body = sliceToTokenCount(source, Math.max(0, remaining - count(title) - cutTok), tokenizer).replace(/\s+$/, '');
+ const text = body + EVIDENCE_CUT_MARKER;
+ remaining -= count(title) + count(text);
+ const row = { ...r, title, chunk_text: text } as T;
+ if (r.delivered) {
+ const spans = r.delivered.match_spans.filter(s => s.start < body.length).map(s => ({ ...s, end: Math.min(s.end, body.length) }));
+ const unmapped = [...new Set([...(r.delivered.unmapped_chunk_ids ?? []), ...r.delivered.match_spans.map(s => s.chunk_id).filter(id => !spans.some(s => s.chunk_id === id))])];
+ row.delivered = { ...r.delivered, match_spans: spans, tokens: count(text), truncated: true, ...(unmapped.length > 0 ? { unmapped_chunk_ids: unmapped } : {}) };
+ }
+ out.push(row);
}
-
- 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);
- return {
- results,
- delivery: {
- requested_unit: plan.requestedUnit,
- applied_unit: fetchFailure ? 'chunk' : plan.unit,
- return_window: plan.window,
- budget_tokens: plan.budgetTokens,
- budget_used: budgetUsed,
- tokens_delivered: tokensDelivered,
- tokenizer,
- coordinates: 'utf16',
- blocks: results.length,
- dropped: droppedTotal,
- dropped_reasons: dropped,
- fallbacks: [...fallbacks].sort(),
- ...(plan.budgetClamped ? { budget_clamped: plan.budgetClamped } : {}),
- },
- };
+ if (lost > 0) {
+ delivery.dropped_reasons = { ...delivery.dropped_reasons, budget_recount: (delivery.dropped_reasons.budget_recount ?? 0) + lost };
+ delivery.dropped += lost;
+ }
+ delivery.blocks = out.length;
+ delivery.tokens_delivered = out.reduce((n, r) => n + (r.delivered?.tokens ?? count(r.chunk_text)), 0);
+ delivery.budget_used = delivery.tokens_delivered + out.reduce((n, r) => n + count(r.title), 0);
+ return out;
}
/**
@@ -993,13 +1260,28 @@ export function capDeliveredSnippets<T extends SearchResult & { delivered?: Deli
if (!Number.isFinite(cap) || cap <= 0) return results;
let any = false;
const tokenizer = delivery.tokenizer;
+ let markerOmitted = false;
const out = results.map(r => {
if (typeof r.chunk_text !== 'string' || r.chunk_text.length <= cap) return r;
any = true;
- const text = r.chunk_text.slice(0, cap) + buildSnippetMarker(r.slug, r.chunk_text.length - cap);
+ let keep = cap;
+ let text = r.chunk_text.slice(0, cap) + buildSnippetMarker(r.slug, r.chunk_text.length - cap);
+ if (delivery.auto_packing) {
+ // Under the cap the marker is paid from the row's own allocation: a
+ // capped row never grows past what it held before the snippet cap.
+ const allowed = countEvidenceTokens(r.chunk_text, tokenizer);
+ if (countEvidenceTokens(text, tokenizer) > allowed) {
+ const markerTok = countEvidenceTokens(buildSnippetMarker(r.slug, r.chunk_text.length), tokenizer);
+ const withMarker = allowed - markerTok >= 1;
+ const body = sliceToTokenCount(r.chunk_text.slice(0, cap), withMarker ? allowed - markerTok : allowed, tokenizer);
+ keep = body.length;
+ text = withMarker ? body + buildSnippetMarker(r.slug, r.chunk_text.length - keep) : body;
+ if (!withMarker) markerOmitted = true;
+ }
+ }
if (!r.delivered) return { ...r, chunk_text: text };
- const spans = r.delivered.match_spans.filter(s => s.start < cap).map(s => ({ ...s, end: Math.min(s.end, cap) }));
- const lost = r.delivered.match_spans.filter(s => s.start >= cap).map(s => s.chunk_id);
+ const spans = r.delivered.match_spans.filter(s => s.start < keep).map(s => ({ ...s, end: Math.min(s.end, keep) }));
+ const lost = r.delivered.match_spans.filter(s => s.start >= keep).map(s => s.chunk_id);
const unmapped = [...new Set([...(r.delivered.unmapped_chunk_ids ?? []), ...lost.filter(id => !spans.some(s => s.chunk_id === id))])];
return {
...r,
@@ -1015,8 +1297,9 @@ export function capDeliveredSnippets<T extends SearchResult & { delivered?: Deli
});
if (!any) return results;
if (!delivery.fallbacks.includes('snippet_cap')) delivery.fallbacks = [...delivery.fallbacks, 'snippet_cap'].sort();
+ if (markerOmitted && !delivery.fallbacks.includes('snippet_marker_omitted')) delivery.fallbacks = [...delivery.fallbacks, 'snippet_marker_omitted'].sort();
delivery.tokens_delivered = out.reduce((n, r) => n + (r.delivered?.tokens ?? 0), 0);
- return out;
+ return capEvidenceToBudget(out, delivery);
}
/** Image-query branches never expand; the meta says so instead of staying silent. */
@@ -1051,6 +1334,12 @@ export interface AssembleEvidenceInput {
budget_tokens?: number;
detail?: 'low' | 'medium' | 'high';
caller?: { remote?: boolean; sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean };
+ /**
+ * Library only (trusted local, never an MCP param): the packing for this
+ * call's explicit `auto` budget, winning over search.auto_packing, so an
+ * evaluation can compare packings on one frozen hit list.
+ */
+ auto_packing?: AutoPacking;
}
export interface AssembleEvidenceOutput {
@@ -1083,6 +1372,7 @@ export async function resolveFrozenHits(
const safe = requiresSafeChunks(scope) ? `AND ${safeChunksFilter('p')}` : '';
const rows = await engine.executeRaw<Record<string, unknown>>(
`SELECT h.ord, p.id AS page_id, p.slug, p.source_id, p.title, p.type,
+ p.effective_date, p.effective_date_source,
cc.id AS chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source
FROM unnest($1::text[], $2::text[], $3::int[], $4::int[]) AS h(source_id, slug, chunk_id, ord)
JOIN pages p ON p.source_id = h.source_id AND p.slug = h.slug
@@ -1098,7 +1388,7 @@ export async function resolveFrozenHits(
hits.forEach((h, i) => {
const r = byOrd.get(i);
if (!r || (h.chunk_id > 0 && r.chunk_id == null) || h.chunk_id < 0) { unresolved.push(i); return; }
- out.push({
+ const row: SearchResult = {
slug: String(r.slug),
page_id: Number(r.page_id),
source_id: String(r.source_id),
@@ -1110,7 +1400,11 @@ export async function resolveFrozenHits(
chunk_index: r.chunk_index == null ? 0 : Number(r.chunk_index),
score: 0,
stale: false,
- });
+ };
+ // The page date, normalized exactly as live search rows are, so frozen
+ // and live delivery hand a reader the same date fields.
+ applyEffectiveDate(row, r);
+ out.push(row);
});
return { rows: out, unresolved };
}
@@ -1143,6 +1437,7 @@ export async function assembleEvidenceForHits(engine: BrainEngine, input: Assemb
snippetChars: undefined,
snippetCap: 0,
op: 'assemble_evidence',
+ autoPacking: input.auto_packing,
});
const { rows, unresolved } = await resolveFrozenHits(engine, input.hits, scope);
if (!plan) {
@@ -1151,7 +1446,7 @@ export async function assembleEvidenceForHits(engine: BrainEngine, input: Assemb
}
const d = await deliverEvidence(engine, rows, plan, scope, { liveHits: true });
const out = redactRetrievalOutput(d.results, d.delivery);
- return { results: out.results, delivery: out.meta, unresolved };
+ return { results: capEvidenceToBudget(out.results, out.meta), delivery: out.meta, unresolved };
}
/** SHA-256 over the delivered evidence (see docs/evidence-delivery.md). */
diff --git a/src/core/search/evidence-packing.ts b/src/core/search/evidence-packing.ts
new file mode 100644
index 0000000000..59096780a5
--- /dev/null
+++ b/src/core/search/evidence-packing.ts
@@ -0,0 +1,50 @@
+/**
+ * The explicit-budget packing surface of evidence delivery
+ * (docs/evidence-delivery.md, "Explicit budgets"): the `search.auto_packing`
+ * values, the documented minimum budget, and their validation. Kept apart
+ * from the assembler so `gbrain config set` can validate a value without
+ * loading it.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { OperationError } from '../ops/contract.ts';
+
+/**
+ * How `auto` packs an explicit `token_budget` (`search.auto_packing`). Every
+ * value but `off` makes the budget a hard cap on the delivered evidence; the
+ * three differ only in how conversations share it. None of them runs without
+ * an explicit budget.
+ */
+export const AUTO_PACKINGS = ['off', 'cap_only', 'breadth_capped', 'depth_first'] as const;
+export type AutoPacking = typeof AUTO_PACKINGS[number];
+export const AUTO_PACKING_CONFIG_KEY = 'search.auto_packing';
+export const DEFAULT_AUTO_PACKING: AutoPacking = 'cap_only';
+/**
+ * The smallest explicit budget the cap accepts under `auto`: room for a cut
+ * marker, a shortened title and a non-empty body, so a non-empty hit list
+ * always yields non-empty evidence without exceeding the budget.
+ */
+export const MIN_EXPLICIT_AUTO_BUDGET = 32;
+
+/** A library caller's per-call packing; throws invalid_params for an unknown value. */
+export function parseAutoPacking(raw: unknown): AutoPacking | undefined {
+ if (raw === undefined || raw === null) return undefined;
+ if (typeof raw === 'string' && (AUTO_PACKINGS as readonly string[]).includes(raw)) return raw as AutoPacking;
+ const shown = typeof raw === 'string' ? JSON.stringify(raw.slice(0, 40)) : typeof raw;
+ throw new OperationError('invalid_params', `auto_packing must be one of ${AUTO_PACKINGS.join(', ')} (got ${shown}).`,
+ `Pass auto_packing: "${DEFAULT_AUTO_PACKING}" (or set ${AUTO_PACKING_CONFIG_KEY}).`);
+}
+
+/** The value `gbrain config set search.auto_packing` refuses, as a message, or null. */
+export function autoPackingValueProblem(value: string): string | null {
+ return (AUTO_PACKINGS as readonly string[]).includes(value) ? null
+ : `${AUTO_PACKING_CONFIG_KEY} must be one of ${AUTO_PACKINGS.join(', ')} (got "${value.slice(0, 40)}"). Nothing was written.`;
+}
+
+/** search.auto_packing as stored; an unknown or unreadable value reads as the default. */
+export async function configPacking(engine: BrainEngine): Promise<AutoPacking> {
+ try {
+ const raw = await engine.getConfig(AUTO_PACKING_CONFIG_KEY);
+ if (typeof raw === 'string' && (AUTO_PACKINGS as readonly string[]).includes(raw)) return raw as AutoPacking;
+ } catch { /* config unreadable: stay on the default */ }
+ return DEFAULT_AUTO_PACKING;
+}
diff --git a/src/core/utils.ts b/src/core/utils.ts
index 40c47cbdf8..026ca4786e 100644
--- a/src/core/utils.ts
+++ b/src/core/utils.ts
@@ -458,34 +458,17 @@ export function rowToChunk(row: Record<string, unknown>, includeEmbedding = fals
};
}
-export function rowToSearchResult(row: Record<string, unknown>): SearchResult {
- const result: SearchResult = {
- slug: row.slug as string,
- page_id: row.page_id as number,
- title: row.title as string,
- type: row.type as string,
- chunk_text: row.chunk_text as string,
- chunk_source: row.chunk_source as 'compiled_truth' | 'timeline',
- chunk_id: row.chunk_id as number,
- chunk_index: row.chunk_index as number,
- score: Number(row.score),
- stale: Boolean(row.stale),
- };
- // v0.17.0: source_id comes from the p.source_id column in search
- // SELECTs. Keep the field optional so pre-v0.17 engines that didn't
- // join sources don't crash on the absent column — rowToSearchResult
- // is shared by both paths.
- if (typeof row.source_id === 'string') {
- result.source_id = row.source_id;
- }
- // v0.34: effective_date / effective_date_source carried through from the
- // pages join. Same three-state read as readOptionalDate elsewhere: the
- // field is left UNTOUCHED when the column isn't in the projection (so
- // legacy callers see undefined), set to null when the column was selected
- // but the page row has no date, and to YYYY-MM-DD when populated. Postgres
- // returns Date objects via postgres.js; PGLite returns strings. Normalize
- // to date-only ISO so downstream prompt-builders don't see noise from
- // midnight-UTC timestamps.
+/**
+ * v0.34: effective_date / effective_date_source carried through from the
+ * pages join. Same three-state read as readOptionalDate elsewhere: the
+ * field is left UNTOUCHED when the column isn't in the projection (so
+ * legacy callers see undefined), set to null when the column was selected
+ * but the page row has no date, and to YYYY-MM-DD when populated. Postgres
+ * returns Date objects via postgres.js; PGLite returns strings. Normalize
+ * to date-only ISO so downstream prompt-builders don't see noise from
+ * midnight-UTC timestamps. Shared by search rows and frozen-hit rows.
+ */
+export function applyEffectiveDate(result: SearchResult, row: Record<string, unknown>): void {
if ('effective_date' in row) {
const raw = row.effective_date;
if (raw === null) {
@@ -506,6 +489,29 @@ export function rowToSearchResult(row: Record<string, unknown>): SearchResult {
result.effective_date_source = raw;
}
}
+}
+
+export function rowToSearchResult(row: Record<string, unknown>): SearchResult {
+ const result: SearchResult = {
+ slug: row.slug as string,
+ page_id: row.page_id as number,
+ title: row.title as string,
+ type: row.type as string,
+ chunk_text: row.chunk_text as string,
+ chunk_source: row.chunk_source as 'compiled_truth' | 'timeline',
+ chunk_id: row.chunk_id as number,
+ chunk_index: row.chunk_index as number,
+ score: Number(row.score),
+ stale: Boolean(row.stale),
+ };
+ // v0.17.0: source_id comes from the p.source_id column in search
+ // SELECTs. Keep the field optional so pre-v0.17 engines that didn't
+ // join sources don't crash on the absent column — rowToSearchResult
+ // is shared by both paths.
+ if (typeof row.source_id === 'string') {
+ result.source_id = row.source_id;
+ }
+ applyEffectiveDate(result, row);
if (typeof row.message_id === 'string' && row.message_id.trim().length > 0) {
result.message_id = row.message_id;
}
diff --git a/test/config-search-registry.test.ts b/test/config-search-registry.test.ts
index ae4ecf8248..4c70347837 100644
--- a/test/config-search-registry.test.ts
+++ b/test/config-search-registry.test.ts
@@ -42,6 +42,7 @@ const DIRECTLY_READ_SINGLETONS = [
'search.return_budget_default',
'search.return_budget_conversation',
'search.return_budget_max_remote',
+ 'search.auto_packing', // search/evidence-delivery.ts (explicit-budget cap)
];
describe('KNOWN_CONFIG_KEYS search.* rows mirror what the code reads (#4605)', () => {
diff --git a/test/e2e/evidence-delivery-leak.test.ts b/test/e2e/evidence-delivery-leak.test.ts
index 2290ed8fdf..bd1da99809 100644
--- a/test/e2e/evidence-delivery-leak.test.ts
+++ b/test/e2e/evidence-delivery-leak.test.ts
@@ -42,7 +42,7 @@ import { importFromContent } from '../../src/core/import-file.ts';
import { operations, type OperationContext } from '../../src/core/operations.ts';
import { renderFactsTable, FACTS_FENCE_BEGIN } from '../../src/core/facts-fence.ts';
import { TAKES_FENCE_BEGIN, TAKES_FENCE_END } from '../../src/core/takes-fence.ts';
-import { deliverEvidence, type EvidencePlan } from '../../src/core/search/evidence-delivery.ts';
+import { AUTO_PACKINGS, EVIDENCE_CUT_MARKER, assembleEvidenceForHits, countEvidenceTokens, deliverEvidence, type EvidencePlan } from '../../src/core/search/evidence-delivery.ts';
import { keylessBrainEnv } from '../helpers/provider-env.ts';
import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
import { createManagedFixtureSource, withManagedFixtureWrite } from '../helpers/managed-e2e-fixture-write.ts';
@@ -324,7 +324,8 @@ for (const backend of backends) describe(`evidence delivery leak canaries (${bac
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')) {
+ const body = text.endsWith(EVIDENCE_CUT_MARKER) ? text.slice(0, -EVIDENCE_CUT_MARKER.length) : text;
+ for (const segment of body.split('\n\n[…]\n\n')) {
for (const line of segment.split('\n')) {
const t = line.trim();
if (!t) continue;
@@ -355,6 +356,55 @@ for (const backend of backends) describe(`evidence delivery leak canaries (${bac
});
}, 180_000);
+ test('explicit budgets under every packing: no canaries, no cross-source or private text, a subset of get_page, within the budget', async () => {
+ await mutate(async () => {
+ const recount = (rows: SearchResult[]) => rows.reduce((n, r) => n + countEvidenceTokens(r.title ?? '') + countEvidenceTokens(r.chunk_text), 0);
+ try {
+ for (const packing of AUTO_PACKINGS.filter(p => p !== 'off')) {
+ await engine.setConfig('search.auto_packing', packing);
+ for (const remote of [false, true]) {
+ const canaries = remote ? [...ALWAYS_CANARIES.filter(c => c !== 'EDITSECRETCANARY'), ...REMOTE_CANARIES] : ALWAYS_CANARIES.filter(c => c !== 'EDITSECRETCANARY');
+ const reference = new Map<string, string | null>();
+ const readable = async (slug: string) => {
+ if (!reference.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 };
+ reference.set(slug, page.content);
+ } catch { reference.set(slug, null); }
+ }
+ return reference.get(slug)!;
+ };
+ for (const budget of [64, 400, 3000]) {
+ const label = `${packing} remote=${remote} @${budget}`;
+ const search = await operations.find(o => o.name === 'search')!.handler(ctxOf(remote), { query: 'heron', token_budget: budget, source_id: BOUND, limit: 50, fields: 'full' }) as SearchResult[];
+ const query = await operations.find(o => o.name === 'query')!.handler(ctxOf(remote), { query: 'heron', return_unit: 'auto', token_budget: budget, source_id: BOUND, expand: false, fields: 'full' }) as SearchResult[];
+ const recall = await operations.find(o => o.name === 'recall')!.handler(ctxOf(remote), { query: 'heron', return_unit: 'auto', budget_tokens: budget, source_id: BOUND });
+ // Frozen hits name the same slug in an ungranted source, and a page this caller cannot read.
+ const frozen = [...search.map(h => ({ source_id: h.source_id!, slug: h.slug, chunk_id: h.chunk_id })), { source_id: FOREIGN, slug: 'notes/heron', chunk_id: 0 }];
+ const assembled = await assembleEvidenceForHits(engine, { hits: frozen, return_unit: 'auto', budget_tokens: budget, auto_packing: packing, caller: { remote, sourceId: BOUND } });
+ for (const [name, payload] of [['search', search], ['query', query], ['recall', recall], ['assemble', assembled]] as const) assertNoLeak(`${label} ${name}`, payload, canaries);
+ expect(assembled.unresolved, label).toContain(frozen.length - 1);
+ for (const rows of [search, query, assembled.results as SearchResult[]]) {
+ expect(recount(rows), label).toBeLessThanOrEqual(budget);
+ for (const row of rows) {
+ const ref = await readable(row.slug);
+ expect(ref, `${label}: ${row.slug} delivered but not readable via get_page`).not.toBeNull();
+ if (row.delivered?.reason === 'not_conversation') continue;
+ const body = row.chunk_text.endsWith(EVIDENCE_CUT_MARKER) ? row.chunk_text.slice(0, -EVIDENCE_CUT_MARKER.length) : row.chunk_text;
+ for (const line of body.split('\n\n[…]\n\n').flatMap(seg => seg.split('\n'))) {
+ if (line.trim()) expect(ref!.includes(line.trim()), `${label}: ${row.slug} line not in get_page: ${line.slice(0, 80)}`).toBe(true);
+ }
+ }
+ }
+ }
+ }
+ }
+ } finally {
+ await engine.executeRaw(`DELETE FROM config WHERE key = 'search.auto_packing'`);
+ }
+ });
+ }, 180_000);
+
test('stdio and HTTP transports deliver presence controls and no canaries', async () => {
const canaries = [...ALWAYS_CANARIES.filter(c => c !== 'EDITSECRETCANARY'), ...REMOTE_CANARIES];
const verify = async (client: Client) => {
@@ -387,7 +437,7 @@ for (const backend of backends) describe(`evidence delivery leak canaries (${bac
}, 180_000);
test('stale hits are re-authorized: grant revocation, private flip and mid-flight edit', async () => {
- const plan: EvidencePlan = { requestedUnit: 'page', unit: 'page', window: 1, budgetTokens: 32000, explicitUnit: true };
+ const plan: EvidencePlan = { requestedUnit: 'page', unit: 'page', window: 1, budgetTokens: 32000, explicitUnit: true, budgetExplicit: false, packing: 'cap_only' };
await mutate(async () => {
// Revocation: hits ranked under a two-source grant, expanded after the grant narrowed.
const wide = await operations.find(o => o.name === 'search')!.handler({ ...ctxOf(false), sourceId: BOUND }, { query: 'heron', source_id: '__all__', limit: 50 }) as SearchResult[];
diff --git a/test/e2e/evidence-delivery-parity.test.ts b/test/e2e/evidence-delivery-parity.test.ts
index 522e01cea4..aa796833ac 100644
--- a/test/e2e/evidence-delivery-parity.test.ts
+++ b/test/e2e/evidence-delivery-parity.test.ts
@@ -9,7 +9,11 @@
* produce the same evidence fingerprint, and both engines deliver the
* same text for every unit;
* - the implied `auto` default (return_unit omitted) delivers exactly what
- * `assemble_evidence` with `auto` delivers for the same hits.
+ * `assemble_evidence` with `auto` delivers for the same hits;
+ * - under an explicit budget (the cap, every search.auto_packing value)
+ * live `query`/`search` and frozen-hit assembly deliver the same fields a
+ * reader consumes, effective_date included, within the budget, on both
+ * engines.
*
* Postgres arm runs when DATABASE_URL is set.
*
@@ -29,7 +33,7 @@ import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
import type { BrainEngine } from '../../src/core/engine.ts';
import type { SearchResult } from '../../src/core/types.ts';
import { operations, type OperationContext } from '../../src/core/operations.ts';
-import { evidenceFingerprint, pageEvidenceText } from '../../src/core/search/evidence-delivery.ts';
+import { AUTO_PACKINGS, assembleEvidenceForHits, countEvidenceTokens, evidenceFingerprint, pageEvidenceText } from '../../src/core/search/evidence-delivery.ts';
import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
import { captureOffPath, seedOffPath, withCostWave } from '../helpers/evidence-delivery-fixture.ts';
import { configureGateway } from '../../src/core/ai/gateway.ts';
@@ -140,6 +144,43 @@ describe('evidence delivery parity', () => {
expect(expanded).toBeGreaterThan(0);
}, 120_000);
+ test(`an explicit budget delivers the same capped, dated evidence live and from frozen hits, every packing (${backend})`, async () => {
+ const engine = engines[backend]!;
+ const recount = (rows: SearchResult[]) => rows.reduce((n, r) => n + countEvidenceTokens(r.title ?? '') + countEvidenceTokens(r.chunk_text), 0);
+ const consumed = (rows: SearchResult[]) => rows.map(r => ({
+ slug: r.slug, title: r.title, chunk_text: r.chunk_text, effective_date: r.effective_date ?? null, effective_date_source: r.effective_date_source ?? null,
+ unit: r.delivered?.unit, spans: r.delivered?.match_spans, tokens: r.delivered?.tokens, truncated: r.delivered?.truncated, reason: r.delivered?.reason,
+ }));
+ await engine.executeRaw(`UPDATE pages SET effective_date = '2026-02-03', effective_date_source = 'frontmatter' WHERE slug = 'chat/session-a'`);
+ try {
+ let dated = 0;
+ for (const packing of AUTO_PACKINGS) {
+ await engine.setConfig('search.auto_packing', packing);
+ for (const remote of [false, true]) {
+ const hits = await op('query').handler(ctxOf(engine, remote), { fields: 'full', query: 'ocelot', expand: false, return_unit: 'chunk' }) as SearchResult[];
+ for (const budget of [400, 2500]) {
+ const live = await op('query').handler(ctxOf(engine, remote), { fields: 'full', query: 'ocelot', expand: false, return_unit: 'auto', token_budget: budget }) as SearchResult[];
+ const viaOp = 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', token_budget: budget,
+ }) as { results: SearchResult[] };
+ const viaLib = await assembleEvidenceForHits(engine, {
+ hits: hits.map(h => ({ source_id: h.source_id!, slug: h.slug, chunk_id: h.chunk_id })), return_unit: 'auto', budget_tokens: budget, auto_packing: packing, caller: { remote },
+ });
+ const label = `${packing} remote=${remote} @${budget}`;
+ expect(consumed(viaOp.results), label).toEqual(consumed(live));
+ expect(consumed(viaLib.results as SearchResult[]), label).toEqual(consumed(live));
+ if (packing !== 'off') expect(recount(live), label).toBeLessThanOrEqual(budget);
+ dated += live.filter(r => r.slug === 'chat/session-a' && r.effective_date === '2026-02-03').length;
+ }
+ }
+ }
+ expect(dated).toBeGreaterThan(0);
+ } finally {
+ await engine.executeRaw(`UPDATE pages SET effective_date = NULL, effective_date_source = NULL WHERE slug = 'chat/session-a'`);
+ await engine.executeRaw(`DELETE FROM config WHERE key = 'search.auto_packing'`);
+ }
+ }, 120_000);
+
test(`page evidence is byte-identical to the stored body minus frontmatter and protected content (${backend})`, async () => {
const engine = engines[backend]!;
for (const remote of [false, true]) {
@@ -183,6 +224,18 @@ describe('evidence delivery parity', () => {
const rb = await op('search').handler(ctxOf(b), { fields: 'full', query: 'ocelot', return_unit: unit, token_budget: 2500 }) as SearchResult[];
expect(textOf(rb)).toEqual(textOf(ra));
}
+ for (const packing of AUTO_PACKINGS) {
+ for (const engine of [a, b]) await engine.setConfig('search.auto_packing', packing);
+ try {
+ for (const budget of [300, 2500]) {
+ const ra = await op('query').handler(ctxOf(a), { fields: 'full', query: 'ocelot', expand: false, return_unit: 'auto', token_budget: budget }) as SearchResult[];
+ const rb = await op('query').handler(ctxOf(b), { fields: 'full', query: 'ocelot', expand: false, return_unit: 'auto', token_budget: budget }) as SearchResult[];
+ expect(textOf(rb), `${packing} @${budget}`).toEqual(textOf(ra));
+ }
+ } finally {
+ for (const engine of [a, b]) await engine.executeRaw(`DELETE FROM config WHERE key = 'search.auto_packing'`);
+ }
+ }
const windows = async (engine: BrainEngine) => {
const ids = await engine.executeRaw<{ id: number; slug: string }>(`SELECT id, slug FROM pages ORDER BY slug`);
const pages = await engine.getChunkWindows(ids.map((p, i) => ({ page_id: p.id, from_index: 0, to_index: 3, priority: i })),
diff --git a/test/evidence-delivery.test.ts b/test/evidence-delivery.test.ts
index a4808eb2e0..06b8480fa8 100644
--- a/test/evidence-delivery.test.ts
+++ b/test/evidence-delivery.test.ts
@@ -24,21 +24,29 @@ import { renderPagesBlock } from '../src/core/think/gather.ts';
import { runThink } from '../src/core/think/index.ts';
import { formatDeliverySummary, formatResultsExplain } from '../src/core/search/explain-formatter.ts';
import {
+ AUTO_PACKINGS,
conversationSignal,
assembleEvidenceForHits,
+ capDeliveredSnippets,
+ capEngaged,
countEvidenceTokens,
deliverEvidence,
deliveryVersionSkewWarning,
EVIDENCE_BLOCK_CHAR_CAP,
+ EVIDENCE_CUT_MARKER,
EVIDENCE_OMISSION,
evidenceFingerprint,
isConversationLabels,
locateChunks,
+ MIN_EXPLICIT_AUTO_BUDGET,
pageEvidenceText,
+ resolveEvidencePlan,
splitPieces,
TIMELINE_SEPARATOR,
+ type AutoPacking,
type EvidencePlan,
} from '../src/core/search/evidence-delivery.ts';
+import { searchConfigValueRefusal } from '../src/core/search/config-values.ts';
function rng(seed: number): () => number {
let a = seed >>> 0;
@@ -171,8 +179,14 @@ function hitFor(p: FakePage, index: number): SearchResult {
};
}
-function planOf(unit: EvidencePlan['unit'], budget: number, window = 1): EvidencePlan {
- return { requestedUnit: unit, unit, window, budgetTokens: budget, explicitUnit: true };
+/**
+ * A plan as resolveEvidencePlan builds it. `budgetExplicit` defaults to false:
+ * the existing property and spill tests pin today's implied-budget path,
+ * which every packing must leave byte-identical; the explicit-budget cap has
+ * its own tests below (`capPlan`).
+ */
+function planOf(unit: EvidencePlan['unit'], budget: number, window = 1, extra: Partial<EvidencePlan> = {}): EvidencePlan {
+ return { requestedUnit: unit, unit, window, budgetTokens: budget, explicitUnit: true, budgetExplicit: false, packing: 'cap_only', ...extra };
}
function randomCorpus(r: () => number, pageCount: number): FakePage[] {
@@ -223,6 +237,9 @@ describe('allocation and boundary properties', () => {
}
});
+ // Pins the implied-budget path (planOf: budgetExplicit false), which the cap
+ // never touches: every chunk is kept and a session that cannot fit spills.
+ // "Explicit budget: ..." below is its twin under the cap.
test('auto: conversation pages whole, every other hit its unchanged chunk, nothing lost, expansion within budget', async () => {
const r = rng(20261001);
let sawPage = 0;
@@ -269,6 +286,7 @@ describe('allocation and boundary properties', () => {
expect(sawChunk).toBeGreaterThan(10);
});
+ // Implied budget only: under an explicit budget nothing spills (twin below).
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);
@@ -390,6 +408,360 @@ describe('allocation and boundary properties', () => {
});
});
+// ---------------------------------------------------------------------------
+// Explicit budgets under auto: the cap (search.auto_packing)
+// ---------------------------------------------------------------------------
+
+const CAP_PACKINGS = AUTO_PACKINGS.filter((x): x is Exclude<AutoPacking, 'off'> => x !== 'off');
+
+function capPlan(budget: number, packing: AutoPacking = 'cap_only', window = 1): EvidencePlan {
+ return planOf('auto', budget, window, { budgetExplicit: true, packing });
+}
+
+const recount = (rows: Array<{ title?: string; chunk_text: string }>) => rows.reduce((n, x) => n + countEvidenceTokens(x.title ?? '') + countEvidenceTokens(x.chunk_text), 0);
+
+/** A chat page of three one-line turns: return_window 1 around turn 1 covers the whole page. */
+function chatPage(id: number, words: number, title = `Chat ${id}`): FakePage {
+ const r = rng(1000 + id);
+ const turn = (who: string, k: number) => `**${who}:** ${Array.from({ length: words }, () => WORDS[Math.floor(r() * WORDS.length)]).join(' ')} turn ${id}-${k}.`;
+ const chunks = [turn('user', 0), turn('assistant', 1), turn('user', 2)];
+ return { page_id: id, slug: `chat/c${id}`, title, chunks };
+}
+
+function notePage(id: number, words: number, title = `Note ${id}`): FakePage {
+ const r = rng(2000 + id);
+ return { page_id: id, slug: `notes/n${id}`, title, chunks: [`${Array.from({ length: words }, () => WORDS[Math.floor(r() * WORDS.length)]).join(' ')} note ${id}.`] };
+}
+
+const whole = (p: FakePage) => countEvidenceTokens(p.title) + countEvidenceTokens(p.chunks.join('\n\n'));
+const floorOf = (p: FakePage, i = 1) => countEvidenceTokens(p.title) + countEvidenceTokens(p.chunks[i] + (i < p.chunks.length - 1 ? '\n' : ''));
+
+describe('explicit budget: the cap', () => {
+ test('without an explicit budget every packing is today\'s path, byte for byte (guard 1, structural)', async () => {
+ const r = rng(20261009);
+ let compared = 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() * 25); 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 today = JSON.stringify(await deliverEvidence(fakeEngine(pages), hits, planOf('auto', budget, 1, { packing: 'off' }), {}));
+ for (const packing of AUTO_PACKINGS) {
+ expect(capEngaged(planOf('auto', budget, 1, { packing }))).toBe(false);
+ expect(JSON.stringify(await deliverEvidence(fakeEngine(pages), hits, planOf('auto', budget, 1, { packing }), {}))).toBe(today);
+ compared++;
+ }
+ // An explicit budget with packing off is today's path too.
+ expect(JSON.stringify(await deliverEvidence(fakeEngine(pages), hits, capPlan(budget, 'off'), {}))).toBe(today);
+ }
+ expect(compared).toBe(240);
+ });
+
+ // Twin of the implied-budget property above: under the cap the recount of
+ // the final evidence fields never exceeds the budget, nothing spills, rank
+ // one is always delivered and every hit is delivered or counted as dropped.
+ test('explicit budget: the recount never exceeds the budget, nothing spills, rank one survives, every hit is accounted for', async () => {
+ const r = rng(20261010);
+ let cut = 0;
+ let droppedAny = 0;
+ for (let trial = 0; trial < 50; trial++) {
+ const pages = randomCorpus(r, 1 + Math.floor(r() * 10));
+ const hits: SearchResult[] = [];
+ for (let k = 0; k < 1 + Math.floor(r() * 25); 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 items = new Set(hits.map(h => h.slug.startsWith('chat/') ? `p${h.page_id}` : `c${h.chunk_id}`)).size;
+ for (const packing of CAP_PACKINGS) {
+ const budget = [MIN_EXPLICIT_AUTO_BUDGET, 40, 200, 800, 3000, 8000, 24000][Math.floor(r() * 7)];
+ const snapshot = JSON.stringify(hits);
+ const { results, delivery } = await deliverEvidence(fakeEngine(pages), hits, capPlan(budget, packing, 1 + Math.floor(r() * 3)), {});
+ const label = `trial ${trial} ${packing} @${budget}`;
+ expect(JSON.stringify(hits)).toBe(snapshot);
+ expect(recount(results), label).toBeLessThanOrEqual(budget);
+ expect(delivery.budget_used, label).toBe(recount(results));
+ expect(delivery.auto_packing).toBe(packing);
+ expect(results.length, label).toBeGreaterThan(0);
+ expect(results[0].delivered.chunk_ids, label).toContain(hits[0].chunk_id);
+ expect(results.length + delivery.dropped, label).toBe(items);
+ expect(results.some(x => x.delivered.reason === 'conversation_over_budget'), label).toBe(false);
+ 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) {
+ expect(res.chunk_text.length).toBeLessThanOrEqual(EVIDENCE_BLOCK_CHAR_CAP + EVIDENCE_CUT_MARKER.length);
+ for (const sp of res.delivered.match_spans) {
+ expect(sp.end).toBeLessThanOrEqual(res.chunk_text.length);
+ const anchor = hits.find(h => h.chunk_id === sp.chunk_id)!;
+ expect(norm(anchor.chunk_text)).toContain(norm(res.chunk_text.slice(sp.start, sp.end)));
+ }
+ if (res.chunk_text.endsWith(EVIDENCE_CUT_MARKER)) { cut++; expect(res.delivered.truncated).toBe(true); }
+ }
+ if (delivery.dropped > 0) droppedAny++;
+ }
+ }
+ expect(cut).toBeGreaterThan(5);
+ expect(droppedAny).toBeGreaterThan(20);
+ });
+
+ test('explicit budget: a session that cannot fit is dropped, never spilled outside the budget (twin of the spill test)', async () => {
+ const pages = randomCorpus(rng(5), 12).filter(p => p.slug.startsWith('chat/')).slice(0, 3);
+ const hits = pages.map(p => hitFor(p, Math.floor(p.chunks.length / 2)));
+ let budget = countEvidenceTokens(hits[0].chunk_text);
+ let tight = await deliverEvidence(fakeEngine(pages), hits, capPlan(budget), {});
+ while (tight.results[0].delivered.truncated) tight = await deliverEvidence(fakeEngine(pages), hits, capPlan(++budget), {});
+ expect(tight.results.map(x => x.slug)).toEqual([pages[0].slug]);
+ expect(tight.delivery.dropped_reasons).toEqual({ budget_floor: 2 });
+ expect(tight.delivery.budget_used).toBeLessThanOrEqual(budget);
+ const today = await deliverEvidence(fakeEngine(pages), hits, planOf('auto', budget), {});
+ expect(today.delivery.budget_used).toBeGreaterThan(budget);
+ });
+
+ test('mixed notes and chats: global rank one comes first, note or chat', async () => {
+ const [c1, c2] = [chatPage(1, 60), chatPage(2, 60)];
+ const n3 = notePage(3, 30);
+ const budget = floorOf(c1) + whole(n3) + 4;
+ for (const packing of CAP_PACKINGS) {
+ const noteFirst = await deliverEvidence(fakeEngine([c1, c2, n3]), [hitFor(n3, 0), hitFor(c1, 1), hitFor(c2, 1)], capPlan(budget, packing), {});
+ expect(noteFirst.results.map(x => x.slug), packing).toEqual(packing === 'breadth_capped' ? ['notes/n3'] : ['notes/n3', 'chat/c1']);
+ expect(noteFirst.results[0].delivered).toMatchObject({ unit: 'chunk', reason: 'not_conversation', truncated: false });
+ const chatFirst = await deliverEvidence(fakeEngine([c1, c2, n3]), [hitFor(c1, 1), hitFor(n3, 0), hitFor(c2, 1)], capPlan(budget, packing), {});
+ expect(chatFirst.results.map(x => x.slug), packing).toEqual(['chat/c1', 'notes/n3']);
+ expect(recount(chatFirst.results)).toBeLessThanOrEqual(budget);
+ }
+ });
+
+ test('a leading chat is never crowded out by a lower-ranked note that does not fit', async () => {
+ const c1 = chatPage(1, 40);
+ const big = notePage(2, 900);
+ const budget = whole(c1) + 10;
+ for (const packing of CAP_PACKINGS) {
+ const { results, delivery } = await deliverEvidence(fakeEngine([c1, big]), [hitFor(c1, 1), hitFor(big, 0)], capPlan(budget, packing), {});
+ expect(results.map(x => x.slug), packing).toEqual(['chat/c1']);
+ expect(results[0].delivered).toMatchObject({ unit: 'page', truncated: false });
+ expect(delivery.dropped_reasons).toEqual({ budget_note: 1 });
+ }
+ // Today's implied path pays the note first and spills the chat to its chunk.
+ const today = await deliverEvidence(fakeEngine([c1, big]), [hitFor(c1, 1), hitFor(big, 0)], planOf('auto', budget), {});
+ expect(today.results.map(x => x.delivered.reason)).toEqual(['conversation_over_budget', 'not_conversation']);
+ });
+
+ test('notes only, over budget: the rank-order prefix that fits is kept and the rest is listed', async () => {
+ const [a, b, c] = [notePage(1, 20), notePage(2, 400), notePage(3, 20)];
+ const budget = whole(a) + 40;
+ const { results, delivery } = await deliverEvidence(fakeEngine([a, b, c]), [hitFor(a, 0), hitFor(b, 0), hitFor(c, 0)], capPlan(budget), {});
+ expect(results.map(x => x.slug)).toEqual(['notes/n1']);
+ expect(results[0].chunk_text).toBe(a.chunks[0]);
+ expect(delivery.dropped_reasons).toEqual({ budget_note: 2 });
+ // Rank one longer than the budget is cut at a piece boundary with the counted marker, never empty.
+ const cut = await deliverEvidence(fakeEngine([b, a]), [hitFor(b, 0), hitFor(a, 0)], capPlan(60), {});
+ expect(cut.results).toHaveLength(1);
+ expect(cut.results[0].chunk_text.endsWith(EVIDENCE_CUT_MARKER)).toBe(true);
+ expect(cut.results[0].chunk_text.length).toBeGreaterThan(EVIDENCE_CUT_MARKER.length + 10);
+ expect(b.chunks[0].startsWith(cut.results[0].chunk_text.slice(0, -EVIDENCE_CUT_MARKER.length))).toBe(true);
+ expect(cut.results[0].delivered).toMatchObject({ truncated: true, match_spans: [{ start: 0, end: cut.results[0].chunk_text.length - EVIDENCE_CUT_MARKER.length }] });
+ expect(recount(cut.results)).toBeLessThanOrEqual(60);
+ expect(cut.delivery.dropped_reasons).toEqual({ budget_note: 1 });
+ });
+
+ test('rank one longer than the budget is cut to fit with a marker, never dropped, in every packing', async () => {
+ const big = chatPage(1, 400);
+ const other = chatPage(2, 40);
+ for (const packing of CAP_PACKINGS) {
+ for (const budget of [MIN_EXPLICIT_AUTO_BUDGET, 40, 100]) {
+ const { results, delivery } = await deliverEvidence(fakeEngine([big, other]), [hitFor(big, 1), hitFor(other, 1)], capPlan(budget, packing), {});
+ expect(results.map(x => x.slug)).toEqual(['chat/c1']);
+ expect(results[0].delivered.truncated).toBe(true);
+ expect(results[0].chunk_text.endsWith(EVIDENCE_CUT_MARKER)).toBe(true);
+ expect(results[0].chunk_text.length - EVIDENCE_CUT_MARKER.length).toBeGreaterThan(0);
+ expect(recount(results), `${packing} @${budget}`).toBeLessThanOrEqual(budget);
+ expect(delivery.dropped).toBe(1);
+ }
+ }
+ });
+
+ test('breadth_capped keeps the longest rank-order prefix whose title, floor and target window fit, then drops the rest as breadth_cap', async () => {
+ const pages = [chatPage(1, 50), chatPage(2, 50), chatPage(3, 50), chatPage(4, 50)];
+ const hits = pages.map(p => hitFor(p, 1));
+ // return_window 1 around turn 1 is the whole three-turn page, so each group's price is the whole page.
+ const budget = whole(pages[0]) + whole(pages[1]) + Math.floor(whole(pages[2]) / 2);
+ const { results, delivery } = await deliverEvidence(fakeEngine(pages), hits, capPlan(budget, 'breadth_capped'), {});
+ expect(results.map(x => x.slug)).toEqual(['chat/c1', 'chat/c2']);
+ for (const res of results) expect(res.delivered).toMatchObject({ unit: 'page', truncated: false });
+ expect(delivery.dropped_reasons).toEqual({ breadth_cap: 2 });
+ // cap_only on the same budget reserves every floor first, so the third session keeps its span.
+ const capOnly = await deliverEvidence(fakeEngine(pages), hits, capPlan(budget, 'cap_only'), {});
+ expect(capOnly.results.length).toBeGreaterThan(2);
+ // An oversized first group is cut, never skipped.
+ const tiny = await deliverEvidence(fakeEngine(pages), hits, capPlan(floorOf(pages[0]) - 5, 'breadth_capped'), {});
+ expect(tiny.results.map(x => x.slug)).toEqual(['chat/c1']);
+ expect(tiny.results[0].delivered.truncated).toBe(true);
+ expect(tiny.delivery.dropped_reasons).toEqual({ breadth_cap: 3 });
+ // A first group whose window does not fit keeps its floor (rank one), and the rest are breadth-capped.
+ const lead = await deliverEvidence(fakeEngine(pages), hits, capPlan(floorOf(pages[0]) + 6, 'breadth_capped'), {});
+ expect(lead.results.map(x => x.slug)).toEqual(['chat/c1']);
+ expect(lead.delivery.dropped_reasons).toEqual({ breadth_cap: 3 });
+ });
+
+ test('depth_first takes each session whole when it fits, else the largest window, else skips it', async () => {
+ const pages = [chatPage(1, 60), chatPage(2, 60), chatPage(3, 60)];
+ const hits = pages.map(p => hitFor(p, 1));
+ const budget = whole(pages[0]) + floorOf(pages[1]) + 2;
+ const depth = await deliverEvidence(fakeEngine(pages), hits, capPlan(budget, 'depth_first'), {});
+ expect(depth.results.map(x => x.slug)).toEqual(['chat/c1', 'chat/c2']);
+ expect(depth.results[0].delivered).toMatchObject({ unit: 'page', truncated: false });
+ expect(depth.results[1].delivered.truncated).toBe(true);
+ expect(depth.delivery.dropped_reasons).toEqual({ budget_floor: 1 });
+ // cap_only reserves all three floors before growing any session.
+ const capOnly = await deliverEvidence(fakeEngine(pages), hits, capPlan(budget, 'cap_only'), {});
+ expect(capOnly.results.map(x => x.slug)).toEqual(['chat/c1', 'chat/c2', 'chat/c3']);
+ expect(capOnly.results[0].delivered.truncated).toBe(true);
+ // Depth first: the leading session grows into what is left before the next one is considered.
+ const greedy = await deliverEvidence(fakeEngine([pages[0], pages[1]]), [hitFor(pages[0], 1), hitFor(pages[1], 1)], capPlan(floorOf(pages[0]) + floorOf(pages[1]) + 1, 'depth_first'), {});
+ expect(greedy.results.map(x => x.slug)).toEqual(['chat/c1']);
+ expect(greedy.delivery.dropped_reasons).toEqual({ budget_floor: 1 });
+ // A session whose matching chunk does not fit is skipped; a later one that fits is still taken.
+ const [big, small] = [chatPage(5, 400), chatPage(6, 10)];
+ const skip = await deliverEvidence(fakeEngine([pages[0], big, small]), [hitFor(pages[0], 1), hitFor(big, 1), hitFor(small, 1)], capPlan(whole(pages[0]) + whole(small) + 2, 'depth_first'), {});
+ expect(skip.results.map(x => x.slug)).toEqual(['chat/c1', 'chat/c6']);
+ expect(skip.results.map(x => x.delivered.truncated)).toEqual([false, false]);
+ expect(skip.delivery.dropped_reasons).toEqual({ budget_floor: 1 });
+ });
+
+ test('source swamp: a curated note survives chat dumps that repeat its phrase under a tight budget, in every packing', async () => {
+ const phrase = 'renewal window closes friday';
+ const dumps = [1, 2, 3, 4].map(id => {
+ const p = chatPage(id, 120);
+ return { ...p, chunks: p.chunks.map(c => `${c} ${phrase}.`) };
+ });
+ const note: FakePage = { page_id: 9, slug: 'notes/renewal-policy', title: 'Renewal policy', chunks: [`The ${phrase}; the owner signs it.`] };
+ const budget = floorOf(dumps[0]) + whole(note) + 20;
+ for (const packing of CAP_PACKINGS) {
+ for (let at = 0; at <= 4; at++) {
+ const hits = dumps.map(d => hitFor(d, 1));
+ hits.splice(at, 0, hitFor(note, 0));
+ const { results } = await deliverEvidence(fakeEngine([...dumps, note]), hits, capPlan(budget, packing), {});
+ expect(results.some(x => x.slug === 'notes/renewal-policy'), `${packing}, note at rank ${at}`).toBe(true);
+ expect(recount(results)).toBeLessThanOrEqual(budget);
+ }
+ }
+ });
+
+ test('zero conversation hits: within the budget the rows are the ranked chunks, unchanged', async () => {
+ const notes = [notePage(1, 20), notePage(2, 20)];
+ const hits = notes.map(n => hitFor(n, 0));
+ const engine = fakeEngine(notes);
+ const { results, delivery } = await deliverEvidence(engine, hits, capPlan(4000), {});
+ expect(engine.calls).toBe(0);
+ expect(results.map(({ delivered, ...row }) => row)).toEqual(hits);
+ expect(delivery).toMatchObject({ auto_packing: 'cap_only', dropped: 0, budget_used: recount(results) });
+ });
+
+ test('redaction that grows a row is recounted inside the budget', async () => {
+ const secret = ['AKIA', 'ABCDEFGHIJKLMNOP'].join('');
+ const note: FakePage = { page_id: 4, slug: 'notes/keys', title: 'Keys', chunks: [`The deploy key is ${secret} ${secret} ${secret} for staging and nothing else here at all.`] };
+ const budget = Math.max(MIN_EXPLICIT_AUTO_BUDGET, whole(note));
+ const { results, delivery } = await deliverEvidence(fakeEngine([note]), [hitFor(note, 0)], capPlan(budget), {});
+ expect(results[0].chunk_text).not.toContain(secret);
+ expect(results[0].chunk_text).toContain('<REDACTED:');
+ expect(delivery.fallbacks).toContain('redaction_unmapped');
+ expect(recount(results)).toBeLessThanOrEqual(budget);
+ expect(delivery.budget_used).toBe(recount(results));
+ });
+
+ test('the 60,000-character cap is reached before a large budget, and CJK spans stay UTF-16 exact', async () => {
+ const big = Array.from({ length: 40 }, (_, i) => `**${i % 2 ? 'assistant' : 'user'}:** Paragraph ${i}. ${'lorem ipsum dolor sit amet '.repeat(90)}`);
+ const page: FakePage = { page_id: 2, slug: 'chat/big', title: 'Big', chunks: big };
+ const { results } = await deliverEvidence(fakeEngine([page]), [hitFor(page, 20)], capPlan(32000), {});
+ expect(results[0].chunk_text.length).toBeLessThanOrEqual(EVIDENCE_BLOCK_CHAR_CAP);
+ expect(results[0].chunk_text).toContain('Paragraph 20.');
+ const r = rng(31);
+ const cjkTurn = (who: string) => `**${who}:** ${Array.from({ length: 120 }, () => '天地玄黄宇宙洪荒日月盈昃'[Math.floor(r() * 12)]).join('')}`;
+ const cjk: FakePage = { page_id: 3, slug: 'chat/cjk', title: '会话', chunks: [cjkTurn('user'), cjkTurn('assistant'), cjkTurn('user'), cjkTurn('assistant')] };
+ for (const packing of CAP_PACKINGS) {
+ const out = await deliverEvidence(fakeEngine([cjk]), [hitFor(cjk, 2)], capPlan(120, packing), {});
+ expect(recount(out.results)).toBeLessThanOrEqual(120);
+ for (const sp of out.results[0].delivered.match_spans) expect(cjk.chunks[2]).toContain(out.results[0].chunk_text.slice(sp.start, sp.end));
+ }
+ });
+
+ test('fetch failure, timeout and cached hits under the cap: fresh chunks within the budget, cached ones dropped', async () => {
+ const pages = [chatPage(1, 200), chatPage(2, 200)];
+ const hits = pages.map(p => hitFor(p, 1));
+ const live = await deliverEvidence(fakeEngine(pages, { fail: true }), hits, capPlan(120), {});
+ expect(live.results[0].delivered.fallback_reason).toBe('fetch_failed');
+ expect(recount(live.results)).toBeLessThanOrEqual(120);
+ const hanging = { getChunkWindows: () => new Promise<never>(() => {}) } as unknown as BrainEngine;
+ const slow = await deliverEvidence(hanging, hits, capPlan(120), {}, { timeoutMs: 20 });
+ expect(slow.delivery.fallbacks).toContain('fetch_timeout');
+ expect(recount(slow.results)).toBeLessThanOrEqual(120);
+ const cached = await deliverEvidence(fakeEngine(pages, { fail: true }), hits, capPlan(120), {}, { liveHits: false });
+ expect(cached.results).toEqual([]);
+ expect(cached.delivery.dropped_reasons).toEqual({ not_readable: 2 });
+ });
+
+ test('budgets below the documented minimum, zero, negative and non-finite are refused by name; the minimum is served', async () => {
+ const stub = { getConfig: async () => null } as unknown as BrainEngine;
+ const plan = (budget: unknown, extra: Record<string, unknown> = {}) => resolveEvidencePlan(stub, {
+ remote: false, returnUnit: 'auto', returnWindow: undefined, budget, snippetChars: undefined, snippetCap: 0, op: 'query', ...extra,
+ });
+ for (const budget of [...Array.from({ length: MIN_EXPLICIT_AUTO_BUDGET - 1 }, (_, i) => i + 1), 0, -5, 31.9, Number.NaN, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY]) {
+ await expect(plan(budget), String(budget)).rejects.toMatchObject({
+ code: 'invalid_params', message: expect.stringContaining(`token_budget must be at least ${MIN_EXPLICIT_AUTO_BUDGET} tokens`),
+ });
+ }
+ await expect(plan(3, { op: 'recall' })).rejects.toMatchObject({ message: expect.stringContaining('budget_tokens must be at least') });
+ expect(await plan(MIN_EXPLICIT_AUTO_BUDGET)).toMatchObject({ budgetTokens: MIN_EXPLICIT_AUTO_BUDGET, budgetExplicit: true, packing: 'cap_only' });
+ // Off the cap the old meanings stand: packing off, another unit, or no budget.
+ expect(await plan(5, { autoPacking: 'off' })).toMatchObject({ budgetTokens: 5, budgetExplicit: true, packing: 'off' });
+ expect(await plan(5, { returnUnit: 'page' })).toMatchObject({ unit: 'page', budgetTokens: 5 });
+ expect(await plan(undefined)).toMatchObject({ budgetTokens: 24000, budgetExplicit: false });
+ await expect(plan(4000, { autoPacking: 'widest' })).rejects.toMatchObject({ code: 'invalid_params', message: expect.stringContaining('auto_packing must be one of off, cap_only, breadth_capped, depth_first') });
+ // At the minimum a non-empty hit list yields non-empty evidence within it.
+ const r = rng(77);
+ for (let trial = 0; trial < 20; trial++) {
+ const pages = randomCorpus(r, 1 + Math.floor(r() * 5));
+ const hits = pages.map(p => hitFor(p, Math.floor(r() * p.chunks.length)));
+ for (const packing of CAP_PACKINGS) {
+ const { results } = await deliverEvidence(fakeEngine(pages), hits, capPlan(MIN_EXPLICIT_AUTO_BUDGET, packing), {});
+ expect(results.length).toBeGreaterThan(0);
+ expect(results[0].chunk_text.replace(EVIDENCE_CUT_MARKER, '').trim().length).toBeGreaterThan(0);
+ expect(recount(results)).toBeLessThanOrEqual(MIN_EXPLICIT_AUTO_BUDGET);
+ }
+ }
+ });
+
+ test('under the cap a snippet marker is paid from the row\'s own allocation, or left out when it cannot fit', async () => {
+ const page = chatPage(1, 30);
+ const { results, delivery } = await deliverEvidence(fakeEngine([page]), [hitFor(page, 1)], capPlan(4000), {});
+ const before = countEvidenceTokens(results[0].chunk_text);
+ const cap = results[0].chunk_text.length - 3;
+ const capped = capDeliveredSnippets(results, cap, { ...delivery, fallbacks: [...delivery.fallbacks] });
+ expect(capped[0].chunk_text).toContain('[truncated');
+ expect(countEvidenceTokens(capped[0].chunk_text)).toBeLessThanOrEqual(before);
+ // Without the cap the same snippet cap grows the row (the old behavior, kept for implied budgets).
+ const legacy = capDeliveredSnippets(results, cap, { ...delivery, auto_packing: undefined, fallbacks: [...delivery.fallbacks] });
+ expect(countEvidenceTokens(legacy[0].chunk_text)).toBeGreaterThan(before);
+ // A row too small to hold the marker keeps a shorter body and says so.
+ const tiny = [{ ...results[0], chunk_text: 'Short row of ten words that the cap trims here.' }];
+ const meta = { ...delivery, fallbacks: [...delivery.fallbacks] };
+ const out = capDeliveredSnippets(tiny, 20, meta);
+ expect(out[0].chunk_text).not.toContain('[truncated');
+ expect(countEvidenceTokens(out[0].chunk_text)).toBeLessThanOrEqual(countEvidenceTokens(tiny[0].chunk_text));
+ expect(meta.fallbacks).toEqual(expect.arrayContaining(['snippet_cap', 'snippet_marker_omitted']));
+ expect(meta.budget_used).toBe(recount(out));
+ });
+
+ test('search.auto_packing refuses unknown values at config set', () => {
+ for (const v of AUTO_PACKINGS) expect(searchConfigValueRefusal('search.auto_packing', v)).toBeNull();
+ expect(searchConfigValueRefusal('search.auto_packing', 'breadth')).toMatchObject({ message: expect.stringContaining('must be one of off, cap_only, breadth_capped, depth_first'), example: 'cap_only' });
+ });
+});
+
// ---------------------------------------------------------------------------
// Real ops on PGLite
// ---------------------------------------------------------------------------
@@ -722,6 +1094,140 @@ describe('ops', () => {
expect(block).toContain(text);
});
+ test('explicit budgets below the minimum are refused through query, search, recall and assemble_evidence; a bare query budget stays legacy chunk (G7)', async () => {
+ const msg = (name: string) => expect.stringContaining(`${name} must be at least ${MIN_EXPLICIT_AUTO_BUDGET} tokens under return_unit auto`);
+ await expect(op('query').handler(ctxOf(), { query: 'narwhal', return_unit: 'auto', token_budget: 10, expand: false })).rejects.toMatchObject({ code: 'invalid_params', message: msg('token_budget') });
+ await expect(op('search').handler(ctxOf(), { query: 'narwhal', token_budget: 5 })).rejects.toMatchObject({ code: 'invalid_params', message: msg('token_budget') });
+ await expect(op('recall').handler(ctxOf(), { query: 'narwhal', return_unit: 'auto', budget_tokens: 3 })).rejects.toMatchObject({ code: 'invalid_params', message: msg('budget_tokens') });
+ await expect(op('assemble_evidence').handler(ctxOf(), { hits: [{ source_id: 'default', slug: 'chat/session-1', chunk_id: 0 }], return_unit: 'auto', token_budget: 0 }))
+ .rejects.toMatchObject({ code: 'invalid_params', message: msg('token_budget') });
+ lastMeta = null;
+ const bare = await op('query').handler(ctxOf(), { query: 'narwhal', token_budget: 10, expand: false }) as SearchResult[];
+ expect(lastMeta!.delivery).toBeUndefined();
+ expect(bare.every(r => r.delivered === undefined)).toBe(true);
+ });
+
+ test('an explicit budget caps query, search, recall and assemble_evidence at the final boundary, snippet markers included', async () => {
+ const rowsCost = (rows: Array<{ title?: string; chunk_text: string }>) => recount(rows);
+ for (const budget of [MIN_EXPLICIT_AUTO_BUDGET, 60, 400, 3000]) {
+ const viaQuery = await op('query').handler(ctxOf(), { query: 'narwhal', return_unit: 'auto', token_budget: budget, expand: false }) as SearchResult[];
+ expect(lastMeta!.delivery).toMatchObject({ auto_packing: 'cap_only', budget_tokens: budget });
+ expect(rowsCost(viaQuery), `query @${budget}`).toBeLessThanOrEqual(budget);
+ expect(lastMeta!.delivery.budget_used).toBe(rowsCost(viaQuery));
+ const viaSearch = await op('search').handler(ctxOf(), { query: 'narwhal', token_budget: budget }) as SearchResult[];
+ expect(rowsCost(viaSearch), `search @${budget}`).toBeLessThanOrEqual(budget);
+ for (const snippet of [10, 40, 120]) {
+ const capped = await op('query').handler(ctxOf(), { query: 'narwhal', return_unit: 'auto', token_budget: budget, snippet_chars: snippet, expand: false }) as SearchResult[];
+ expect(rowsCost(capped), `query @${budget} snippet ${snippet}`).toBeLessThanOrEqual(budget);
+ expect(lastMeta!.delivery.budget_used).toBe(rowsCost(capped));
+ expect(lastMeta!.delivery.tokens_delivered).toBe(capped.reduce((n, r) => n + countEvidenceTokens(r.chunk_text), 0));
+ }
+ const recall = await op('recall').handler(ctxOf(), { query: 'narwhal', return_unit: 'auto', budget_tokens: budget }) as Record<string, any>;
+ expect(recall.delivery.auto_packing).toBe('cap_only');
+ expect(recall.delivery.budget_used).toBeLessThanOrEqual(budget);
+ const hits = await op('query').handler(ctxOf(), { query: 'narwhal', return_unit: 'chunk', expand: false }) as SearchResult[];
+ const assembled = await op('assemble_evidence').handler(ctxOf(), {
+ hits: hits.map(h => ({ source_id: h.source_id, slug: h.slug, chunk_id: h.chunk_id })), return_unit: 'auto', token_budget: budget,
+ }) as { results: SearchResult[]; delivery: { budget_used: number } };
+ expect(rowsCost(assembled.results), `assemble @${budget}`).toBeLessThanOrEqual(budget);
+ expect(assembled.delivery.budget_used).toBe(rowsCost(assembled.results));
+ }
+ // The remote clamp: the cap applies to the clamped value.
+ const remote = await op('search').handler(ctxOf({ remote: true }), { query: 'narwhal', token_budget: 90000, fields: 'full' }) as SearchResult[];
+ expect(lastMeta!.delivery).toMatchObject({ budget_tokens: 32000, budget_clamped: { requested: 90000, max: 32000 }, auto_packing: 'cap_only' });
+ expect(rowsCost(remote)).toBeLessThanOrEqual(32000);
+ });
+
+ test('search.auto_packing selects the packing; the library override wins per call; neither touches a call without a budget', async () => {
+ const baseline = async () => {
+ const out: string[] = [];
+ out.push(JSON.stringify(await op('search').handler(ctxOf(), { query: 'narwhal' })), JSON.stringify(lastMeta));
+ out.push(JSON.stringify(await op('query').handler(ctxOf(), { query: 'narwhal', expand: false })), JSON.stringify(lastMeta));
+ out.push(JSON.stringify(await op('query').handler(ctxOf(), { query: 'narwhal', return_unit: 'auto', expand: false })), JSON.stringify(lastMeta));
+ out.push(JSON.stringify(await op('recall').handler(ctxOf(), { query: 'narwhal' })));
+ const hits = await op('search').handler(ctxOf(), { query: 'narwhal', return_unit: 'chunk' }) as SearchResult[];
+ out.push(JSON.stringify(await op('assemble_evidence').handler(ctxOf(), { hits: hits.map(h => ({ source_id: h.source_id, slug: h.slug, chunk_id: h.chunk_id })), return_unit: 'auto' })));
+ return out;
+ };
+ const today = await baseline();
+ try {
+ for (const packing of AUTO_PACKINGS) {
+ await engine.setConfig('search.auto_packing', packing);
+ expect(await baseline(), packing).toEqual(today);
+ await op('query').handler(ctxOf(), { query: 'narwhal', return_unit: 'auto', token_budget: 3000, expand: false });
+ if (packing === 'off') expect(lastMeta!.delivery.auto_packing).toBeUndefined();
+ else expect(lastMeta!.delivery.auto_packing).toBe(packing);
+ }
+ await engine.setConfig('search.auto_packing', 'depth_first');
+ const hits = await op('search').handler(ctxOf(), { query: 'narwhal', return_unit: 'chunk' }) as SearchResult[];
+ const frozen = hits.map(h => ({ source_id: h.source_id!, slug: h.slug, chunk_id: h.chunk_id }));
+ for (const packing of AUTO_PACKINGS) {
+ const out = await assembleEvidenceForHits(engine, { hits: frozen, return_unit: 'auto', budget_tokens: 3000, auto_packing: packing });
+ expect(out.delivery!.auto_packing).toBe(packing === 'off' ? undefined : packing);
+ }
+ await expect(assembleEvidenceForHits(engine, { hits: frozen, return_unit: 'auto', budget_tokens: 3000, auto_packing: 'widest' as never }))
+ .rejects.toMatchObject({ code: 'invalid_params' });
+ } finally {
+ await engine.executeRaw(`DELETE FROM config WHERE key = 'search.auto_packing'`);
+ }
+ // An explicit 24,000 and the implied 24,000 resolve to plans that differ only in the flag.
+ const resolve = (budget: unknown) => resolveEvidencePlan(engine, { remote: false, returnUnit: 'auto', returnWindow: undefined, budget, snippetChars: undefined, snippetCap: 0, op: 'search' });
+ const [explicit, implied] = [await resolve(24000), await resolve(undefined)];
+ expect({ ...explicit!, budgetExplicit: false }).toEqual(implied!);
+ expect(explicit!.budgetExplicit).toBe(true);
+ });
+
+ test('think passes no budget, so its prompt is the same under every packing', 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 } };
+ } };
+ try {
+ for (const packing of AUTO_PACKINGS) {
+ await engine.setConfig('search.auto_packing', packing);
+ await runThink(engine, { question: 'narwhal launch march', client: client as never, remote: false, reference_date: '2026-10-09' } as never);
+ }
+ } finally {
+ await engine.executeRaw(`DELETE FROM config WHERE key = 'search.auto_packing'`);
+ }
+ expect(new Set(prompts).size).toBe(1);
+ });
+
+ test('frozen-hit delivery carries effective_date, and every field a reader consumes equals live query (both packings and today\'s auto)', async () => {
+ await engine.executeRaw(`UPDATE pages SET effective_date = '2026-03-04', effective_date_source = 'frontmatter' WHERE slug = 'chat/session-1'`);
+ try {
+ const hits = await op('query').handler(ctxOf(), { query: 'narwhal', return_unit: 'chunk', expand: false }) as SearchResult[];
+ expect(lastMeta!.delivery).toBeUndefined();
+ const frozen = hits.map(h => ({ source_id: h.source_id!, slug: h.slug, chunk_id: h.chunk_id }));
+ const consumed = (rows: SearchResult[]) => rows.map(r => ({
+ slug: r.slug, title: r.title, chunk_text: r.chunk_text, effective_date: r.effective_date, effective_date_source: r.effective_date_source,
+ unit: r.delivered?.unit, spans: r.delivered?.match_spans, tokens: r.delivered?.tokens, truncated: r.delivered?.truncated, reason: r.delivered?.reason,
+ fallback: r.delivered?.fallback_reason, unmapped: r.delivered?.unmapped_chunk_ids,
+ }));
+ const totals = (d: Record<string, any>) => ({ budget_used: d.budget_used, tokens_delivered: d.tokens_delivered, fallbacks: d.fallbacks, dropped_reasons: d.dropped_reasons, auto_packing: d.auto_packing });
+ let dated = 0;
+ for (const packing of AUTO_PACKINGS) {
+ await engine.setConfig('search.auto_packing', packing);
+ for (const budget of [400, 3000, undefined]) {
+ const live = await op('query').handler(ctxOf(), { query: 'narwhal', return_unit: 'auto', expand: false, ...(budget ? { token_budget: budget } : {}) }) as SearchResult[];
+ const liveDelivery = lastMeta!.delivery;
+ const assembled = await assembleEvidenceForHits(engine, { hits: frozen, return_unit: 'auto', ...(budget ? { budget_tokens: budget } : {}) });
+ expect(consumed(assembled.results as SearchResult[]), `${packing} @${budget}`).toEqual(consumed(live));
+ expect(totals(assembled.delivery!)).toEqual(totals(liveDelivery));
+ expect(evidenceFingerprint(assembled.results)).toBe(evidenceFingerprint(live));
+ for (const r of assembled.results.filter(x => x.slug === 'chat/session-1')) { expect(r.effective_date).toBe('2026-03-04'); dated++; }
+ // A page with no date reads null on both paths, never an invented date.
+ for (const r of assembled.results.filter(x => x.slug !== 'chat/session-1')) expect(r.effective_date).toBeNull();
+ }
+ }
+ expect(dated).toBeGreaterThan(0);
+ } finally {
+ await engine.executeRaw(`UPDATE pages SET effective_date = NULL, effective_date_source = NULL WHERE slug = 'chat/session-1'`);
+ await engine.executeRaw(`DELETE FROM config WHERE key = 'search.auto_packing'`);
+ }
+ });
+
test('thin-client skew warning fires only when the server dropped delivery', () => {
expect(deliveryVersionSkewWarning('query', { return_unit: 'page' }, { returned_count: 1 }, [])).toContain('v0.60.13.0');
expect(deliveryVersionSkewWarning('query', { return_unit: 'page' }, { delivery: {} }, [])).toBeNull();