Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
v0.60.13.0 feat(search): return_unit evidence delivery + 7 correctness fixes (#5769)
Garry Tan6c8373c3de9b
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex b9f07bdb1b..1ba25df157 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.60.12.0",+ "version": "0.60.13.0","description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.","author": {"name": "Garry Tan",diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex c770ad5739..bd5cae1ea9 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.60.12.0",+ "version": "0.60.13.0","description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.","author": {"name": "Garry Tan",diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.mdindex e9c629e904..9eba330261 100644--- a/BOOTSTRAP_FOR_AGENTS.md+++ b/BOOTSTRAP_FOR_AGENTS.md@@ -1,4 +1,4 @@-<!-- gbrain-runbook-stamp: 0.60.12.0 -->+<!-- gbrain-runbook-stamp: 0.60.13.0 --><!-- This stamp must equal the VERSION file at every release; CI enforces it(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it tothe installed binary and warns on skew. -->diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4ae94df2cc..2c75715710 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,86 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [0.60.13.0] - 2026-09-30++**Two things: your agent can now ask search for the whole conversation, section or page around each hit in the same call (off by default until a matched study shows it helps), and seven correctness fixes land, led by a privacy one: the entity card no longer shows remote agents that a private page links to a public one.**++When an agent searches your brain it gets ranked chunks. For questions that span several conversations, or ask when something changed, the answer often sits in the text around the chunk. In a fixed 100-question LongMemEval-S study (reranker off), the same reader answered 89 correctly from the full retrieved sessions and 65 from the top five chunks. Until now the agent had to call `get_page` once per hit to close that gap.++`search`, `query` and `recall` now take `return_unit`: `window` (the hit plus neighbor chunks), `section` (the enclosing section, or the conversation rounds around the hit), `page` (the whole page or session) or `auto` (page for conversations and short pages, section or window for long notes). The evidence arrives in each result's existing `chunk_text`, packed into your `token_budget` (default 6,000 tokens), with a `delivered` block saying which unit applied, where the hits sit in the text and what was cut. `think` gets the same through its own `think.return_unit` setting.++| | Before | After (opt-in) |+| --- | --- | --- |+| Surrounding conversation for a hit | one `get_page` call per hit | the same `search` / `query` / `recall` call |+| Budget | chunks skipped past `token_budget` | whole evidence packed into `token_budget`, each page keeps its matching span |+| Extra latency, 10K-page brain (warm p95) | — | 10–23 ms per request on PGLite and Postgres |+| Default responses | — | byte-identical (pinned against the previous release) |++The default stays `chunk`: nothing changes unless you or your agent ask. An earlier attempt to cut sessions down to "relevant" rounds lost answers (53/60 to 48/60, `docs/eval/ANSWER_PACKET_RESULTS.md`), so the default only flips if the gbrain-evals study shows a real gain; if only `page` helps, `page` stays an opt-in at its full token cost.++Things to watch: expansion never shows more than `get_page` would show the same caller. It removes takes, private fact rows and withdrawn facts from the whole page before cutting evidence, even on your own machine (use `get_page` for those), and it never includes page frontmatter. A page that became private, was deleted, or left your grant between the search and the expansion is dropped, not served from the old hit.++### Seven correctness fixes++Before this release, an agent connected over MCP could ask for the `entity` card (or `context_pack`) of a public page and see inbound links from private pages, including the private page's slug and the sentence it wrote. That is fixed, along with six smaller bugs in name resolution, federated recall, as-of facts, "last seen" and search date filters. Each one was found by the new gbrain-evals N3 (temporal and as-of), N4 (entity resolution) and N6 (visibility leak fuzz) categories, which score synthetic worlds with known answers, and each is now pinned by a test.++| Benchmark (synthetic worlds, $0, no keys) | Before | After |+| --- | --- | --- |+| Visibility leak fuzz: probes that leaked private content to a remote caller | 8 of 3,158 | 0 of 3,158 |+| Temporal as-of: `ontology_get` as-of accuracy | 99/104 | 104/104 |+| Temporal as-of: `chronicle_last_seen` probes right | 76/83 (mean error 16.3 days) | 83/83 (0 days) |+| Temporal as-of: bad date bounds rejected | 4/5 | 5/5 |+| Entity resolution: wrong merges (resolver / recall) | 1/136 / 3/144 | 0/136 / 0/144 |+| Entity resolution: exact-name floor (resolver / recall) | 47/48 / 49/50 | 48/48 / 50/50 |+| Entity resolution: recall correct refusals | 90.5% of 21 | 100% of 21 |++- **The entity card keeps private pages private.** For remote callers, `entity`, `context_pack` and `delta` now leave out inbound links from pages marked `visibility: private`, from derived pages (atoms and synthesized concepts, private by default) and from edges authored by a private page, and `backlink_count` stops counting them, matching `get_backlinks`. Links from soft-deleted pages are left out for every caller. Your own local CLI still sees private links.+- **A person's own name beats someone else's former name.** When one page is titled "Jordan Lee-Example" and another page lists "Jordan Lee-Example" as an alias, the name now resolves to the first page. `remember`, `recall` and save-time fact attribution follow.+- **Federated recall stops mixing up namesakes.** With a grant over several sources, `recall({ entity })` used to merge two different people who share a slug in two sources. It now returns no facts and an `ambiguous_entity` list naming each `(source_id, entity_slug)`, so the agent can pick one with `source_id`. Pages linked with `entity_identity_link` still merge. Every recalled fact now carries `source_id`.+- **A stint learned late stays in as-of answers.** If you record that someone works at a company, then later learn they also worked there years earlier, `ontology_get --asof` now returns the earlier stint instead of nothing.+- **"Last seen" is exact.** `chronicle_last_seen` no longer credits `people/kim-example` with sightings of `people/kim-example-2` (it matches the exact slug or a wikilink to it), and a late-evening event no longer outranks a row dated the next day, so it stops reporting the day before.+- **Bad search dates fail loudly.** `query --since "May 5"` used to return an empty list. Search date bounds now accept only `YYYY-MM-DD`, an ISO timestamp or a duration like `7d`, and anything else is rejected with a clear message.++### To take advantage of v0.60.13.0++`gbrain upgrade`. There is no migration. Agents that read `recall` results over several sources should handle the new `ambiguous_entity` field. To try evidence delivery on one question:++```bash+gbrain query "when did the launch move?" --return-unit page --token-budget 6000+gbrain search "acme-example renewal" --return-unit window --return-window 2+```++**Say to your agent:** *"Search my brain for what we decided about the acme-example renewal and read the whole conversations, not just snippets."*++The contract, the fallback codes and the benchmark are in `docs/evidence-delivery.md`. To make an expanded unit the default for search (not recommended until the study lands): `gbrain config set search.return_unit auto`; `gbrain config set search.return_unit chunk` turns it off again.++### Itemized changes++#### Evidence delivery+- New `src/core/search/evidence-delivery.ts`: one assembler shared by `search`, `query`, `recall` and `think`. It groups hits by page, reads each page's authorization, body and the hit chunks in one batched query keyed by page id (`getChunkWindows`, SQL once in `engine-sql/chunks.ts` for both engines), sanitizes the whole body before slicing, locates the hits in it so chunk overlap never duplicates text, cuts the requested unit, and packs blocks by rank with a per-page floor. `page` evidence is byte-identical to the page body minus frontmatter and protected content.+- Params `return_unit` and `return_window` on `search`, `query`, `recall`; `token_budget` declared on `search` and `query` (on `query` it budgets the delivered evidence when a non-chunk unit applies). Config keys `search.return_unit`, `search.return_window`, `search.return_budget_default` (6,000), `search.return_budget_max_remote` (32,000) and `think.return_unit`.+- Additive `delivered` per result (`unit`, `chunk_ids`, `match_spans` as UTF-16 offsets, `tokens`, `truncated`, `revision`, `unmapped_chunk_ids`, `fallback_reason`) and a `delivery` meta block (`_meta.retrieval.delivery` over MCP, top-level on `recall`). `gbrain search --explain` prints an evidence line.+- Tokens are counted with cl100k per line (CJK-correct), after secret redaction. Blocks are capped at 60,000 characters so large pages are cut, not replaced by the output-limit marker. Remote budgets are clamped and the clamp is reported.+- An explicit `snippet_chars` still wins; an explicit `return_unit` skips the subagent snippet default; a config-level unit never overrides the subagent default.+- Bad `return_unit` / `return_window` values fail with `invalid_params` naming the allowed values and an example call. A thin client whose server ignores `return_unit` prints one warning naming the minimum server version.+- New read op `assemble_evidence` and library call `assembleEvidenceForHits` return exactly the evidence `query` returns for a frozen ordered hit list, with `evidenceFingerprint`, exported as `gbrain/search/evidence-delivery` for gbrain-evals.++#### Safety+- Every delivered page is re-authorized under the caller's current scope (source grant, private pages, deleted, quarantined, archived sources, current text revision); stale or cached hits are dropped, never served from hit text. Leak canaries (private facts, takes, withdrawn facts, malformed protected tails, timeline facts, private pages, derived atoms, same-slug pages in another source, grant revocation, a page turning private, an edit mid-flight) pass on PGLite and Postgres through local ops, MCP stdio and MCP HTTP, with public presence controls.++#### Correctness fixes (found by gbrain-evals N3 / N4 / N6)+- `src/core/verbs/entity-card.ts`: the card's inbound-edge query and `backlink_count` apply `privatePagesFilterFragment` and `privateLinkOriginFilterFragment` for untrusted callers and skip soft-deleted referrers; outgoing links and recent timeline rows use the same private-page gate.+- `src/core/entities/resolve.ts`: an exact slug-basename match on a live page resolves before the alias arm in both `resolveEntitySlug` and `resolveEntitySlugWithSource`.+- `src/core/ops/facts.ts`: `recall`'s entity arms (with and without `since`) refuse namesakes in several sources unless an entity-identity group links them; fact rows add `source_id`. New `identityIdsForPages` in `src/core/entity-identity.ts`.+- `mergeOntologyFact` (both engines): a same-value observation dated before the current open value's start is stored as a live row, not an expired corroboration (`isBackdatedObservation` in `src/core/chronicle/ontology.ts`).+- `src/core/engine-sql/timeline.ts` `getLastSeen`: exact and wikilink matching with LIKE metacharacters escaped; newest projected day first, event instant only within a day.+- `src/core/search/date-bounds.ts`: strict ISO-8601 grammar; `src/core/search/hybrid/arms.ts` surfaces a datetime cast error (SQLSTATE 22007/22008) instead of treating it as a degraded arm.++#### Tests and tooling+- Fix tests: `test/entity-card-private-backlinks.test.ts`, `test/entity-resolve-exact-name-floor.test.ts`, `test/recall-federated-namesakes.test.ts`, `test/ontology-backdated-same-value.test.ts`, `test/chronicle-last-seen-matching.test.ts`, `test/search-date-bound-non-iso.test.ts`, plus Postgres arms in `test/e2e/chronicle-last-seen-postgres.test.ts` and `test/e2e/ontology-merge-parity.test.ts`.+- `test/evidence-delivery.test.ts` (stitching round trip, allocation and boundary properties, units, errors, snippet precedence, recall and think wiring), `test/evidence-delivery-golden.test.ts` (default output byte-identical to v0.60.12.0), `test/e2e/evidence-delivery-leak.test.ts`, `test/e2e/evidence-delivery-parity.test.ts` (engine parity and query/assemble parity).+- `scripts/bench-evidence-delivery.ts` measures the stage's added latency per unit (cold, warm, large pages, CJK, 8-way concurrency) on PGLite and Postgres.+## [0.60.12.0] - 2026-09-30**Nothing you use changes. Under the hood, GBrain's storage code is now written once instead of twice, and its biggest files are split into pieces a person can read, so fixes stop landing on one database and missing the other.**diff --git a/VERSION b/VERSIONindex 26c214fe29..442a06ccac 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-0.60.12.0+0.60.13.0diff --git a/docs/TOOL_CATALOG.md b/docs/TOOL_CATALOG.mdindex 8e9969835a..ed7f277941 100644--- a/docs/TOOL_CATALOG.md+++ b/docs/TOOL_CATALOG.md@@ -4,7 +4,7 @@<!-- Regenerate: bun run scripts/generate-tool-catalog.ts --><!-- Freshness-guarded by scripts/check-tool-catalog-fresh.sh (bun run verify). -->-Every non-localOnly operation on the MCP surface: 133 tools across 23 areas. **Starter** marks membership in the ~38-op `starter` surface (`src/mcp/surface.ts`); **Gate** names the config key that must be true before remote callers see/call the op (`gbrain config set <key> true`). What a given token actually sees is further filtered per request by scope, bound-client fence, publish gates, and the per-client surface — see `docs/operations/mcp-surface-runbook.md`. Area names are non-contractual groupings.+Every non-localOnly operation on the MCP surface: 134 tools across 23 areas. **Starter** marks membership in the ~38-op `starter` surface (`src/mcp/surface.ts`); **Gate** names the config key that must be true before remote callers see/call the op (`gbrain config set <key> true`). What a given token actually sees is further filtered per request by scope, bound-client fence, publish gates, and the per-client surface — see `docs/operations/mcp-surface-runbook.md`. Area names are non-contractual groupings.## admin@@ -192,6 +192,7 @@ Every non-localOnly operation on the MCP surface: 133 tools across 23 areas. **S| Tool | Description | Scope | Starter | Gate ||---|---|---|---|---|+| `assemble_evidence` | Deliver whole evidence for an ordered list of search hits (each {source_id, slug, chunk_id} from a prior search/query result): the same windows, sections or pages `query` returns with return_unit, packed into token_budget. | read | | || `cache_stats` | Semantic query-cache introspection: resolved knobs (enabled, similarity threshold, TTL) plus row counts and total hits. | admin | | || `query` | Hybrid search with vector + keyword + multi-query expansion. | read | yes | || `search` | Cheap hybrid search (vector + keyword + RRF) with no LLM expansion. | read | yes | |diff --git a/docs/architecture/RETRIEVAL.md b/docs/architecture/RETRIEVAL.mdindex 23270afae7..78d7653409 100644--- a/docs/architecture/RETRIEVAL.md+++ b/docs/architecture/RETRIEVAL.md@@ -366,6 +366,28 @@ before any other cell is read.Each stage is testable in isolation. Each stage is replaceable. The whole pipeline is < 1ms of orchestration cost; the latency budget goes to the upstream HTTP calls (embedding, rerank) and the index scans.+## Evidence delivery: whole evidence after ranking++Ranking decides which pages matter; the reader still needs enough of each page+to answer. `return_unit` (`window`, `section`, `page`, `auto`; default `chunk`)+adds an opt-in stage after ranking, cache and capture, and before output+redaction and snippet capping, shared by `search`, `query`, `recall` and+`think` (via `think.return_unit`). It groups the ranked hits by page, reads+every needed neighbor chunk in ONE batched, page_id-keyed query that+re-authorizes each page under the caller's current scope, sanitizes each+page's complete body before slicing, locates the hit chunks in it (so chunk+overlap never duplicates text), cuts the requested unit around the hits,+and packs blocks by rank into the token budget with a per-page floor so lower+ranked sessions keep their matching span. The strict protected-body sanitizer+runs on the whole body first, so delivered evidence never contains more than+`get_page` returns to the same caller. With the default `chunk` the stage does not run and responses are+byte-identical. The measured motivation (full sessions 89/100 against+top-5 chunks 65/100 on a fixed LongMemEval-S subset, reranker off) and the+earlier failed lexical excerpt selector (`docs/eval/ANSWER_PACKET_RESULTS.md`)+are why `page` is the reference and the default stays `chunk` until a matched+study shows a benefit. Contract, algorithms and latency:+[`docs/evidence-delivery.md`](../evidence-delivery.md).+## How to verify on your own brain```bashdiff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.mdindex 250706c879..3bf43b170a 100644--- a/docs/architecture/key-files/core-search-2.md+++ b/docs/architecture/key-files/core-search-2.md@@ -3,6 +3,10 @@[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.+- `src/core/search/evidence-delivery.ts` — the `return_unit` evidence assembler (opt-in; default `chunk` = inert, byte-identical off path). `resolveEvidencePlan` validates `return_unit` / `return_window` (invalid_params naming the allowed values and an example), reads `search.return_unit` / `think.return_unit`, `search.return_window`, `search.return_budget_default` (6,000) and clamps remote budgets to `search.return_budget_max_remote` (32,000, reported). Snippet precedence: explicit `snippet_chars` > explicit `return_unit` > subagent default cap > config unit. `deliverEvidence` groups hits by page_id (one block per page at its best rank), makes ONE `engine.getChunkWindows` call (re-authorizes every page; unauthorized pages are dropped, never served from hit text), builds the page text from the stored body sanitized whole before slicing (`pageEvidenceText`: compiled truth + serializer timeline sentinel + timeline; frontmatter excluded), locates the hit chunks in it (`locateChunks`: exact, then whitespace-insensitive, since the chunker trims and folds whitespace), cuts `window` / `section` (ATX headings outside code fences, or conversation rounds detected structurally, never by page type) / `page` / `auto`, counts tokens as the sum of per-line cl100k counts, reserves each page's matching span before enriching by rank, caps blocks at 60,000 characters, redacts secrets before final accounting, and returns NEW rows with `delivered` plus a `delivery` meta. Fetch failure/timeout (5 s) falls back to the hit chunk only for live hits. `assembleEvidenceForHits` / op `assemble_evidence` deliver the exact evidence `query` returns for a frozen `(source_id, slug, chunk_id)` list; `evidenceFingerprint` hashes it (gbrain-evals E1/E3 parity). Normative spec: `docs/evidence-delivery.md`. Tests: `test/evidence-delivery.test.ts`, `test/evidence-delivery-golden.test.ts`, `test/e2e/evidence-delivery-leak.test.ts`, `test/e2e/evidence-delivery-parity.test.ts`; bench `scripts/bench-evidence-delivery.ts`.++- `src/core/search/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.+- `src/core/search/output-redaction.ts` — copies retrieval results and metadata before output sanitation, sharing the canonical `secret-scan.ts` plan and echo dictionary. Keyword, hybrid, image, exact and CRAG paths sanitize after internal grading/capture and before snippet truncation; CLI search/query JSON, explain and human rendering repeat the defense-in-depth pass. Identity fields (`id`, `slug`, `source_id`, `page_id`, `chunk_id`, `message_id`, `thread_id`, `graph_session_prefix`, relational seed/path, `superseded_by`) remain byte-identical: never put secrets in IDs. Each field is capped at 64 Ki UTF-16 characters, the response at 1 Mi characters/8192 text fields, and nesting at 24 levels; oversized/unscannable text becomes `<REDACTED:output_limit>`. Unknown formats, high-entropy assignments and short fragments can escape default detection. This is output hygiene, not authorization or provider/eval no-egress; internal pages and capture retain originals. Tests: `test/search/output-redaction.serial.test.ts`, `test/search/output-redaction.test.ts`.- `src/core/search/return-policy.ts` (default OFF) — intent-aware adaptive return-sizing. Pure, dependency-light module that trims the final ranked candidate set to an intent-driven cap instead of returning the full top-K. `entity` intent gets a tight cap; `temporal`/`event`/`general` get a recall-preserving cap (`concept` is coerced to `general` by `hybrid.ts` before the call — concept queries want breadth). A `minKeep` failsafe (≥1) guarantees a human never gets a silent blank when candidates exist. WHY a cap, not a score-cliff detector: PrecisionMemBench instrumentation (gbrain-evals) measured the rank1→rank2 RRF gap is ~identical whether rank-1 is correct (0.602) or wrong (0.569) — mechanical decay, not a separatrix; rank-1 is right in 94% of single-answer cases, so "return a tight set" is the whole win and cliff-cutting just adds noise. Exports `AdaptiveReturnConfig`, `DEFAULT_ADAPTIVE_RETURN` (frozen: `enabled=false`, `entityMax=2`, `otherMax=6`, `minKeep=1`), `AdaptiveReturnDecision` (`{applied, intent, cap, kept, total}`), `AdaptiveReturnInput` (`boolean | Partial<AdaptiveReturnConfig> | undefined`), `adaptiveReturnFromConfig(cfg)`, `resolveAdaptiveReturn(perCall, fromConfig)` (defaults → config → per-call merge), `adaptiveReturnEnabled(...)` (cache-skip gate check), `applyAdaptiveReturn(results, intent, cfg)` (the trim). Config knobs (DB or file plane): `search.adaptive_return` (master switch), `search.adaptive_return_entity_max`, `search.adaptive_return_other_max`, `search.adaptive_return_min_keep` (each clamped ≥1). Wired into `hybridSearch` AFTER `applyReranker`, BEFORE the `limit` slice, and ONLY on the first page (`offset===0`) — paginating a confidence-gated set is incoherent, so paginated calls fall through to the fixed limit. Stamps the decision onto `HybridSearchMeta.adaptive_return` for `gbrain search --explain`. `hybridSearchCached` SKIPS the cache when the gate is on (a trimmed set must not be served to a gate-off lookup and vice versa). `SearchOpts.adaptiveReturn` + `HybridSearchMeta.adaptive_return` declared in `src/core/types.ts`. Agent-facing: the `query` op (`src/core/operations.ts`) exposes an `adaptive_return` boolean param whose description instructs the agent WHEN to set it (single-answer → on; breadth/exploration → off; pass `limit:1` for a hard single-answer cap), threaded into `hybridSearchCached` — end users never touch the config knob; their agent decides per query (same pattern as `salience`/`recency`). Pinned by `test/search/return-policy.test.ts` (mechanism) + `test/search/query-op-adaptive-return.test.ts` (agent surface: param exists + description teaches both directions + the never-empty contract).diff --git a/docs/evidence-delivery.md b/docs/evidence-delivery.mdnew file mode 100644index 0000000000..2a5e7c694c--- /dev/null+++ b/docs/evidence-delivery.md@@ -0,0 +1,330 @@+# Evidence delivery (`return_unit`)++> Status: shipped opt-in. The default stays `chunk` until the matched study in+> gbrain-evals shows a benefit (full sessions 89/100 against top-5 chunks+> 65/100 on a fixed LongMemEval-S subset, reranker off; an earlier lexical+> excerpt selector lost 53/60 → 48/60, see+> [`docs/eval/ANSWER_PACKET_RESULTS.md`](eval/ANSWER_PACKET_RESULTS.md)). If+> only `page` recovers the gap, `page` stays a documented opt-in at its full+> token cost.++Search returns ranked **chunks**. An agent that needs the surrounding+conversation or section has to call `get_page` for each hit. Evidence delivery+lets `search`, `query`, `recall` and `think` return the surrounding evidence in+the same call: a window of neighboring chunks, the enclosing section, or the+whole page, packed into a token budget.++It is **opt-in**. With `return_unit` omitted and the config at its default+(`chunk`), every response is byte-identical to earlier releases.++**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."*++## Quick start++```bash+# CLI+gbrain query "when did we move the launch?" --return-unit page --token-budget 6000+gbrain search "acme-example renewal" --return-unit window --return-window 2+gbrain recall --query "renewal terms" --return-unit section --budget-tokens 4000+```++```jsonc+// MCP+{ "name": "query", "arguments": { "query": "when did we move the launch?", "return_unit": "page", "token_budget": 6000 } }+```++## Units++| `return_unit` | What each result's `chunk_text` holds | Typical cost |+|---|---|---|+| `chunk` (default) | The ranked chunk only (today's behavior). | ~300–450 tokens per result |+| `window` | The hit chunk plus `return_window` (1–3, default 1) neighbor chunks on each side, same page. Overlapping windows merge. | ~3× chunk per result |+| `section` | The enclosing markdown section (by ATX heading). On conversation pages: the user→assistant rounds that overlap the hit. No structure → falls back to `window`. | varies |+| `page` | The whole page or session, capped at 60,000 characters and by the budget. | whole page |+| `auto` | `page` for conversation-shaped pages and short pages; `section` for long pages with headings; `window` otherwise. Each result's `delivered.unit` says which branch ran. | budget-bound |++Use `page` for multi-session / temporal questions where the answer depends on+the whole conversation. Use `window` when you only need local context.++## Parameters and config++Per-call params on `search`, `query`, `recall`:++- `return_unit`: `chunk` | `window` | `section` | `page` | `auto`. Default from+ config `search.return_unit` (default `chunk`).+- `return_window`: integer 1–3, default from `search.return_window` (default 1).+ Used by `window` (and by the `section`/`auto` fallbacks to `window`).+- Budget: `token_budget` on `search` / `query`, `budget_tokens` on `recall`.+ When a non-`chunk` unit applies and no budget is given,+ `search.return_budget_default` (default 6,000) applies. Remote callers are+ clamped to `search.return_budget_max_remote` (default 32,000); the clamp is+ reported in `delivery.budget_clamped` and `delivery.fallbacks`, never raised.++Think reads `think.return_unit` (default `chunk`) and never+`search.return_unit`, so flipping search's default does not change `think`.++Config keys: `search.return_unit`, `search.return_window`,+`search.return_budget_default`, `search.return_budget_max_remote`,+`think.return_unit`. Kill switch: `gbrain config set search.return_unit chunk`+(or pass `return_unit: "chunk"` per call).++### Precedence with `snippet_chars`++1. An explicit `snippet_chars` wins: delivered blocks are capped at that many+ characters (spans are clipped, `delivered.truncated` becomes true and+ `snippet_cap` is reported).+2. Then an explicit `return_unit`: the subagent default snippet cap is skipped+ for its blocks.+3. Then the subagent default snippet cap (`agent.search_snippet_chars`, 300):+ when it applies, a config-level `search.return_unit` does **not** expand.+4. Then `search.return_unit` from config.++## Response shape (additive)++When a non-`chunk` unit is applied, each result's existing `chunk_text`+carries the delivered evidence (no duplicated body field), and each result+gains `delivered`:++```jsonc+"delivered": {+ "unit": "page", // applied unit for this block: window | section | page | chunk (fallback)+ "chunk_ids": [812, 815], // every ranked hit merged into this block, rank order (first = the result's own chunk_id)+ "match_spans": [ // where each hit chunk sits in chunk_text+ { "chunk_id": 812, "start": 0, "end": 1840 },+ { "chunk_id": 815, "start": 5210, "end": 6933 }+ ],+ "tokens": 2311, // tokens of chunk_text (delivery.tokenizer)+ "truncated": false, // true when the unit was cut (budget, 60,000-char cap, fetch radius, snippet cap)+ "revision": "3f0c…", // pages.knowledge_revision the text was read from+ "unmapped_chunk_ids": [], // hits whose chunk is no longer in the current revision (present only when non-empty)+ "fallback_reason": "fetch_failed" // present only when the block fell back to the hit chunk text+}+```++`match_spans` are **UTF-16 code-unit offsets** (JavaScript string indices) into+the returned `chunk_text`, computed after every text transformation (sanitizing,+cuts, omission lines and secret redaction). The text carries no inline markers.+A hit whose chunk cannot be located is listed in `unmapped_chunk_ids` instead.++One result is returned per page, at the page's best rank. `chunk_id`,+`chunk_index`, `score` and the other ranking fields stay those of the page's+best-ranked hit (anchor provenance).++Response meta (`_meta.retrieval.delivery` over MCP; top-level `delivery` on+`recall`):++```jsonc+"delivery": {+ "requested_unit": "auto",+ "applied_unit": "auto", // "chunk" when the stage could not run at all+ "return_window": 1,+ "budget_tokens": 6000,+ "budget_used": 5874, // title + chunk_text tokens of every delivered block (≤ budget_tokens)+ "tokens_delivered": 5790, // Σ delivered.tokens+ "tokenizer": "cl100k", // "heuristic" when the encoder is unavailable+ "coordinates": "utf16",+ "blocks": 4,+ "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 }+}+```++`recall` keeps its frozen v1 fields (`chunk`, `evidence`, char/4 packing via+`budget_tokens`); with a non-`chunk` unit its `results[].chunk` carries the+delivered text and each result gains `delivered`.++### Fallback and drop codes++| Code | Meaning | What the caller gets |+|---|---|---|+| `fetch_failed` / `fetch_timeout` | The neighbor fetch errored or exceeded 5 s. | The hit chunk (from this request's live retrieval), `fallback_reason` set. |+| `unsealed_page` | The page's chunks predate the protected-body index (`gbrain repair safe-chunks`). | The hit chunk, `fallback_reason` set. |+| `row_limit` | The request hit the budget-derived row cap before this page's rows. | The hit chunk, `fallback_reason` set. |+| `no_section_structure` | `section` found no headings or speaker turns. | A `window` block (`delivered.unit: "window"`). |+| `no_text_chunks` / `anchor_not_fetched` | The page has no text chunks in reach, or none of its hits' chunks were read. | The hit chunk, `fallback_reason` set. |+| `page_missing` | A hit carried no page id (cannot be re-authorized by id). | The hit chunk (live hits only), `fallback_reason` set. |+| `redaction_unmapped` | Secret redaction changed a block. | Redacted block; its spans move to `unmapped_chunk_ids`. |+| `image_query_unsupported` | `query` with `image`: image hits are never expanded. | Plain image results; meta says so. |+| `snippet_cap` | An explicit `snippet_chars` cut a block. | Capped block, `truncated: true`. |+| `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). |++## Errors++An unknown `return_unit` or an out-of-range `return_window` fails with+`invalid_params`, naming the allowed values and an example call, e.g.++```+return_window must be an integer from 1 to 3 (got 7). Example: {"query": "launch date", "return_unit": "window", "return_window": 2}+```++A thin client talking to an older server that ignores `return_unit` prints one+warning naming the minimum server version.++## Guarantees++- **Authorization.** Every delivered block is re-read under the caller's+ current read scope (source scope, `visibility: private`, deleted,+ quarantined, archived sources, current text projection) in one batched query+ keyed by `page_id`, never by slug. A page that no longer passes is dropped.+- **Protected content.** Evidence text is cut from the page's stored body,+ sanitized WHOLE before any slicing with the same strict boundary the chunker+ uses (Takes fences removed, only world and not-withdrawn Facts rows kept,+ malformed or unterminated protected tails dropped, materialized markers+ stripped), `compiled_truth` and `timeline` each sanitized whole. This applies+ to every caller, including trusted local ones. Chunks only anchor the hits in+ that text, and the page must hold a sealed chunk index. Delivered text never+ contains anything `get_page` would not return to the same caller.+ `detail: "low"` never adds timeline text.+- **Frontmatter is not evidence.** Page frontmatter (YAML metadata) is never+ part of delivered text; `page` text is the sanitized body only.+- **Non-mutation.** The stage returns new result objects and never mutates or+ caches expanded text.+- **Bounded work.** One engine query per request. It reads each hit page's+ body once (bounded by the import size cap) plus the chunks within+ ±`return_window` of each hit; each block ≤ 60,000 characters (under the+ 64 KiB output-redaction field limit).++## Algorithms (normative; E1 depends on them)++1. **Group.** Hits are grouped by `page_id` in rank order; the block takes the+ page's best rank. Fenced-code chunks (duplicates of page text) and image+ chunks never contribute neighbor text.+2. **Fetch.** One query returns each page's authorization, seal, stored body+ and the chunks within ±`return_window` of each hit (at most 1,024 rows).+3. **Page text and anchors.** The page text is `sanitize(compiled_truth)`,+ plus `\n\n<!-- timeline -->\n\n` + `sanitize(timeline)` when the+ timeline is non-empty after sanitizing and `detail` is not `low` (the join+ `serializeMarkdown` writes). Each fetched chunk is located in that text in+ `chunk_index` order: exact match first, then a whitespace-insensitive match+ (the chunker trims chunks and folds some whitespace-only runs, so chunk text+ is not always verbatim). Overlapping chunks therefore never duplicate text:+ `page` evidence with an unlimited budget is byte-identical to the page text+ (trailing whitespace trimmed). Non-contiguous selections join with the+ omission line `\n\n[…]\n\n`.+4. **Units.** `section`: the nearest preceding ATX heading (outside fenced+ code) through the next heading of the same or higher level; unioned across+ hits. Conversation pages (≥ 4 speaker-turn lines such as `**user:**` /+ `**assistant:**`, `User:`, `Speaker 2:`, with ≥ 2 distinct labels and ≥ 3+ label changes; page `type` is ignored) use rounds: a round starts at each+ `user`/`human` turn (or the first label seen). `auto`: conversation → `page`;+ else ≤ 3 chunks → `page`; else headings present → `section`; else `window`.+5. **Pieces.** The unit text is split into lines; lines over 400 characters+ split at whitespace. Token counts are the sum of per-piece cl100k counts+ (plus the omission line and the title), so the count is deterministic and+ CJK-correct.+6. **Allocate.** Budget `B` covers title + `chunk_text` of every block.+ *Reserve:* walk blocks by rank; each block's floor is its title plus the+ pieces covering its best hit; a block whose floor does not fit is dropped+ (`budget_floor`), later smaller blocks may still fit; if rank one alone+ exceeds `B` it is cut to fit (`truncated`). *Enrich:* walk kept blocks by+ rank; add pieces in priority order (other hits' pieces by hit rank, then by+ 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.+7. **Redact.** Blocks pass through the same secret redaction as every search+ response before spans and tokens are computed.++## Latency (added by the stage)++`bun scripts/bench-evidence-delivery.ts --pages 10000 --iterations 200 [--postgres <url>]`+builds a synthetic brain (60% curated notes of 3–12 chunks, 30% conversation+sessions of 6–24 chunks, 5% 120-chunk pages, 5% CJK pages; sealed and+projection-current) and times `deliverEvidence` on ranked lists of 5 hits over+distinct random pages with a 6,000-token budget. Measured 2026-09-30 on a+4-vCPU / 15 GB cloud VM, Bun 1.3.14; PGLite in-memory; Postgres 16 + pgvector+in local Docker. Milliseconds.++| Engine | Unit | Cold | Warm p50 | Warm p95 | Large-page p95 | CJK p95 | 8 concurrent p95 | Rows / KB read per request |+|---|---|---|---|---|---|---|---|---|+| PGLite | window | 86.0 | 8.4 | 10.4 | 12.1 | 4.8 | 67.5 | 13.8 / 93.1 |+| PGLite | section | 8.6 | 7.8 | 9.6 | 14.9 | 4.8 | 66.0 | 13.6 / 87.6 |+| PGLite | page | 14.8 | 14.7 | 16.0 | 27.9 | 5.7 | 113.2 | 13.8 / 87.8 |+| PGLite | auto | 14.8 | 13.4 | 17.2 | 15.2 | 6.7 | 112.0 | 13.7 / 83.6 |+| Postgres | window | 176.7 | 8.3 | 11.8 | 12.8 | 5.3 | 64.2 | 13.8 / 93.1 |+| Postgres | section | 8.5 | 7.8 | 10.8 | 18.6 | 10.5 | 57.6 | 13.6 / 87.6 |+| Postgres | page | 17.0 | 15.5 | 22.6 | 26.6 | 7.3 | 108.7 | 13.8 / 87.8 |+| Postgres | auto | 15.4 | 13.3 | 16.5 | 14.7 | 5.6 | 104.8 | 13.7 / 83.6 |++Every unit stays under the 50 ms warm p95 target on the 10K-page brain. Every+request made exactly one engine call (no N+1); it reads the hit chunks and+each hit page's body once. The first call in a process pays a one-time cl100k+encoder load and query planning (the "cold" window row). Tails are noisy on a+shared VM: an earlier PGLite run with another process busy measured 56.5 ms+large-page p95 for `page` and 34.8 ms warm p95 for `auto`. Under 8+concurrent requests each request waits for the others' JavaScript work+(sanitizing, chunk location and token counting run on the single event loop), so per-request+p95 grows to about 8 × the warm cost while throughput stays the same.++## Frozen-candidate interface (gbrain-evals, E1/E3 parity)++Evaluations must measure the code that ships. Two entry points produce, for an+ordered hit list, **exactly** the evidence the `query` op would return:++### Library (trusted local, in-process)++```ts+import { assembleEvidenceForHits, evidenceFingerprint } from 'gbrain/search/evidence-delivery';++const out = await assembleEvidenceForHits(engine, {+ hits: [ { source_id: 'default', slug: 'chat/session-0412', chunk_id: 8812 }, /* rank order */ ],+ return_unit: 'page', // chunk | window | section | page | auto+ return_window: 1, // optional+ budget_tokens: 6000, // optional; same default/clamp rules as query+ detail: 'medium', // optional, as query+ caller: { remote: false }, // optional; { remote: true, sourceIds: [...] } emulates a remote caller+});+// 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, ... }+// 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+```++`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).++### Op `assemble_evidence` (any transport: local CLI, MCP stdio, HTTP)++Read scope. Params: `hits` (array of `{ source_id, slug, chunk_id }`, rank+order, max 50), `return_unit` (required), `return_window`, `token_budget`,+`detail`. Returns `{ results, delivery, unresolved }` with the same content as+the library call for that caller. Remote callers get the same filtering as+`query` (private pages hidden, sealed pages only, grants enforced).++### Fingerprint++`evidenceFingerprint(results)` is the SHA-256 (hex) of+`JSON.stringify(results.map(r => [r.source_id ?? 'default', r.slug, r.chunk_text, r.delivered?.unit ?? 'chunk', r.delivered?.chunk_ids ?? [r.chunk_id]]))`.+It is identical for the `query` op's results and for `assemble_evidence` /+`assembleEvidenceForHits` given the same ordered hits, unit, window, budget and+caller class, on both engines. `test/evidence-delivery-parity.test.ts` pins+this.++### Parity recipe for E3++1. Run `query` with `return_unit: "chunk"` and **no** `token_budget` to get the+ ranked hits (or use the frozen list). With a non-`chunk` unit, `token_budget`+ budgets the delivered evidence instead of pruning chunks, so the ranked list+ the stage sees equals the chunk-mode list without a budget.+2. Run `assemble_evidence` with those hits and the policy, and `query` with+ the same policy and budget.+3. Fingerprints must match; any difference means the product path does not+ deliver the evidence the experiment assumed.++Always pass `expand: false` to `query` for E3. `query` otherwise runs LLM+multi-query expansion by default, which can change the ranked list from run to+run (retrieval drift, not a delivery difference). `assemble_evidence` does no+retrieval at all, so it is deterministic for a given hit list, page revision,+unit, window and budget.diff --git a/llms.txt b/llms.txtindex 31cca47994..8fdd99e83d 100644--- a/llms.txt+++ b/llms.txt@@ -38,6 +38,7 @@ Repo: https://github.com/garrytan/gbrain- [docs/guides/quiet-hours.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/quiet-hours.md): Notification hold + timezone-aware delivery.- [docs/guides/scaling-skills.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/scaling-skills.md): Three-tier architecture for agents with 300+ skills: always-loaded, resolver-routed, and dormant. Per-turn token math, the v0.41.7.0 compact list-format resolver, and the `gbrain doctor` safety net. 306 skills, ~21K tokens freed per turn, zero capability loss.- [docs/guides/push-context.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/push-context.md): Push-based context: the brain volunteers confidence-gated pages from the rolling conversation window. Three channels (ambient reflex, volunteer_context op, gbrain watch), config knobs, and the volunteered-vs-used feedback loop.+- [docs/evidence-delivery.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/evidence-delivery.md): Evidence delivery (`return_unit`): window / section / page / auto evidence instead of chunks on search, query, recall and think, packed into a token budget; response fields, fallback codes, authorization guarantees, latency, and the frozen-hit `assemble_evidence` interface for evals.- [docs/guides/github-source.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/github-source.md): Mirror GitHub issues, PRs, comments, reviews and CI checks as brain pages. One key + one registration command to a searchable mirror; webhook-driven instant refresh, poll-sweep fallback, daily reconcile, App-credential option.- [docs/mcp/DEPLOY.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/mcp/DEPLOY.md): MCP server deployment.- [docs/protocol/MEMORY_VERBS_v1.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/protocol/MEMORY_VERBS_v1.md): The frozen five-verb memory protocol (recall/remember/entity/synthesize/forget): response envelopes, error contract, additive-forever versioning, surface modes, conformance certification, per-harness installs.diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex 37f2340109..c315a34bb1 100644--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@ -1,7 +1,7 @@{"id": "gbrain-context-engine","name": "gbrain",- "version": "0.60.12.0",+ "version": "0.60.13.0","description": "Personal knowledge brain with Postgres + pgvector hybrid search","family": "bundle-plugin","kind": "context-engine",diff --git a/package.json b/package.jsonindex cacfc0fdb0..bb3a8d9969 100644--- a/package.json+++ b/package.json@@ -30,6 +30,7 @@"./backoff": "./src/core/backoff.ts","./search/hybrid": "./src/core/search/hybrid.ts","./search/expansion": "./src/core/search/expansion.ts",+ "./search/evidence-delivery": "./src/core/search/evidence-delivery.ts","./eval/longmemeval/reader": "./src/eval/longmemeval/reader.ts","./think": "./src/core/think/index.ts","./ai/gateway": "./src/core/ai/gateway.ts",@@ -203,7 +204,7 @@"bun": ">=1.3.11"},"license": "MIT",- "version": "0.60.12.0",+ "version": "0.60.13.0","overrides": {"@ai-sdk/provider-utils": "4.0.33","@hono/node-server": "^2.0.5",diff --git a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json b/plugin-variants/gbrain-coding/.claude-plugin/plugin.jsonindex 8ab51b18dc..6d3d619df4 100644--- a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-coding",- "version": "0.60.12.0",+ "version": "0.60.13.0","description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json b/plugin-variants/gbrain-coding/.codex-plugin/plugin.jsonindex 8fd9a31059..281c4cebd2 100644--- a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-coding",- "version": "0.60.12.0",+ "version": "0.60.13.0","description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-coding/README.md b/plugin-variants/gbrain-coding/README.mdindex cb06c9b3e4..ca46d5aeb5 100644--- a/plugin-variants/gbrain-coding/README.md+++ b/plugin-variants/gbrain-coding/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.60.12.0 -->+<!-- gbrain-plugin-tree-stamp: 0.60.13.0 --># gbrain-coding (generated persona variant — do not hand-edit)Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant.diff --git a/plugin-variants/gbrain-coding/skills/query/SKILL.md b/plugin-variants/gbrain-coding/skills/query/SKILL.mdindex 5815c66bc8..a9ff76f6db 100644--- a/plugin-variants/gbrain-coding/skills/query/SKILL.md+++ b/plugin-variants/gbrain-coding/skills/query/SKILL.md@@ -139,6 +139,13 @@ claiming activation; otherwise report adoption as unverified.- `gbrain search` / `gbrain query` return ranked chunks with context snippets.These are often enough to answer the question directly.+- For multi-conversation or "when did X change" questions, where the answer+ depends on the surrounding conversation rather than one chunk, ask for whole+ evidence in the same call: `return_unit: "page"` (whole page or session,+ budgeted by `token_budget`, default 6,000) or `"window"` (neighbor chunks).+ Each result then carries the evidence in `chunk_text` plus a `delivered`+ block; see [evidence delivery](../../docs/evidence-delivery.md).+ `gbrain query "when did the launch move?" --return-unit page --token-budget 6000`- Only use `gbrain get <slug>` to load the full page when a chunk confirms thepage is relevant and you need more context (e.g., compiled truth, timeline).- **"Tell me about X"** -- get the full page (the user wants the complete picture).diff --git a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json b/plugin-variants/gbrain-daily/.claude-plugin/plugin.jsonindex 9100723932..8872cd480f 100644--- a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-daily",- "version": "0.60.12.0",+ "version": "0.60.13.0","description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json b/plugin-variants/gbrain-daily/.codex-plugin/plugin.jsonindex bc16900766..be656425fe 100644--- a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-daily",- "version": "0.60.12.0",+ "version": "0.60.13.0","description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-daily/README.md b/plugin-variants/gbrain-daily/README.mdindex 5ab5412ab6..7ccaa01d3a 100644--- a/plugin-variants/gbrain-daily/README.md+++ b/plugin-variants/gbrain-daily/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.60.12.0 -->+<!-- gbrain-plugin-tree-stamp: 0.60.13.0 --># gbrain-daily (generated persona variant — do not hand-edit)Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant.diff --git a/plugin-variants/gbrain-daily/skills/query/SKILL.md b/plugin-variants/gbrain-daily/skills/query/SKILL.mdindex 5815c66bc8..a9ff76f6db 100644--- a/plugin-variants/gbrain-daily/skills/query/SKILL.md+++ b/plugin-variants/gbrain-daily/skills/query/SKILL.md@@ -139,6 +139,13 @@ claiming activation; otherwise report adoption as unverified.- `gbrain search` / `gbrain query` return ranked chunks with context snippets.These are often enough to answer the question directly.+- For multi-conversation or "when did X change" questions, where the answer+ depends on the surrounding conversation rather than one chunk, ask for whole+ evidence in the same call: `return_unit: "page"` (whole page or session,+ budgeted by `token_budget`, default 6,000) or `"window"` (neighbor chunks).+ Each result then carries the evidence in `chunk_text` plus a `delivered`+ block; see [evidence delivery](../../docs/evidence-delivery.md).+ `gbrain query "when did the launch move?" --return-unit page --token-budget 6000`- Only use `gbrain get <slug>` to load the full page when a chunk confirms thepage is relevant and you need more context (e.g., compiled truth, timeline).- **"Tell me about X"** -- get the full page (the user wants the complete picture).diff --git a/plugin/README.md b/plugin/README.mdindex 4417fd79eb..b8bf668331 100644--- a/plugin/README.md+++ b/plugin/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.60.12.0 -->+<!-- gbrain-plugin-tree-stamp: 0.60.13.0 --># gbrain plugin skill tree (generated — do not hand-edit)This tree is the curated skill set for the gbrain Codex and Claude Codediff --git a/plugin/skills/query/SKILL.md b/plugin/skills/query/SKILL.mdindex 5815c66bc8..a9ff76f6db 100644--- a/plugin/skills/query/SKILL.md+++ b/plugin/skills/query/SKILL.md@@ -139,6 +139,13 @@ claiming activation; otherwise report adoption as unverified.- `gbrain search` / `gbrain query` return ranked chunks with context snippets.These are often enough to answer the question directly.+- For multi-conversation or "when did X change" questions, where the answer+ depends on the surrounding conversation rather than one chunk, ask for whole+ evidence in the same call: `return_unit: "page"` (whole page or session,+ budgeted by `token_budget`, default 6,000) or `"window"` (neighbor chunks).+ Each result then carries the evidence in `chunk_text` plus a `delivered`+ block; see [evidence delivery](../../docs/evidence-delivery.md).+ `gbrain query "when did the launch move?" --return-unit page --token-budget 6000`- Only use `gbrain get <slug>` to load the full page when a chunk confirms thepage is relevant and you need more context (e.g., compiled truth, timeline).- **"Tell me about X"** -- get the full page (the user wants the complete picture).diff --git a/scripts/bench-evidence-delivery.ts b/scripts/bench-evidence-delivery.tsnew file mode 100644index 0000000000..1f607705c0--- /dev/null+++ b/scripts/bench-evidence-delivery.ts@@ -0,0 +1,206 @@+#!/usr/bin/env bun+/**+ * Evidence delivery latency benchmark (plan amendment 10).+ *+ * bun scripts/bench-evidence-delivery.ts [--pages 10000] [--iterations 200] [--postgres <url>] [--json]+ *+ * Builds a synthetic brain (in-memory PGLite, or a fresh database on the+ * given test Postgres server) with a realistic page-size mix: 60% curated+ * notes (3-12 chunks, headed sections), 30% conversation sessions (6-24+ * chunks), 5% large pages (120 chunks) and 5% CJK pages. Chunks are written+ * sealed and projection-current, exactly as the importer leaves them; each+ * page's body is stored too (evidence text is cut from the sanitized body).+ *+ * Measures the ADDED latency of the evidence stage (deliverEvidence: one+ * batched getChunkWindows call + body sanitizing, chunk location, cutting,+ * token counting and packing) for every unit, on ranked hit lists of 5 hits over distinct+ * random pages, with a 6,000-token budget:+ * - cold: the first call per unit after connect;+ * - warm p50 / p95 over --iterations calls;+ * - large-page and CJK-only hit lists;+ * - 8 concurrent requests (per-request p95);+ * and reports rows/bytes read per request (bounded work, no N+1: the stage+ * issues exactly one engine call per request, counted here).+ */+import type { BrainEngine } from '../src/core/engine.ts';+import type { SearchResult } from '../src/core/types.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { deliverEvidence, type EvidencePlan } from '../src/core/search/evidence-delivery.ts';++function arg(name: string): string | undefined {+ const at = process.argv.indexOf(name);+ return at >= 0 ? process.argv[at + 1] : undefined;+}+const PAGES = Number(arg('--pages') ?? 10000);+const ITER = Number(arg('--iterations') ?? 200);+const databaseUrl = arg('--postgres');+const json = process.argv.includes('--json');+const UNITS = ['window', 'section', 'page', 'auto'] as const;+const BUDGET = 6000;++let seed = 20260930;+function rand(): number {+ seed = (seed * 1664525 + 1013904223) >>> 0;+ return seed / 4294967296;+}+const pick = <T>(xs: readonly T[]) => xs[Math.floor(rand() * xs.length)];+const WORDS = ['alpha', 'river', 'launch', 'march', 'budget', 'widget', 'acme', 'notes', 'said', 'moved', 'plan', 'review', 'quarter', 'team', 'draft', 'owner'];+const sentence = () => Array.from({ length: 8 + Math.floor(rand() * 10) }, () => pick(WORDS)).join(' ') + '.';+const para = (n: number) => Array.from({ length: n }, sentence).join(' ');+const CJK = '天地玄黄宇宙洪荒日月盈昃辰宿列张寒来暑往秋收冬藏';++/** One chunk (~1,600 chars) per kind; the 50-word overlap is reproduced like the chunker. */+function chunkTexts(kind: 'note' | 'chat' | 'large' | 'cjk', count: number): string[] {+ const bodies: string[] = [];+ for (let i = 0; i < count; i++) {+ if (kind === 'chat') bodies.push(Array.from({ length: 4 }, (_, t) => `**${t % 2 ? 'assistant' : 'user'}:** ${para(3)}`).join('\n\n'));+ else if (kind === 'cjk') bodies.push(Array.from({ length: 600 }, () => pick(CJK.split(''))).join('').replace(/(.{60})/g, '$1。'));+ else bodies.push(`${i % 3 === 0 ? `## Section ${i}\n\n` : ''}${para(6)}\n\n${para(6)}`);+ }+ return bodies;+}++/** The chunks the chunker would store for these bodies: each carries the previous body's last 50 words. */+function overlapped(bodies: string[], kind: string): string[] {+ return bodies.map((b, i) => (i === 0 || kind === 'cjk' ? b : `${bodies[i - 1].split(' ').slice(-50).join(' ')}\n\n${b}`));+}++async function build(engine: BrainEngine): Promise<Array<{ id: number; kind: string; chunks: number }>> {+ const pages: Array<{ id: number; kind: string; chunks: number }> = [];+ const BATCH = 500;+ for (let start = 0; start < PAGES; start += BATCH) {+ const slugs: string[] = []; const kinds: string[] = [];+ for (let i = start; i < Math.min(PAGES, start + BATCH); i++) {+ const r = rand();+ kinds.push(r < 0.6 ? 'note' : r < 0.9 ? 'chat' : r < 0.95 ? 'large' : 'cjk');+ slugs.push(`bench/p${i}`);+ }+ const bodies = kinds.map(kind => chunkTexts(kind as 'note', kind === 'note' ? 3 + Math.floor(rand() * 10) : kind === 'chat' ? 6 + Math.floor(rand() * 19) : kind === 'large' ? 120 : 8));+ const rows = await engine.executeRaw<{ id: number; slug: string }>(+ `INSERT INTO pages (slug, type, title, compiled_truth, timeline, source_id)+ SELECT s, 'note', s, b, '', 'default' FROM unnest($1::text[], $2::text[]) AS t(s, b) RETURNING id, slug`,+ [slugs, bodies.map(b => b.join('\n\n'))]);+ const pageIds: number[] = []; const idx: number[] = []; const texts: string[] = [];+ for (const row of rows) {+ const k = slugs.indexOf(row.slug);+ overlapped(bodies[k], kinds[k]).forEach((t, i) => { pageIds.push(row.id); idx.push(i); texts.push(t); });+ pages.push({ id: row.id, kind: kinds[k], chunks: bodies[k].length });+ }+ await engine.executeRaw(+ `INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source)+ SELECT * FROM unnest($1::int[], $2::int[], $3::text[], $4::text[])`,+ [pageIds, idx, texts, texts.map(() => 'compiled_truth')]);+ }+ await engine.executeRaw(`UPDATE pages SET chunker_version = 4, text_projection_revision = knowledge_revision WHERE slug LIKE 'bench/%'`);+ await engine.executeRaw('ANALYZE');+ return pages;+}++async function hitsFor(engine: BrainEngine, pages: Array<{ id: number; chunks: number }>): Promise<SearchResult[]> {+ const chosen = new Map<number, number>();+ while (chosen.size < Math.min(5, pages.length)) {+ const p = pick(pages);+ chosen.set(p.id, Math.floor(rand() * p.chunks));+ }+ const rows = await engine.executeRaw<Record<string, unknown>>(+ `SELECT cc.id, cc.page_id, cc.chunk_index, cc.chunk_text, p.slug, p.title FROM content_chunks cc JOIN pages p ON p.id = cc.page_id+ WHERE (cc.page_id, cc.chunk_index) IN (SELECT * FROM unnest($1::int[], $2::int[]))`,+ [[...chosen.keys()], [...chosen.values()]]);+ return rows.map(r => ({+ slug: String(r.slug), page_id: Number(r.page_id), title: String(r.title), type: 'note', chunk_text: String(r.chunk_text),+ chunk_source: 'compiled_truth', chunk_id: Number(r.id), chunk_index: Number(r.chunk_index), score: 1, stale: false, source_id: 'default',+ }) as SearchResult);+}++const pct = (xs: number[], q: number) => {+ const s = [...xs].sort((a, b) => a - b);+ return s[Math.min(s.length - 1, Math.floor(q * s.length))];+};+const r1 = (n: number) => Math.round(n * 10) / 10;++async function main() {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ if (databaseUrl) {+ const { isolatedPersistencePostgres } = await import('../test/helpers/persistence-postgres.ts');+ ({ engine, close } = await isolatedPersistencePostgres(databaseUrl));+ } else {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ close = () => engine.disconnect();+ }+ const t0 = performance.now();+ const pages = await build(engine);+ const buildMs = performance.now() - t0;+ let calls = 0; let rowsRead = 0; let bytesRead = 0;+ const counted = new Proxy(engine, {+ get(target, prop, recv) {+ if (prop !== 'getChunkWindows') return Reflect.get(target, prop, recv);+ return async (...args: Parameters<BrainEngine['getChunkWindows']>) => {+ calls++;+ const out = await target.getChunkWindows(...args);+ for (const p of out) { rowsRead += p.chunks.length; bytesRead += p.compiled_truth.length + p.timeline.length; for (const c of p.chunks) bytesRead += c.chunk_text.length; }+ return out;+ };+ },+ }) as BrainEngine;+ const plan = (unit: EvidencePlan['unit']): EvidencePlan => ({ requestedUnit: unit, unit, window: 1, budgetTokens: BUDGET, explicitUnit: true });+ const scope = { excludePrivate: true, requireSafeChunks: true };+ const results: Record<string, unknown>[] = [];+ const large = pages.filter(p => p.kind === 'large');+ const cjk = pages.filter(p => p.kind === 'cjk');+ for (const unit of UNITS) {+ const coldHits = await hitsFor(engine, pages);+ let s = performance.now();+ await deliverEvidence(counted, coldHits, plan(unit), scope);+ const cold = performance.now() - s;+ const warm: number[] = [];+ calls = 0; rowsRead = 0; bytesRead = 0;+ for (let i = 0; i < ITER; i++) {+ const hits = await hitsFor(engine, pages);+ s = performance.now();+ await deliverEvidence(counted, hits, plan(unit), scope);+ warm.push(performance.now() - s);+ }+ const callsPerRequest = calls / ITER;+ const rowsPerRequest = rowsRead / ITER;+ const bytesPerRequest = bytesRead / ITER;+ const special = async (subset: typeof pages) => {+ const xs: number[] = [];+ for (let i = 0; i < Math.min(60, ITER); i++) {+ const hits = await hitsFor(engine, subset);+ s = performance.now();+ await deliverEvidence(engine, hits, plan(unit), scope);+ xs.push(performance.now() - s);+ }+ return { p50: r1(pct(xs, 0.5)), p95: r1(pct(xs, 0.95)) };+ };+ const conc: number[] = [];+ for (let round = 0; round < Math.max(5, ITER / 20); round++) {+ const batch = await Promise.all(Array.from({ length: 8 }, () => hitsFor(engine, pages)));+ await Promise.all(batch.map(async hits => {+ const t = performance.now();+ await deliverEvidence(engine, hits, plan(unit), scope);+ conc.push(performance.now() - t);+ }));+ }+ results.push({+ unit, cold_ms: r1(cold), warm_p50_ms: r1(pct(warm, 0.5)), warm_p95_ms: r1(pct(warm, 0.95)),+ large_page: await special(large), cjk: await special(cjk),+ concurrent8_p95_ms: r1(pct(conc, 0.95)),+ engine_calls_per_request: callsPerRequest, rows_per_request: r1(rowsPerRequest), kb_per_request: r1(bytesPerRequest / 1024),+ });+ }+ await close();+ const summary = { engine: databaseUrl ? 'postgres' : 'pglite', pages: PAGES, iterations: ITER, budget_tokens: BUDGET, build_s: r1(buildMs / 1000), results };+ if (json) { console.log(JSON.stringify(summary, null, 2)); return; }+ console.log(`evidence delivery bench — ${summary.engine}, ${PAGES} pages, ${ITER} warm iterations, budget ${BUDGET}`);+ console.log('| unit | cold ms | warm p50 | warm p95 | large p95 | CJK p95 | 8-conc p95 | calls/req | rows/req | KB/req |');+ console.log('|---|---|---|---|---|---|---|---|---|---|');+ for (const r of results as Array<Record<string, any>>) {+ console.log(`| ${r.unit} | ${r.cold_ms} | ${r.warm_p50_ms} | ${r.warm_p95_ms} | ${r.large_page.p95} | ${r.cjk.p95} | ${r.concurrent8_p95_ms} | ${r.engine_calls_per_request} | ${r.rows_per_request} | ${r.kb_per_request} |`);+ }+}++await main();diff --git a/scripts/check-exports-count.sh b/scripts/check-exports-count.shindex 1e5620cd4c..6021397e81 100755--- a/scripts/check-exports-count.sh+++ b/scripts/check-exports-count.sh@@ -19,7 +19,7 @@set -euo pipefail-EXPECTED_COUNT=27+EXPECTED_COUNT=28# Count top-level keys in the exports object. `node -e` parses JSON# reliably without needing jq (which isn't in every CI environment).diff --git a/scripts/e2e-backend-matrix.txt b/scripts/e2e-backend-matrix.txtindex 72baff1ffb..dac9ef0611 100644--- a/scripts/e2e-backend-matrix.txt+++ b/scripts/e2e-backend-matrix.txt@@ -43,3 +43,4 @@ test/e2e/persistence-sync-options-parity.test.tstest/e2e/persistence-sync-origin-parity.test.tstest/e2e/projection-recovery-parity.test.tstest/e2e/takes-scorecard-parity.test.ts+test/e2e/evidence-delivery-parity.test.tsdiff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.tsindex c159d158fe..cc810a9d22 100644--- a/scripts/e2e-test-map.ts+++ b/scripts/e2e-test-map.ts@@ -94,6 +94,10 @@ export const E2E_TEST_MAP: Record<string, string[]> = {],"src/core/page-state/**": ["test/e2e/projection-recovery-parity.test.ts", "test/e2e/projection-readiness-currency.test.ts", "test/e2e/projection-embedding-input-hash.test.ts", "test/e2e/safe-chunk-reseal.test.ts", ...MIGRATION_WAVE_TESTS],"src/core/embedding-input-hash.ts": ["test/e2e/projection-embedding-input-hash.test.ts"],+ // Evidence delivery (return_unit): the release-gate leak canaries and the+ // engine / product-path parity suite.+ "src/core/search/evidence-delivery.ts": ["test/e2e/evidence-delivery-leak.test.ts", "test/e2e/evidence-delivery-parity.test.ts"],+ "src/core/search/chunk-windows.ts": ["test/e2e/evidence-delivery-leak.test.ts", "test/e2e/evidence-delivery-parity.test.ts"],"src/core/search/safe-chunks.ts": ["test/e2e/safe-chunk-reseal.test.ts", "test/e2e/legacy-chunk-privacy.test.ts"],"src/core/code-chunks.ts": ["test/e2e/projection-recovery-parity.test.ts"],"src/core/markdown-chunks.ts": ["test/e2e/projection-recovery-parity.test.ts"],@@ -545,3 +549,4 @@ E2E_TEST_MAP["src/core/engine-sql/executor.ts"] = ENGINE_SQL_EXECUTOR_E2E;E2E_TEST_MAP["src/core/engine-sql/dialect-*.ts"] = ENGINE_SQL_EXECUTOR_E2E;E2E_TEST_MAP["src/core/engine-sql/normalize.ts"] = ["test/e2e/engine-sql-normalize-parity.test.ts"];E2E_TEST_MAP["src/core/engine-sql/brands.ts"] = ["test/e2e/engine-sql-rls-scope.test.ts"];+E2E_TEST_MAP["src/core/engine-sql/chunks.ts"] = ["test/e2e/evidence-delivery-leak.test.ts", "test/e2e/evidence-delivery-parity.test.ts"];diff --git a/scripts/llms-config.ts b/scripts/llms-config.tsindex 7e4e3277ba..fa8751aaee 100644--- a/scripts/llms-config.ts+++ b/scripts/llms-config.ts@@ -168,6 +168,13 @@ export const SECTIONS: DocSection[] = ["Push-based context: the brain volunteers confidence-gated pages from the rolling conversation window. Three channels (ambient reflex, volunteer_context op, gbrain watch), config knobs, and the volunteered-vs-used feedback loop.",path: "docs/guides/push-context.md",},+ {+ title: "docs/evidence-delivery.md",+ description:+ "Evidence delivery (`return_unit`): window / section / page / auto evidence instead of chunks on search, query, recall and think, packed into a token budget; response fields, fallback codes, authorization guarantees, latency, and the frozen-hit `assemble_evidence` interface for evals.",+ path: "docs/evidence-delivery.md",+ includeInFull: false,+ },{title: "docs/guides/github-source.md",description:diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 9aacd45f57..c1d71a324c 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -3,7 +3,7 @@# Raising a ceiling is a conscious, reviewer-visible act. Lower ceilings in# the same commit as any peel (the guard fails on >50 lines of stale slack).# Columns: path max_lines policy note-src/cli.ts 3143 ratchet refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts+src/cli.ts 3146 ratchet refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts)src/commands/autopilot.ts 1633 ratchet refactor wave 1 split target (W4 autopilot, cut line); ceiling rationale: docs/architecture/key-files/commands-1.md entry for src/commands/autopilot.tssrc/commands/doctor.ts 653 ratchet refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.tssrc/commands/embed.ts 2182 ratchet lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring; archived eligibility: active-only dispatch with honest stranded-work reporting; explicit archived admission: live-source snapshots and honest refused-installation failures; +2 fw3: embed --stale --images dispatch (sweep lives in core/embed-stale-images.ts); +5 #5289: dry run reports restamp-only chunks apart from chunks to embed (count lives in core/embedding-invalidation.ts); +6 #4616: keep a partially refused batch in embedPageTexts and name the recovery command in failure samples (guard lives in core/ai/embedding-guard.ts)@@ -16,14 +16,14 @@ src/commands/sync.ts 468 ratchet refactor wave 1 split target (W4 sync); ceilingsrc/core/cycle.ts 3217 ratchet grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the mergesrc/core/cycle/synthesize.ts 3317 ratchet merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the mergesrc/core/cycle/extract-atoms.ts 1798 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts)-src/core/engine.ts 2667 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract+src/core/engine.ts 2670 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3)src/core/import-file.ts 2230 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode)src/core/migrate.ts 599 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3)src/core/operations.ts 329 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base-src/core/pglite-engine.ts 3371 ratchet refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts-src/core/postgres-engine.ts 3388 ratchet refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts+src/core/pglite-engine.ts 3374 ratchet refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts)+src/core/postgres-engine.ts 3393 ratchet refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts)src/core/search/hybrid.ts 1572 ratchet refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts-src/core/types.ts 2086 ratchet +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge+src/core/types.ts 2088 ratchet +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts)src/core/minions/queue.ts 2522 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keyssrc/commands/init.ts 1932 ratchet grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-initsrc/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)@@ -36,7 +36,7 @@ src/core/embedding-migration.ts 1515 ratchet new row: crossed 1500 in v0.46.25.0src/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 refreshsrc/commands/hook.ts 1892 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-transcriptssrc/core/chunkers/code.ts 1582 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES-src/core/config.ts 1795 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge+src/core/config.ts 1802 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7)src/core/bootstrap/harness.ts 2656 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 basesrc/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 optionsrc/core/ops/pages.ts 613 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 parameterdiff --git a/skills/query/SKILL.md b/skills/query/SKILL.mdindex 5815c66bc8..a9ff76f6db 100644--- a/skills/query/SKILL.md+++ b/skills/query/SKILL.md@@ -139,6 +139,13 @@ claiming activation; otherwise report adoption as unverified.- `gbrain search` / `gbrain query` return ranked chunks with context snippets.These are often enough to answer the question directly.+- For multi-conversation or "when did X change" questions, where the answer+ depends on the surrounding conversation rather than one chunk, ask for whole+ evidence in the same call: `return_unit: "page"` (whole page or session,+ budgeted by `token_budget`, default 6,000) or `"window"` (neighbor chunks).+ Each result then carries the evidence in `chunk_text` plus a `delivered`+ block; see [evidence delivery](../../docs/evidence-delivery.md).+ `gbrain query "when did the launch move?" --return-unit page --token-budget 6000`- Only use `gbrain get <slug>` to load the full page when a chunk confirms thepage is relevant and you need more context (e.g., compiled truth, timeline).- **"Tell me about X"** -- get the full page (the user wants the complete picture).diff --git a/skills/skills.lock.json b/skills/skills.lock.jsonindex c1180a2763..4b864492dd 100644--- a/skills/skills.lock.json+++ b/skills/skills.lock.json@@ -168,7 +168,7 @@"postgres-adopt/SKILL.md": "4c402527bd0d98aa4e7f1a341a25ac0d1bba5e98b3dd55bcc5e30ed2858fa0e0","postgres-adopt/routing-eval.jsonl": "db91c1fae408a45082979c402c11eff413277ace6cf746297cc86009dcaefe06","publish/SKILL.md": "e06b609db780a3cc93a1755a87b30ff08ffdc0fdbc834c1422b2ad2489b57497",- "query/SKILL.md": "7a5857b4898f2e20cfa2d69c4d24e071978ab38a7471a12d9652da4093f202c1",+ "query/SKILL.md": "7c2eea23d789eeac82afe37ab85557cd92f7be3a409e8cceadc8ce03f448f73d","query/routing-eval.jsonl": "74f5a91e52fabc54e0e9403fa17db87ee26bb7ebb8ae8005148c51142abc62fe","remote-mcp/SKILL.md": "3021054e2b21fa589310181d5140bc6caae5a4d75e3f3aa2cdbddac272cd4873","remote-mcp/routing-eval.jsonl": "7287693135c9fe2d6495d81d22746ddf41b116254db4b6e683dbdee251e08f8e",diff --git a/src/cli.ts b/src/cli.tsindex 98ecfb7a69..36fb9beee7 100755--- a/src/cli.ts+++ b/src/cli.ts@@ -1,6 +1,7 @@#!/usr/bin/env bunimport { affectsRecall } from './core/types.ts';+import { deliveryVersionSkewWarning } from './core/search/evidence-delivery.ts';import { installSigchldHandler } from './core/zombie-reap.ts';installSigchldHandler();import { installSignalHandlers as installCleanupSignalHandlers } from './core/process-cleanup.ts';@@ -765,6 +766,8 @@ async function runThinClientRouted(const envelopeMeta = extractResponseMeta(raw);if (envelopeMeta?.retrieval) captureRetrievalMeta('retrieval', envelopeMeta.retrieval);const result = unpackToolResult(raw);+ const skew = deliveryVersionSkewWarning(op.name, params, envelopeMeta?.retrieval as Record<string, unknown> | undefined, result);+ if (skew) process.stderr.write(skew + '\n');const output = formatResult(op.name, result, params);// Awaited delivery (#3423) — same contract as the local-engine path.if (output) await writeStdoutFinal(output);diff --git a/src/core/chronicle/ontology.ts b/src/core/chronicle/ontology.tsindex c6cffd2cab..2d9e271f37 100644--- a/src/core/chronicle/ontology.ts+++ b/src/core/chronicle/ontology.ts@@ -42,3 +42,15 @@ export function normalizeDimension(name: string): string {export function isNovelDimension(normalized: string): boolean {return !KNOWN_DIMENSIONS.has(normalized);}++/**+ * A same-value observation dated BEFORE the current open value's start is an+ * earlier stint (possibly separated from the current one by another value),+ * not a corroboration of the current one: mergeOntologyFact stores it as a+ * live row so as-of reads see it, exactly like a backdated observation of a+ * different value. Undated observations are never backdated.+ */+export function isBackdatedObservation(validFrom: string | null, currentValidFrom: string | Date | null | undefined): boolean {+ return validFrom != null && currentValidFrom != null+ && new Date(validFrom).getTime() < new Date(currentValidFrom).getTime();+}diff --git a/src/core/chunkers/token-estimate.ts b/src/core/chunkers/token-estimate.tsindex 7c1642b719..3d52af9e25 100644--- a/src/core/chunkers/token-estimate.ts+++ b/src/core/chunkers/token-estimate.ts@@ -32,18 +32,27 @@ let tiktokenInitialized = false;// surprise OpenAI bill. Same cl100k_base tokenizer the embedding path// actually uses, so cost estimates match actual billing within tokenizer// noise.+function loadEncoder(): void {+ if (tiktokenInitialized) return;+ try {+ // eslint-disable-next-line @typescript-eslint/no-var-requires+ const m = require('@dqbd/tiktoken');+ tiktokenEncoder = m.get_encoding('cl100k_base');+ } catch {+ tiktokenEncoder = null;+ }+ tiktokenInitialized = true;+}++/** Whether estimateTokens counts with cl100k (false = the len/4 fallback). */+export function cl100kAvailable(): boolean {+ loadEncoder();+ return tiktokenEncoder !== null;+}+export function estimateTokens(text: string): number {if (!text) return 0;- if (!tiktokenInitialized) {- try {- // eslint-disable-next-line @typescript-eslint/no-var-requires- const m = require('@dqbd/tiktoken');- tiktokenEncoder = m.get_encoding('cl100k_base');- } catch {- tiktokenEncoder = null;- }- tiktokenInitialized = true;- }+ loadEncoder();if (tiktokenEncoder) {try {return tiktokenEncoder.encode(text).length;diff --git a/src/core/config.ts b/src/core/config.tsindex e1cab36bd8..c10025afcc 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1341,6 +1341,13 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = ['search.metadata_boost_gate','search.crag_escalation','search.crag_think',+ // Evidence delivery (search/evidence-delivery.ts): default unit (chunk),+ // window radius, default/remote-max token budgets; think reads its own unit.+ 'search.return_unit',+ 'search.return_window',+ 'search.return_budget_default',+ 'search.return_budget_max_remote',+ 'think.return_unit',// Models tier system (v0.31.12)'models.default','models.tier.utility',diff --git a/src/core/engine-sql/chunks.ts b/src/core/engine-sql/chunks.tsindex 9bf44f42cd..5cdad5f1aa 100644--- a/src/core/engine-sql/chunks.ts+++ b/src/core/engine-sql/chunks.ts@@ -36,6 +36,8 @@ import { privatePagesFilterFragment } from '../search/private-visibility.ts';import { splitEmbeddingSignature, lockEmbeddingSources } from '../embedding-invalidation.ts';import { EMBED_SKIP_FILTER_FRAGMENT } from '../embed-skip.ts';import { QUARANTINE_FILTER_FRAGMENT } from '../quarantine.ts';+import { SAFE_FENCE_CHUNKER_VERSION } from '../search/safe-chunks.ts';+import { mapChunkWindowRows, type ChunkWindowOpts, type ChunkWindowPage, type ChunkWindowRequest } from '../search/chunk-windows.ts';import type { SqlExecutor } from './executor.ts';import type { LegacyUnscopedRead, ScopedRead } from './brands.ts';import { joinFragments, renderFragment, sqlFragment, trustedSql, type SqlFragment } from './fragment.ts';@@ -671,6 +673,62 @@ export async function getEmbeddingsByChunkIds(exec: LegacyUnscopedRead, ids: numreturn result;}+/**+ * Evidence delivery: ONE batched read of chunk_index windows, keyed by+ * page_id. Every requested page is re-authorized with the search legs'+ * visibility predicate (source scope, deleted, current text projection,+ * archived source, quarantine, private pages, safe chunks); pages that fail+ * are absent. Page rows carry the raw body columns (the assembler sanitizes+ * them whole before slicing); chunk rows (sealed pages only) anchor the hits+ * in that text. Page rows and chunk+ * rows come back in one UNION so the row cap never hides a page's+ * authorization.+ */+export async function getChunkWindows(exec: ScopedRead, requests: ChunkWindowRequest[], opts: ChunkWindowOpts): Promise<ChunkWindowPage[]> {+ if (requests.length === 0) return [];+ const maxRows = Math.max(0, Math.floor(opts.maxRows));+ const scopeSql = opts.sourceIds && opts.sourceIds.length > 0+ ? sqlFragment`AND p.source_id = ANY(${opts.sourceIds}::text[])`+ : opts.sourceId ? sqlFragment`AND p.source_id = ${opts.sourceId}` : sqlFragment``;+ const privateSql = opts.excludePrivate ? trustedSql(`AND ${privatePagesFilterFragment('p')}`) : sqlFragment``;+ const safeSql = requiresSafeChunks(opts) ? trustedSql(`AND ${safeChunksFilter('p')}`) : sqlFragment``;+ const { rows } = await exec.run(sqlFragment`+ WITH req AS (+ SELECT * FROM unnest(${requests.map(r => r.page_id)}::int[], ${requests.map(r => r.from_index)}::int[],+ ${requests.map(r => r.to_index)}::int[], ${requests.map(r => r.priority)}::int[]) AS r(page_id, lo, hi, prio)+ ), auth AS (+ SELECT p.id, p.slug, p.source_id, p.type, p.knowledge_revision::text AS revision, p.compiled_truth, p.timeline,+ (COALESCE(p.chunker_version, 0) >= ${SAFE_FENCE_CHUNKER_VERSION}) AS sealed,+ (SELECT MIN(req.prio) FROM req WHERE req.page_id = p.id) AS prio+ FROM pages p+ JOIN sources s ON s.id = p.source_id+ WHERE p.id = ANY(${[...new Set(requests.map(r => r.page_id))]}::int[]) ${scopeSql}+ AND p.deleted_at IS NULL AND ${trustedSql(currentTextProjectionFilter('p'))} AND NOT s.archived+ AND ${trustedSql(QUARANTINE_FILTER_FRAGMENT)} ${privateSql} ${safeSql}+ ), chunk_rows AS (+ SELECT cc.page_id, cc.id AS chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, a.prio+ FROM auth a+ JOIN content_chunks cc ON cc.page_id = a.id+ WHERE a.sealed+ AND cc.chunk_source = ANY(${opts.chunkSources}::text[])+ AND COALESCE(cc.modality, 'text') = 'text'+ AND EXISTS (SELECT 1 FROM req r WHERE r.page_id = cc.page_id AND cc.chunk_index BETWEEN r.lo AND r.hi)+ ORDER BY a.prio, cc.page_id, cc.chunk_index+ LIMIT ${maxRows + 1}+ )+ SELECT 'page' AS kind, a.id AS page_id, a.slug, a.source_id, a.type, a.revision, a.sealed, a.prio,+ (SELECT MAX(c2.chunk_index) FROM content_chunks c2 WHERE c2.page_id = a.id) AS max_chunk_index,+ a.compiled_truth, a.timeline,+ NULL::int AS chunk_id, NULL::int AS chunk_index, NULL::text AS chunk_text, NULL::text AS chunk_source+ FROM auth a+ UNION ALL+ SELECT 'chunk' AS kind, c.page_id, NULL, NULL, NULL, NULL, NULL, c.prio,+ NULL, NULL, NULL, c.chunk_id, c.chunk_index, c.chunk_text, c.chunk_source+ FROM chunk_rows c+ `);+ return mapChunkWindowRows(rows, maxRows);+}+export async function getChunksWithEmbeddings(exec: LegacyUnscopedRead, slug: string, opts?: { sourceId?: string; includeUnsealed?: boolean }): Promise<Chunk[]> {const sourceId = opts?.sourceId;const projection = trustedSql(opts?.includeUnsealed ? 'TRUE' : currentTextProjectionFilter('p'));diff --git a/src/core/engine-sql/timeline.ts b/src/core/engine-sql/timeline.tsindex 8b13adfaed..e68c9bc2c9 100644--- a/src/core/engine-sql/timeline.ts+++ b/src/core/engine-sql/timeline.ts@@ -203,12 +203,19 @@ export async function getOnThisDay(exec: LegacyUnscopedRead, opts?: PageReadScopexport async function getLastSeen(exec: LegacyUnscopedRead, entitySlug: string, opts?: PageReadScope & { asof?: string }): Promise<LastSeenResult> {// "Seen" = the entity's own page has a timeline row, OR an event's `who`- // array references the entity (exact slug or wikilink-substring match).+ // array references the entity: the exact slug, or a wikilink to exactly+ // that slug ([[slug]] / [[slug|label]]). Never a substring — a slug that+ // prefixes another slug must not inherit its sightings — and LIKE+ // metacharacters in the slug are escaped.// "Last seen" is a PAST relation: the chronicle legitimately stores// future events (calendar-event is eligibility-eligible), so bound to// <= asof/today or a scheduled event reads as "seen today". Mirrors// getOnThisDay's `te.date < target` bound.+ // The newest sighting is the newest projected day (te.date is already the+ // chronicle.tz local day); the event instant only orders within a day, so+ // a late-evening event never outranks a plain row dated the next day.const seenThrough = opts?.asof ? sqlFragment`${opts.asof}::date` : sqlFragment`current_date`;+ const likeSlug = entitySlug.replace(/[\\%_]/g, (c) => '\\' + c);const rows = (await exec.run(sqlFragment`SELECT te.date::text AS last_date, ep.slug AS last_event_slugFROM timeline_entries te@@ -223,11 +230,13 @@ export async function getLastSeen(exec: LegacyUnscopedRead, entitySlug: string,CASE WHEN jsonb_typeof(ep.frontmatter->'event'->'who') = 'array'THEN ep.frontmatter->'event'->'who' ELSE '[]'::jsonb END) AS w(name)- WHERE w.name = ${entitySlug} OR w.name LIKE ${'%' + entitySlug + '%'}+ WHERE w.name = ${entitySlug}+ OR w.name LIKE ${'%[[' + likeSlug + ']]%'} ESCAPE '\\'+ OR w.name LIKE ${'%[[' + likeSlug + '|%'} ESCAPE '\\')))${chronicleSourceCond(opts)}- ORDER BY COALESCE(ep.effective_date, te.date::timestamptz) DESC, te.id DESC+ ORDER BY te.date DESC, COALESCE(ep.effective_date, te.date::timestamptz) DESC, te.id DESCLIMIT 1`)).rows;const row = rows[0] as { last_date?: string; last_event_slug?: string } | undefined;return finalizeLastSeen(entitySlug, row?.last_date ?? null, row?.last_event_slug ?? null, opts?.asof);diff --git a/src/core/engine.ts b/src/core/engine.tsindex 2c40fc9975..d24cc9a718 100644--- a/src/core/engine.ts+++ b/src/core/engine.ts@@ -1,4 +1,5 @@import type { PageKey, PageSnapshot, PageSnapshotOptions, PageWriteOptions } from './page-state/types.ts';+import type { ChunkWindowRequest, ChunkWindowOpts, ChunkWindowPage } from './search/chunk-windows.ts';import type { DerivedLinkOrigin, DerivedLinkReplacementOptions } from './derived-links.ts';export type { PageKey, PageSnapshot, PageSnapshotOptions, PageWriteOptions, PageMutationPrecondition, PageWithdrawal } from './page-state/types.ts';import type {@@ -1158,6 +1159,8 @@ export interface BrainEngine {* `getChunksWithEmbeddings`, which honors neither scope precedence nor RLS.*/getChunks(slug: string, opts?: PageReadScope & { includeEmbedding?: boolean; includeUnsealed?: boolean }): Promise<Chunk[]>;+ /** Evidence delivery: one batched, re-authorized chunk-window read keyed by page_id (engine-sql/chunks.ts). */+ getChunkWindows(requests: ChunkWindowRequest[], opts: ChunkWindowOpts): Promise<ChunkWindowPage[]>;/*** Count chunks whose registry-ACTIVE embedding column IS NULL (S2).* Pre-flight short-circuit for `embed --stale` so a 100%-embedded braindiff --git a/src/core/entities/resolve.ts b/src/core/entities/resolve.tsindex ced660d3ff..3b85b230d8 100644--- a/src/core/entities/resolve.ts+++ b/src/core/entities/resolve.ts@@ -31,7 +31,9 @@ import { isUndefinedTableError } from '../utils.ts';** Resolution order:* 1. If `raw` is already a page slug shape (contains a "/" or matches an- * exact pages.slug row in this source), return it untouched.+ * exact pages.slug row in this source), return it untouched. A mention+ * that is exactly one live page's own name (slug basename) resolves to+ * it next, before any other page's alias.* 2. Resolve a bare name only when prefix expansion finds one candidate.* 3. For multi-token input, take a fuzzy candidate within the source only* when it carries the same name tokens (sameEntityName).@@ -58,6 +60,13 @@ export async function resolveEntitySlug(if (exact) return exact;}+ // 1.25. Exact own name: a live page whose slug basename IS the mention wins+ // over another page's alias — "Jordan Lee-Example" is+ // people/jordan-lee-example even when a different person lists it as+ // a former name.+ const basenames = await findExactBasenameCandidates(engine, source_id, trimmed);+ if (basenames.length === 1) return basenames[0].slug;+// 1.5. Alias-exact (v0.46.15 identity wave, #3730): an unambiguous// page_aliases hit resolves BEFORE prefix expansion / fuzzy — the// alias table is curated ground truth ("saoirse" → people/saoirse-x)@@ -65,8 +74,6 @@ export async function resolveEntitySlug(const aliased = await tryAliasExact(engine, source_id, trimmed);if (aliased) return aliased;- const basenames = await findExactBasenameCandidates(engine, source_id, trimmed);- if (basenames.length === 1) return basenames[0].slug;if (basenames.length > 1) return fallbackSlugify(trimmed);// 2. Prefix-expansion match: when the input looks like a bare first name@@ -262,11 +269,12 @@ export async function resolveEntitySlugWithSource(if (exact) return { slug: exact, source: 'exact_page' };}+ const basenames = await findExactBasenameCandidates(engine, source_id, trimmed);+ if (basenames.length === 1) return { slug: basenames[0].slug, source: 'fuzzy_match' };+const aliased = await tryAliasExact(engine, source_id, trimmed);if (aliased) return { slug: aliased, source: 'alias_exact' };- const basenames = await findExactBasenameCandidates(engine, source_id, trimmed);- if (basenames.length === 1) return { slug: basenames[0].slug, source: 'fuzzy_match' };if (basenames.length > 1) return { slug: fallbackSlugify(trimmed), source: 'fallback_slugify' };if (isBareName(trimmed)) {diff --git a/src/core/entity-identity.ts b/src/core/entity-identity.tsindex bfc81df3cb..2195ebe5f4 100644--- a/src/core/entity-identity.ts+++ b/src/core/entity-identity.ts@@ -250,6 +250,31 @@ export async function listEntityIdentities(}}+/**+ * The identity group of each given (source_id, slug) page that belongs to one,+ * keyed `${source_id}:${slug}`. Pages outside any group are absent.+ */+export async function identityIdsForPages(+ engine: BrainEngine,+ pages: Array<{ sourceId: string; slug: string }>,+): Promise<Map<string, string>> {+ if (pages.length === 0) return new Map();+ const wanted = new Set(pages.map(p => `${p.sourceId}:${p.slug}`));+ try {+ const rows = await engine.executeRaw<{ entity_id: string; source_id: string; slug: string }>(+ `SELECT ei.entity_id, ei.source_id, p.slug+ FROM entity_identities ei+ JOIN pages p ON p.id = ei.page_id AND p.source_id = ei.source_id AND p.deleted_at IS NULL+ WHERE ei.source_id = ANY($1::text[]) AND p.slug = ANY($2::text[])`,+ [[...new Set(pages.map(p => p.sourceId))], [...new Set(pages.map(p => p.slug))]],+ );+ return new Map(rows.map((r): [string, string] => [`${r.source_id}:${r.slug}`, r.entity_id]).filter(([k]) => wanted.has(k)));+ } catch (e) {+ if (isUndefinedTableError(e)) return new Map();+ throw e;+ }+}+/** Is the flag-gated retrieval union on? Fail-closed on any read error. */export async function isIdentityUnionEnabled(engine: BrainEngine): Promise<boolean> {try {diff --git a/src/core/operations-descriptions.ts b/src/core/operations-descriptions.tsindex 5424ed4531..2feebdebec 100644--- a/src/core/operations-descriptions.ts+++ b/src/core/operations-descriptions.ts@@ -74,7 +74,9 @@ export const QUERY_DESCRIPTION ="default count when `limit` is omitted depends on the configured search " +"mode (10 conservative / 25 balanced / 50 tokenmax — see the `limit` param " +"description); pass `limit` explicitly for a stable count regardless of " +- "mode. For exhaustive enumeration use list_pages; for exact known tokens " ++ "mode. When the answer needs the surrounding conversation or section, pass " ++ "`return_unit` ('page' / 'section' / 'window') to get that evidence in one call " ++ "instead of get_page per hit. For exhaustive enumeration use list_pages; for exact known tokens " +"`search` is cheaper (no expansion LLM call). " +"For personal/emotional questions ('what's going on with me', 'anything notable', " +"'how am I feeling'), prefer get_recent_salience, find_anomalies, or " +@@ -88,6 +90,7 @@ export const SEARCH_DESCRIPTION ="result set is NOT proof of coverage — for concept / synonym / landscape " +"questions use `query` (adds multi-query expansion); for exhaustive " +"enumeration use list_pages pagination. " ++ "Pass `return_unit` ('window' / 'section' / 'page') for whole evidence instead of chunks. " +"For personal/emotional questions, " +"prefer get_recent_salience or find_anomalies — they surface activity bursts " +"without needing a search term. " +diff --git a/src/core/operations.ts b/src/core/operations.tsindex eb6a59a86b..b9656fc93d 100644--- a/src/core/operations.ts+++ b/src/core/operations.ts@@ -244,7 +244,7 @@ const OP_AREAS: Record<string, string> = {put_raw_data: 'pages', get_raw_data: 'pages',fetch: 'pages', // #4039 deep-research read adapter (search/fetch pair)// search- search: 'search', query: 'search', search_by_image: 'search',+ search: 'search', query: 'search', search_by_image: 'search', assemble_evidence: 'search',// tagsadd_tag: 'tags', remove_tag: 'tags', get_tags: 'tags',// links + graphdiff --git a/src/core/ops/facts.ts b/src/core/ops/facts.tsindex 6b20bdcbd3..b7cae99549 100644--- a/src/core/ops/facts.ts+++ b/src/core/ops/facts.ts@@ -1,4 +1,5 @@import { WRITE_REQUEST_PARAM } from '../persistence/params.ts';+import { deliverEvidence, resolveEvidencePlan, type DeliveryMeta, type EvidencePlan } from '../search/evidence-delivery.ts';import { randomUUID } from 'node:crypto';import { readHolders } from './context.ts';/**@@ -15,7 +16,7 @@ import { readHolders } from './context.ts';* from '../operations.ts' here (cycle).*/-import type { Operation } from './contract.ts';+import type { Operation, OperationContext } from './contract.ts';import { OperationError, verbError } from './contract.ts';import { assertExplicitSourceLive, federatedSearchScope, parseSourceIdParam, sourceScopeOpts, stampEvidenceSafe } from './context.ts';import { markKeywordHits } from '../search/evidence.ts';@@ -30,6 +31,7 @@ import { ENTITY_HINTS_CAP } from '../facts/extract.ts';import { parseTtlShorthand } from '../facts/ttl-parse.ts';import { MEMORY_VERBS_VERSION } from '../verbs.ts';import type { SearchResult } from '../types.ts';+import type { BrainEngine, FactRow } from '../engine.ts';import { AUDIT_ROW_SOURCES } from '../facts/audit-sources.ts';// ============================================================@@ -176,12 +178,25 @@ const extract_facts: Operation = {},};+/** One arm of recall's budget_packing accounting. */+function packingArm<T>(candidates: T[], kept: T[], cost: (item: T) => number) {+ return { candidates: candidates.length, kept: kept.length, dropped: candidates.length - kept.length, used: kept.reduce((sum, r) => sum + cost(r), 0) };+}++/** recall's evidence plan: budget_tokens budgets the delivered blocks before recall's own packing. */+function recallEvidencePlan(ctx: OperationContext, p: Record<string, unknown>): Promise<EvidencePlan | null> {+ return resolveEvidencePlan(ctx.engine, {+ remote: ctx.remote, viaSubagent: ctx.viaSubagent, returnUnit: p.return_unit, returnWindow: p.return_window,+ budget: p.budget_tokens, snippetChars: undefined, snippetCap: 0, op: 'recall',+ });+}+const recall: Operation = {name: 'recall',description:'MEMORY VERB (v1): retrieve saved facts/snippets — the protocol read verb. Filters hot-memory facts by entity / since / session_id; pass `query` to ALSO run hybrid search over pages (results[] arm); pass `budget_tokens` for server-side packing (response reports budget_used + dropped_count — never trims client-side). Remote callers see visibility=world facts only. Routing: for ONE known person/company/project card use `entity` (zero LLM); for broad questions needing reasoning use `synthesize` (expensive). Branch on structured fields (status/kind/evidence), never on prose. Every response carries protocol_version.',params: {- entity: { type: 'string', description: 'Entity slug (canonical). Returns facts about this entity newest first.' },+ entity: { type: 'string', description: 'Entity slug (canonical). Returns facts about this entity newest first, each labelled with its source_id. Across several granted sources, same-slug entities that no entity-identity group links are different entities: facts comes back empty and ambiguous_entity names each (source_id, entity_slug); pass source_id to read one.' },query: { type: 'string', description: 'MEMORY_VERBS v1: free-text retrieval over pages (hybrid search arm). Response adds results[] (slug, title, chunk, evidence, create_safety, provenance). Combinable with entity (both arms run). Degrades to keyword-only search when no embedding provider is configured (search_degraded notes it; never an error).' },budget_tokens: { type: 'number', description: 'MEMORY_VERBS v1: server-side token budget (char/4 estimate). Facts pack first, then results. Response adds budget_tokens, budget_used, dropped_count.' },budget_policy: { type: 'string', enum: ['facts_first', 'query_first'], description: 'Optional packing order. facts_first preserves legacy behavior (default). query_first packs the ranked page prefix before facts only with a nonblank query and positive finite budget; a positive budget below one token keeps neither arm. No query or inactive budget preserves legacy behavior. Neither policy skips oversized items or truncates. Supplying this option adds budget_packing accounting. Keep fact-focused/entity-filtered questions on facts_first.' },@@ -193,6 +208,8 @@ const recall: Operation = {limit: { type: 'number', description: 'Per-arm cap: max fact rows AND max search results. Default 50, cap 100.' },grep: { type: 'string', description: 'Substring filter on fact text (case-insensitive). Applied in SQL before the limit, so matches on high-cardinality entities are found even outside the newest-N window.' },include_pending: { type: 'boolean', description: 'v0.32: when true, response includes pending_consolidation_count (facts not yet promoted to takes by the dream-cycle consolidate phase). One round trip; backward-compatible (field omitted when false).' },+ return_unit: { type: 'string', enum: ['chunk', 'window', 'section', 'page', 'auto'], description: "Evidence unit for the results[] arm (needs `query`; default config search.return_unit = 'chunk'). 'window' adds neighbor chunks, 'section' the enclosing section or conversation rounds, 'page' the whole page/session (best for multi-session questions), 'auto' picks per page. Non-chunk units return one result per page with `delivered` metadata and a top-level `delivery` block; the evidence is budgeted by budget_tokens (default 6000) and then packed by recall's usual rules." },+ return_window: { type: 'number', description: "Neighbor chunks on each side for return_unit 'window' (integer 1-3, default 1)." },},scope: 'read',verb: true,@@ -271,6 +288,7 @@ const recall: Operation = {const byEventTime = (rec: Record<string, unknown>) => rec.valid_from ?? rec.created_at;let rows: FactRows = [];+ let ambiguousEntity: EntityCandidate[] | null = null;// `since` is parsed once, up front, and a value that does not parse is// rejected instead of silently widening the window: a caller that asked@@ -317,29 +335,22 @@ const recall: Operation = {// in this session) since T" is a question about when the underlying// events occurred, not about when a batch extraction wrote the rows.const { resolveEntitySlug } = await import('../entities/resolve.ts');- rows = mergeNewest(- await Promise.all(factSources.map(async (src) => {- const entitySlug = entityParam- ? ((await resolveEntitySlug(ctx.engine, src, entityParam)) ?? entityParam)- : undefined;- return ctx.engine.listFactsSince(src, since, {- ...listOpts,- eventTime: true,- entitySlug,- sessionId: sessionParam ?? undefined,- });- })),- byEventTime,- );+ const lists = await Promise.all(factSources.map(async (src) => {+ const entitySlug = entityParam+ ? ((await resolveEntitySlug(ctx.engine, src, entityParam)) ?? entityParam)+ : undefined;+ return ctx.engine.listFactsSince(src, since, { ...listOpts, eventTime: true, entitySlug, sessionId: sessionParam ?? undefined });+ }));+ ambiguousEntity = entityParam ? await unlinkedNamesakes(ctx.engine, lists) : null;+ rows = ambiguousEntity ? [] : mergeNewest(lists, byEventTime);} else if (entityParam) {const { resolveEntitySlug } = await import('../entities/resolve.ts');- rows = mergeNewest(- await Promise.all(factSources.map(async (src) => {- const slug = (await resolveEntitySlug(ctx.engine, src, entityParam)) ?? entityParam;- return ctx.engine.listFactsByEntity(src, slug, listOpts);- })),- (rec) => rec.valid_from ?? rec.created_at,- );+ const lists = await Promise.all(factSources.map(async (src) => {+ const slug = (await resolveEntitySlug(ctx.engine, src, entityParam)) ?? entityParam;+ return ctx.engine.listFactsByEntity(src, slug, listOpts);+ }));+ ambiguousEntity = await unlinkedNamesakes(ctx.engine, lists);+ rows = ambiguousEntity ? [] : mergeNewest(lists, (rec) => rec.valid_from ?? rec.created_at);} else if (sessionParam) {rows = mergeNewest(await Promise.all(factSources.map(src =>@@ -404,6 +415,8 @@ const recall: Operation = {let searchResults: SearchResult[] = [];let searchDegraded: string | undefined;+ let delivery: DeliveryMeta | undefined;+ const evidencePlan = queryText ? await recallEvidencePlan(ctx, p) : null;if (queryText) {// #3242 parity (#4707): the page-search arm widens an unqualified// no-grant caller across the transport-computed federated set, exactly@@ -434,6 +447,7 @@ const recall: Operation = {});}bumpLastRetrievedAt(ctx.engine, searchResults.map(r => r.page_id));+ if (evidencePlan) ({ results: searchResults, delivery } = await deliverEvidence(ctx.engine, searchResults, evidencePlan, { ...searchScope, excludePrivate, requireSafeChunks: ctx.remote !== false }));}let packedFacts = rows;@@ -476,18 +490,8 @@ const recall: Operation = {: rows.length + searchResults.length === 0 ? 'no_candidates': packedFacts.length + packedResults.length === 0 ? 'first_items_exceed_budget': 'packed',- facts: {- candidates: rows.length,- kept: packedFacts.length,- dropped: rows.length - packedFacts.length,- used: packedFacts.reduce((sum, r) => sum + estimateTokens(r.fact), 0),- },- results: {- candidates: searchResults.length,- kept: packedResults.length,- dropped: searchResults.length - packedResults.length,- used: packedResults.reduce((sum, r) => sum + resultTokens(r), 0),- },+ facts: packingArm(rows, packedFacts, r => estimateTokens(r.fact)),+ results: packingArm(searchResults, packedResults, resultTokens),}: undefined;@@ -497,6 +501,7 @@ const recall: Operation = {fact: r.fact,kind: r.kind,entity_slug: r.entity_slug,+ source_id: r.source_id,visibility: r.visibility,// v0.31.2: notability surfaced to recall consumers (CLI, MCP, admin).// Pre-v46 brains return 'medium' via the row mapper's fallback so the@@ -523,6 +528,7 @@ const recall: Operation = {provenance: r.source,})),total: packedFacts.length,+ ...(ambiguousEntity ? { ambiguous_entity: { candidates: ambiguousEntity, suggestion: AMBIGUOUS_ENTITY_SUGGESTION } } : {}),...(pending_consolidation_count !== undefined ? { pending_consolidation_count } : {}),// MEMORY_VERBS v1 envelope (G1B superset — additive on every response).protocol_version: MEMORY_VERBS_VERSION,@@ -535,6 +541,7 @@ const recall: Operation = {evidence: r.evidence,create_safety: r.create_safety,provenance: r.slug,+ ...(r.delivered ? { delivered: r.delivered } : {}),})),...(searchDegraded ? { search_degraded: searchDegraded } : {}),}@@ -543,10 +550,31 @@ const recall: Operation = {? { budget_tokens: budgetTokens, budget_used: budgetUsed, dropped_count: droppedCount }: {}),...(budgetPacking ? { budget_packing: budgetPacking } : {}),+ ...(delivery ? { delivery } : {}),};},};+type EntityCandidate = { source_id: string; entity_slug: string };+const AMBIGUOUS_ENTITY_SUGGESTION = 'These are different entities in different sources. Pass source_id to read one, or link them with entity_identity_link if they are the same.';++/**+ * The identity key is (source_id, slug): an entity name resolved in several+ * granted sources names different entities unless an entity-identity group+ * links their pages. Merging them would hand the caller a stranger's facts,+ * so federated recall refuses unlinked namesakes and names the candidates.+ * Returns null when the per-source fact lists are one entity.+ */+async function unlinkedNamesakes(engine: BrainEngine, lists: FactRow[][]): Promise<EntityCandidate[] | null> {+ const candidates = [...new Map(lists.flat().map((r): [string, EntityCandidate] =>+ [`${r.source_id}:${r.entity_slug}`, { source_id: r.source_id, entity_slug: r.entity_slug as string }])).values()];+ if (candidates.length < 2) return null;+ const { identityIdsForPages } = await import('../entity-identity.ts');+ const ids = await identityIdsForPages(engine, candidates.map(c => ({ sourceId: c.source_id, slug: c.entity_slug })));+ const groups = new Set(candidates.map(c => ids.get(`${c.source_id}:${c.entity_slug}`) ?? null));+ return groups.size === 1 && !groups.has(null) ? null : candidates;+}+/** Parse an `entities` param (comma-string or array) to a trimmed name list. */function parseEntityList(v: unknown): string[] {if (Array.isArray(v)) return v.filter((x) => typeof x === 'string' && x.trim()).map((x) => (x as string).trim());diff --git a/src/core/ops/search.ts b/src/core/ops/search.tsindex 1371ebe828..3fd5d0cc07 100644--- a/src/core/ops/search.ts+++ b/src/core/ops/search.ts@@ -25,6 +25,7 @@ import type { HybridSearchMeta, SearchResult } from '../types.ts';import { bumpLastRetrievedAt } from '../last-retrieved.ts';import { applySnippetCap, DEFAULT_AGENT_SNIPPET_CHARS } from '../search/snippet-cap.ts';import { redactRetrievalOutput } from '../search/output-redaction.ts';+import { assembleEvidenceForHits, capDeliveredSnippets, deliverEvidence, resolveEvidencePlan, unsupportedDelivery, type DeliveryMeta, type DeliveryScope, type EvidencePlan, type FrozenHit, type ReturnUnit } from '../search/evidence-delivery.ts';import { resolveExcludePrivatePages } from '../search/private-visibility.ts';import { SAFE_FENCE_CHUNKER_VERSION } from '../search/safe-chunks.ts';import { expandEngineTypeFilters } from '../schema-pack/query-types.ts';@@ -65,10 +66,71 @@ async function resolveEffectiveLimit(ctx: OperationContext, p: Record<string, untype SourceScope = { sourceId?: string; sourceIds?: string[] };-function searchOutput(ctx: OperationContext, results: SearchResult[], meta: Record<string, unknown>, snippetCap: number): SearchResult[] {- const output = redactRetrievalOutput(results, meta);+function searchOutput(ctx: OperationContext, results: SearchResult[], meta: Record<string, unknown>, snippetCap: number,+ evidence?: { delivery: DeliveryMeta; explicitSnippet: boolean }): SearchResult[] {+ if (!evidence) {+ const output = redactRetrievalOutput(results, meta);+ ctx.emitResponseMeta?.('retrieval', output.meta);+ return applySnippetCap(output.results, snippetCap);+ }+ // Evidence delivery: explicit snippet_chars wins over the delivered blocks;+ // 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 });+ const capped = evidence.explicitSnippet ? capDeliveredSnippets(output.results, snippetCap, output.meta.delivery) : output.results;ctx.emitResponseMeta?.('retrieval', output.meta);- return applySnippetCap(output.results, snippetCap);+ return capped;+}++/** Evidence delivery params shared by `search` and `query`. */+const RETURN_UNIT_PARAM = {+ type: 'string' as const,+ enum: ['chunk', 'window', 'section', 'page', 'auto'],+ description:+ "Evidence unit returned in each result's chunk_text (default: config search.return_unit, which defaults to 'chunk').\n" ++ " 'chunk' — the ranked chunk only (~300-450 tokens per result).\n" ++ " 'window' — the hit chunk plus return_window neighbor chunks each side (local context, ~3x chunk).\n" ++ " 'section' — the enclosing markdown section, or the conversation rounds around the hit.\n" ++ " 'page' — the whole page/session, capped. Use for multi-session or temporal questions where the answer needs the whole conversation.\n" ++ " 'auto' — page for conversations and short pages, section or window for long curated pages.\n" ++ 'Non-chunk units return one result per page, packed into token_budget (default 6000; remote max 32000), with a `delivered` object (unit, chunk_ids, match_spans, tokens, truncated) per result and `delivery` in the response meta.',+};+const RETURN_WINDOW_PARAM = {+ type: 'number' as const,+ description: "Neighbor chunks on each side for return_unit 'window' (integer 1-3, default 1).",+};++/** With a plan, `token_budget` budgets the delivered evidence, so query's chunk-level budget stays off. */+async function evidencePlanFor(ctx: OperationContext, p: Record<string, unknown>, snippetCap: number, op: string): Promise<EvidencePlan | null> {+ return resolveEvidencePlan(ctx.engine, {+ remote: ctx.remote,+ viaSubagent: ctx.viaSubagent,+ returnUnit: p.return_unit,+ returnWindow: p.return_window,+ budget: p.token_budget,+ snippetChars: p.snippet_chars,+ snippetCap,+ op,+ });+}++/**+ * Run the evidence stage when a plan applies: the rows to serialize plus the+ * delivery handed to searchOutput. Hits from a cache hit are not live, so a+ * failed fetch drops them instead of falling back to cached text.+ */+async function withEvidence(ctx: OperationContext, p: Record<string, unknown>, results: SearchResult[], plan: EvidencePlan | null,+ scope: DeliveryScope, meta: HybridSearchMeta | null): Promise<{ rows: SearchResult[]; evidence?: { delivery: DeliveryMeta; explicitSnippet: boolean } }> {+ if (!plan) return { rows: results };+ const d = await deliverEvidence(ctx.engine, results, plan, { ...scope, requireSafeChunks: ctx.remote !== false }, { liveHits: meta?.cache?.status !== 'hit' });+ return { rows: d.results, evidence: { delivery: d.delivery, explicitSnippet: typeof p.snippet_chars === 'number' && Number.isFinite(p.snippet_chars) } };+}++/** withEvidence + the response meta for the rows actually returned + searchOutput. */+async function evidenceOutput(ctx: OperationContext, p: Record<string, unknown>, results: SearchResult[], plan: EvidencePlan | null, scope: DeliveryScope,+ meta: HybridSearchMeta | null, snippetCap: number, buildMeta: (rows: SearchResult[]) => Promise<Record<string, unknown>>): Promise<SearchResult[]> {+ const ev = await withEvidence(ctx, p, results, plan, scope, meta);+ return searchOutput(ctx, ev.rows, await buildMeta(ev.rows), snippetCap, ev.evidence);}/**@@ -253,6 +315,9 @@ const search: Operation = {types: { type: 'array', items: { type: 'string' }, description: TYPES_PARAM_DESCRIPTION },// #3800: subagent token economy — per-call snippet cap.snippet_chars: { type: 'number', description: SNIPPET_CHARS_PARAM_DESCRIPTION },+ return_unit: RETURN_UNIT_PARAM,+ return_window: RETURN_WINDOW_PARAM,+ token_budget: { type: 'number', description: "Token budget for delivered evidence when return_unit is not 'chunk' (default search.return_budget_default = 6000). Ignored in chunk mode." },// #4415: explicit ranking-axis overrides (the same knobs `query` has had// since v0.29.1). The auto-detect banks are English regex, so on a// non-English brain the recency/salience stages never fire — these flags@@ -282,6 +347,7 @@ const search: Operation = {let types = normalizeTypesParam(p.types);// #3800: snippet cap (param > subagent config default > full text).const snippetCap = await resolveSnippetCap(ctx, p);+ const plan = await evidencePlanFor(ctx, p, snippetCap, 'search');// #4398: explicit per-call source_id wins over ctx.sourceId, validated// (invalid ids throw invalid_params) then resolved through the single// trust+grant resolver (resolveRequestedScope inside federatedSearchScope)@@ -329,7 +395,8 @@ const search: Operation = {bumpLastRetrievedAt(ctx.engine, results.map((r) => r.page_id));maybeCaptureSearch(ctx, queryText, results, Date.now() - startedAt, false);// #3800: cap AFTER capture/meta so eval + cache see the real payload.- return searchOutput(ctx, results, await buildRetrievalResponseMeta(ctx, scope, queryText, results, null, { conceptHint: true, types }), snippetCap);+ return evidenceOutput(ctx, p, results, plan, { ...scope, excludePrivate }, null, snippetCap,+ rows => buildRetrievalResponseMeta(ctx, scope, queryText, rows, null, { conceptHint: true, types }));}// Cheap-hybrid (D4/D15): full vector+keyword+RRF+pool+title+alias, but@@ -355,7 +422,8 @@ const search: Operation = {bumpLastRetrievedAt(ctx.engine, results.map((r) => r.page_id));maybeCaptureSearch(ctx, queryText, results, latency_ms, true, capturedMeta);// #3800: cap AFTER capture/meta so eval + cache see the real payload.- return searchOutput(ctx, results, await buildRetrievalResponseMeta(ctx, scope, queryText, results, capturedMeta, { conceptHint: true, types }), snippetCap);+ return evidenceOutput(ctx, p, results, plan, { ...scope, excludePrivate }, capturedMeta, snippetCap,+ rows => buildRetrievalResponseMeta(ctx, scope, queryText, rows, capturedMeta, { conceptHint: true, types }));},scope: 'read',cliHints: { name: 'search', positional: ['query'] },@@ -398,6 +466,9 @@ const query: Operation = {types: { type: 'array', items: { type: 'string' }, description: TYPES_PARAM_DESCRIPTION },// #3800: subagent token economy — per-call snippet cap.snippet_chars: { type: 'number', description: SNIPPET_CHARS_PARAM_DESCRIPTION },+ return_unit: RETURN_UNIT_PARAM,+ return_window: RETURN_WINDOW_PARAM,+ token_budget: { type: 'number', description: "Token budget. Chunk mode: caps the cumulative chunk payload (results that would overflow are skipped). Non-chunk return_unit: the budget for delivered evidence (default search.return_budget_default = 6000; remote max search.return_budget_max_remote = 32000)." },expand: { type: 'boolean', description: 'Request multi-query expansion (default: true in every search mode, regardless of search.expansion). Set false to opt out. Requires configured embedding and expansion providers; a cloud expander receives the query and may charge for the call. Response metadata expansion_applied reports whether variants were actually used.' },detail: { type: 'string', description: 'Result detail level: low (compiled truth only), medium (default, all with dedup), high (all chunks)' },mode: { type: 'string', description: 'Search mode (conservative|balanced|tokenmax). Local callers only; remote uses configured mode.' },@@ -490,6 +561,7 @@ const query: Operation = {let types = normalizeTypesParam(p.types);// #3800: snippet cap (param > subagent config default > full text).const snippetCap = await resolveSnippetCap(ctx, p);+ const plan = await evidencePlanFor(ctx, p, snippetCap, 'query');const imageData = p.image as string | undefined;const imageMime = (p.image_mime as string) || 'image/jpeg';const embeddingColumnParam =@@ -559,7 +631,7 @@ const query: Operation = {})).map(r => ({ ...r }));stampDeepResearchIds(results);imageMeta.retrieved_count = results.length;- return searchOutput(ctx, results, await buildRetrievalResponseMeta(ctx, querySourceScope, queryText ?? '', results, imageMeta, { types }), snippetCap);+ return searchOutput(ctx, results, { ...await buildRetrievalResponseMeta(ctx, querySourceScope, queryText ?? '', results, imageMeta, { types }), ...(plan ? { delivery: unsupportedDelivery(plan, 'image_query_unsupported') } : {}) }, snippetCap);}if (!queryText) {@@ -618,7 +690,7 @@ const query: Operation = {since: typeof p.since === 'string' ? p.since : undefined,until: typeof p.until === 'string' ? p.until : undefined,// v0.32.x search-lite: token budget + cache opt-outs.- tokenBudget: typeof p.token_budget === 'number' ? (p.token_budget as number) : undefined,+ tokenBudget: !plan && typeof p.token_budget === 'number' ? (p.token_budget as number) : undefined,useCache: typeof p.use_cache === 'boolean' ? (p.use_cache as boolean) : undefined,intentWeighting: typeof p.intent_weighting === 'boolean' ? (p.intent_weighting as boolean) : undefined,// v0.36 cross-modal routing param.@@ -802,19 +874,61 @@ const query: Operation = {// WP2/D3: query never nudges toward itself — no concept hint here.// #1663: the CRAG grade rides the same retrieval meta channel.- const responseMeta = {- ...(await buildRetrievalResponseMeta(ctx, querySourceScope, queryText, results, capturedMeta, { types })),- crag,- };// #3800: cap AFTER capture/meta/CRAG so every internal consumer graded// and recorded the real payload; only the returned envelope is snipped.- return searchOutput(ctx, results, responseMeta, snippetCap);+ return evidenceOutput(ctx, p, results, plan, { ...querySourceScope, excludePrivate, detail }, capturedMeta, snippetCap,+ async rows => ({ ...(await buildRetrievalResponseMeta(ctx, querySourceScope, queryText, rows, capturedMeta, { types })), crag }));},scope: 'read',cliHints: { name: 'query', positional: ['query'] },};+/**+ * Evidence delivery for a frozen, ordered hit list: exactly the evidence the+ * `query` op returns for those hits (same plan resolution, assembler and+ * redaction). gbrain-evals uses it for product-path parity (E3); agents can+ * use it to widen hits from an earlier search. Hits are resolved under the+ * caller's read scope — out-of-scope, deleted or private-to-caller hits are+ * reported by index in `unresolved`, never read.+ */+const assemble_evidence: Operation = {+ name: 'assemble_evidence',+ description:+ 'Deliver whole evidence for an ordered list of search hits (each {source_id, slug, chunk_id} from a prior search/query result): ' ++ "the same windows, sections or pages `query` returns with return_unit, packed into token_budget. Use it to widen hits you already have " ++ "instead of calling get_page per hit. Returns { results, delivery, unresolved }; results carry chunk_text (the evidence) and `delivered`.",+ params: {+ hits: { type: 'array', required: true, items: { type: 'object' }, description: 'Ordered hits, best first (max 50): [{ "source_id": "default", "slug": "chat/session-0412", "chunk_id": 8812 }]. chunk_id 0 addresses the page\'s first chunk.' },+ return_unit: { ...RETURN_UNIT_PARAM, description: "Evidence unit: 'chunk' | 'window' | 'section' | 'page' | 'auto' (default 'page')." },+ return_window: RETURN_WINDOW_PARAM,+ token_budget: { type: 'number', description: 'Token budget for the delivered evidence (default search.return_budget_default = 6000; remote max 32000).' },+ detail: { type: 'string', enum: ['low', 'medium', 'high'], description: "As query: 'low' delivers compiled truth only (no timeline text)." },+ },+ scope: 'read',+ annotations: { title: 'assemble evidence', readOnlyHint: true },+ handler: async (ctx, p) => {+ const hits = p.hits;+ if (!Array.isArray(hits) || hits.some(h => typeof h !== 'object' || h === null+ || typeof (h as Record<string, unknown>).source_id !== 'string' || typeof (h as Record<string, unknown>).slug !== 'string'+ || !Number.isInteger((h as Record<string, unknown>).chunk_id))) {+ throw new OperationError('invalid_params', 'hits must be an array of { source_id: string, slug: string, chunk_id: integer }.',+ 'Example: {"hits": [{"source_id": "default", "slug": "chat/session-0412", "chunk_id": 8812}], "return_unit": "page"}');+ }+ const scope = federatedSearchScope(ctx);+ const excludePrivate = await resolveExcludePrivatePages(ctx.engine, ctx.remote);+ const out = await assembleEvidenceForHits(ctx.engine, {+ hits: hits as FrozenHit[],+ return_unit: (p.return_unit as ReturnUnit | undefined) ?? 'page',+ return_window: p.return_window as number | undefined,+ budget_tokens: p.token_budget as number | undefined,+ detail: p.detail as 'low' | 'medium' | 'high' | undefined,+ caller: { remote: ctx.remote !== false, ...scope, excludePrivate },+ });+ return out;+ },+};+// ---------------------------------------------------------------------------// CLI→MCP gap-closure wave — search/cache introspection ops. Read-only views// shared with the `gbrain search modes|stats|tune` + `gbrain cache stats` CLI@@ -934,5 +1048,5 @@ const cache_stats: Operation = {// Ops in EXACTLY the canonical `operations` array order.export const searchOperations: Operation[] = [- search, query, search_stats, search_modes, search_tune, cache_stats,+ search, query, assemble_evidence, search_stats, search_modes, search_tune, cache_stats,];diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.tsindex 2482e831d7..e2872f8551 100644--- a/src/core/pglite-engine.ts+++ b/src/core/pglite-engine.ts@@ -66,7 +66,7 @@ import {import {valueHash,normalizeDimension,- isNovelDimension,+ isNovelDimension, isBackdatedObservation,} from './chronicle/ontology.ts';import { logBatchRetry as auditLogBatchRetry, logBatchExhausted as auditLogBatchExhausted } from './audit/batch-retry-audit.ts';import { runMigrations } from './migrate.ts';@@ -145,6 +145,7 @@ import * as linksImpl from './engine-sql/links.ts';import * as timelineImpl from './engine-sql/timeline.ts';import * as sourcesImpl from './engine-sql/sources.ts';import * as filesImpl from './engine-sql/files.ts';+import type { ChunkWindowRequest, ChunkWindowOpts, ChunkWindowPage } from './search/chunk-windows.ts';import * as chunksImpl from './engine-sql/chunks.ts';import { searchKeywordCJK } from './engine-sql/cjk-search.ts';import { applyForwardReferenceBootstrap, pgliteBootstrapTarget } from './engine-sql/bootstrap.ts';@@ -1982,6 +1983,8 @@ export class PGLiteEngine implements BrainEngine {}, slug, chunks, opts);}+ getChunkWindows(requests: ChunkWindowRequest[], opts: ChunkWindowOpts): Promise<ChunkWindowPage[]> { return chunksImpl.getChunkWindows(scopedRead(this.engineSql), requests, opts); }+async getChunks(slug: string, opts?: { sourceId?: string; sourceIds?: string[]; includeEmbedding?: boolean; excludePrivate?: boolean; requireSafeChunks?: boolean; includeUnsealed?: boolean }): Promise<Chunk[]> {const sourceIds = opts?.sourceIds && opts.sourceIds.length > 0 ? opts.sourceIds : undefined;const sourceId = opts?.sourceId ?? 'default';@@ -2273,7 +2276,7 @@ export class PGLiteEngine implements BrainEngine {);const current = cur.rows[0] as { id: number; value_hash: string; valid_from: string | null } | undefined;- if (current && current.value_hash === vh) {+ if (current && current.value_hash === vh && !isBackdatedObservation(validFrom, current.valid_from)) {const ins = await this.db.query(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, dimension, value, value_hash, dim_status,confidence, source, source_markdown_slug, valid_from, valid_until, expired_at, consolidated_into)diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex d7c7e15fb0..aa38570c96 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -44,7 +44,7 @@ import { CheckoutGauge, type PoolGaugeSnapshot } from './pool-gauge.ts';import {valueHash,normalizeDimension,- isNovelDimension,+ isNovelDimension, isBackdatedObservation,} from './chronicle/ontology.ts';import { logDbDisconnect } from './audit/db-disconnect-audit.ts';import { logPoolRecovery } from './audit/pool-recovery-audit.ts';@@ -125,6 +125,7 @@ import * as linksImpl from './engine-sql/links.ts';import * as timelineImpl from './engine-sql/timeline.ts';import * as sourcesImpl from './engine-sql/sources.ts';import * as filesImpl from './engine-sql/files.ts';+import type { ChunkWindowRequest, ChunkWindowOpts, ChunkWindowPage } from './search/chunk-windows.ts';import * as chunksImpl from './engine-sql/chunks.ts';import { hasCJK } from './cjk.ts';import { searchKeywordCJK as searchKeywordCJKImpl } from './engine-sql/cjk-search.ts';@@ -1732,6 +1733,10 @@ export class PostgresEngine implements BrainEngine {}, slug, chunks, opts);}+ getChunkWindows(requests: ChunkWindowRequest[], opts: ChunkWindowOpts): Promise<ChunkWindowPage[]> {+ return this.withScopedReadTransaction(opts.sourceIds?.length ? opts.sourceIds : undefined, opts.sourceIds?.length ? undefined : opts.sourceId, tx => chunksImpl.getChunkWindows(scopedRead(this.engineSqlOn(tx)), requests, opts));+ }+async getChunks(slug: string, opts?: { sourceId?: string; sourceIds?: string[]; includeEmbedding?: boolean; excludePrivate?: boolean; requireSafeChunks?: boolean; includeUnsealed?: boolean }): Promise<Chunk[]> {const sourceIds = opts?.sourceIds && opts.sourceIds.length > 0 ? opts.sourceIds : undefined;const sourceId = opts?.sourceId ?? 'default';@@ -2026,7 +2031,7 @@ export class PostgresEngine implements BrainEngine {LIMIT 1`;const current = cur[0];- if (current && current.value_hash === vh) {+ if (current && current.value_hash === vh && !isBackdatedObservation(validFrom, current.valid_from)) {// Same value → corroboration (or exact dup → noop via the dedup unique).const ins = await sql<{ id: number }[]>`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, dimension, value, value_hash, dim_status,diff --git a/src/core/search/chunk-windows.ts b/src/core/search/chunk-windows.tsnew file mode 100644index 0000000000..3f21302d9f--- /dev/null+++ b/src/core/search/chunk-windows.ts@@ -0,0 +1,95 @@+/**+ * Evidence delivery — request/response shapes and the row mapper for the ONE+ * batched neighbor fetch (`BrainEngine.getChunkWindows`). The SQL lives once+ * in `engine-sql/chunks.ts` (`getChunkWindows`); both engines delegate.+ *+ * Keyed by page_id (never slug), so same-slug pages in two sources never mix.+ * Every requested page is re-authorized under the caller's CURRENT read+ * scope with the same predicate the search legs use (source scope, deleted,+ * text projection, archived source, quarantine, private pages, safe chunks);+ * a page that fails is simply absent from the result. Page rows carry the+ * raw body (the assembler sanitizes it whole); chunk rows are read only for+ * sealed pages and anchor the hits in that text.+ */+import type { PageReadScope } from '../types.ts';++export interface ChunkWindowRequest {+ page_id: number;+ /** Inclusive chunk_index range to read. */+ from_index: number;+ to_index: number;+ /** Lower = more important; rows are read in this order under `maxRows`. */+ priority: number;+}++export interface ChunkWindowChunk {+ id: number;+ chunk_index: number;+ chunk_text: string;+ chunk_source: string;+}++export interface ChunkWindowPage {+ page_id: number;+ slug: string;+ source_id: string;+ type: string;+ /** pages.knowledge_revision the chunks belong to. */+ revision: string;+ /** False when the page's chunks predate the protected-body index. */+ sealed: boolean;+ /** The stored body columns (raw; the assembler sanitizes them whole). */+ compiled_truth: string;+ timeline: string;+ /** Highest chunk_index stored for the page (text chunks of any source). */+ max_chunk_index: number;+ /** Rows inside the requested ranges, chunk_index order. */+ chunks: ChunkWindowChunk[];+ /** True when the row cap stopped before every requested row was read. */+ row_limited: boolean;+}++export interface ChunkWindowOpts extends PageReadScope {+ /** Restrict to these chunk sources (detail: 'low' passes ['compiled_truth']). */+ chunkSources: string[];+ /** Hard cap on chunk rows read for the whole request. */+ maxRows: number;+}++/** Group the flat UNION rows into per-page windows. Row order is not trusted. */+export function mapChunkWindowRows(rows: Record<string, unknown>[], maxRows: number): ChunkWindowPage[] {+ const pages = new Map<number, ChunkWindowPage & { prio: number }>();+ const chunkRows = rows+ .filter(r => r.kind === 'chunk')+ .map(r => ({ page_id: Number(r.page_id), id: Number(r.chunk_id), chunk_index: Number(r.chunk_index), chunk_text: String(r.chunk_text ?? ''), chunk_source: String(r.chunk_source), prio: Number(r.prio) }))+ .sort((a, b) => a.prio - b.prio || a.page_id - b.page_id || a.chunk_index - b.chunk_index);+ for (const r of rows) {+ if (r.kind !== 'page') continue;+ pages.set(Number(r.page_id), {+ page_id: Number(r.page_id),+ slug: String(r.slug),+ source_id: String(r.source_id),+ type: String(r.type),+ revision: String(r.revision),+ sealed: r.sealed === true || r.sealed === 't',+ compiled_truth: String(r.compiled_truth ?? ''),+ timeline: String(r.timeline ?? ''),+ max_chunk_index: r.max_chunk_index == null ? -1 : Number(r.max_chunk_index),+ chunks: [],+ row_limited: false,+ prio: Number(r.prio),+ });+ }+ const limited = chunkRows.length > maxRows;+ const kept = limited ? chunkRows.slice(0, maxRows) : chunkRows;+ for (const c of kept) pages.get(c.page_id)?.chunks.push({ id: c.id, chunk_index: c.chunk_index, chunk_text: c.chunk_text, chunk_source: c.chunk_source });+ if (limited) {+ const cutoff = chunkRows[maxRows];+ for (const p of pages.values()) {+ if (p.prio > cutoff.prio || (p.prio === cutoff.prio && p.page_id >= cutoff.page_id)) p.row_limited = true;+ }+ }+ return [...pages.values()]+ .sort((a, b) => a.prio - b.prio || a.page_id - b.page_id)+ .map(({ prio: _prio, ...page }) => page);+}diff --git a/src/core/search/date-bounds.ts b/src/core/search/date-bounds.tsindex 0b7c5a4518..55b1cb784d 100644--- a/src/core/search/date-bounds.ts+++ b/src/core/search/date-bounds.ts@@ -11,15 +11,22 @@ export function resolveDateBoundary(raw: string | undefined, boundary: 'since' |const days = unit === 'd' ? n : unit === 'w' ? n * 7 : unit === 'm' ? n * 30 : n * 365;return new Date(Date.now() - days * 86400000).toISOString();}- if (/^\d{4}-\d{2}-\d{2}$/.test(s)) {- const day = new Date(`${s}T00:00:00Z`);- if (!Number.isFinite(day.getTime()) || day.toISOString().slice(0, 10) !== s || s.startsWith('0000-')) {- throw new Error(`Invalid ${boundary} date: expected a real calendar date.`);- }- return boundary === 'until' ? `${s}T23:59:59.999Z` : s;+ // Only ISO-8601 is accepted: Date.parse also reads strings such as "May 5"+ // (Bun: 2001-05-05) that the database cast then rejects.+ const iso = /^(\d{4}-\d{2}-\d{2})(?:[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d{1,9})?)?(?:Z|[+-]\d{2}(?::?\d{2})?)?)?$/i.exec(s);+ if (!iso) {+ throw new Error(`Invalid ${boundary} value "${s}" — expected ISO-8601 (YYYY-MM-DD or timestamp) or a relative duration like '7d', '2w', '1y'.`);}- if (Number.isFinite(Date.parse(s))) return s;- throw new Error(`Invalid ${boundary} value "${s}" — expected ISO-8601 (YYYY-MM-DD or timestamp) or a relative duration like '7d', '2w', '1y'.`);+ const date = iso[1];+ const day = new Date(`${date}T00:00:00Z`);+ if (!Number.isFinite(day.getTime()) || day.toISOString().slice(0, 10) !== date || date.startsWith('0000-')) {+ throw new Error(`Invalid ${boundary} date: expected a real calendar date.`);+ }+ if (s === date) return boundary === 'until' ? `${date}T23:59:59.999Z` : date;+ if (!Number.isFinite(Date.parse(s.replace(' ', 'T')))) {+ throw new Error(`Invalid ${boundary} value "${s}" — expected ISO-8601 (YYYY-MM-DD or timestamp) or a relative duration like '7d', '2w', '1y'.`);+ }+ return s;}export function resolveSearchDateBounds(opts?: SearchOpts): Pick<SearchOpts, 'afterDate' | 'beforeDate' | 'afterDateInclusive' | 'beforeDateInclusive'> {diff --git a/src/core/search/evidence-delivery.ts b/src/core/search/evidence-delivery.tsnew file mode 100644index 0000000000..d7e0d7b2ef--- /dev/null+++ b/src/core/search/evidence-delivery.ts@@ -0,0 +1,1061 @@+/**+ * Evidence delivery (`return_unit`) — the authorization-safe assembler that+ * turns ranked chunk hits into whole evidence: a window of neighbor chunks,+ * the enclosing section, or the page, packed into a token budget.+ *+ * Runs at the op layer AFTER `hybridSearchCached` returns and before output+ * redaction / snippet capping. It never mutates the hit rows (they may be+ * shared with cache or capture) and never caches expanded text. Opt-in: a+ * resolved unit of `chunk` means the stage does not run at all, so the+ * off path is byte-identical.+ *+ * Text source: the page's stored body, sanitized WHOLE with the strict+ * protected-body boundary before any slicing (a slice can cut a fence and+ * read as a protected tail), fetched with the hit chunks in one batched+ * `getChunkWindows` call that re-authorizes every page under the caller's+ * current read scope. Chunks only anchor hits in that text.+ *+ * The normative algorithm (page text, units, allocation, spans) is specified+ * in docs/evidence-delivery.md; gbrain-evals measures exactly this code.+ */+import { createHash } from 'node:crypto';+import type { BrainEngine } from '../engine.ts';+import type { PageReadScope, SearchResult } from '../types.ts';+import type { ChunkWindowPage, ChunkWindowRequest } from './chunk-windows.ts';+import { estimateTokens as cl100kTokens, cl100kAvailable } from '../chunkers/token-estimate.ts';+import { estimateTokens as heuristicTokens } from './token-budget.ts';+import { redactRetrievalOutput } from './output-redaction.ts';+import { buildSnippetMarker } from './snippet-cap.ts';+import { pageReadFilter } from './read-policy-sql.ts';+import { currentTextProjectionFilter, safeChunksFilter, requiresSafeChunks } from './safe-chunks.ts';+import { resolveExcludePrivatePages } from './private-visibility.ts';+import { safeSplitIndex } from '../text-safe.ts';+import { sanitizeRemoteBody } from '../remote-body.ts';+import { OperationError } from '../ops/contract.ts';++export const RETURN_UNITS = ['chunk', 'window', 'section', 'page', 'auto'] as const;+export type ReturnUnit = typeof RETURN_UNITS[number];+export type DeliveredUnit = 'chunk' | 'window' | 'section' | 'page';++export const RETURN_UNIT_CONFIG_KEY = 'search.return_unit';+export const THINK_RETURN_UNIT_CONFIG_KEY = 'think.return_unit';+export const RETURN_WINDOW_CONFIG_KEY = 'search.return_window';+export const RETURN_BUDGET_DEFAULT_KEY = 'search.return_budget_default';+export const RETURN_BUDGET_MAX_REMOTE_KEY = 'search.return_budget_max_remote';+export const DEFAULT_RETURN_BUDGET = 6000;+export const DEFAULT_REMOTE_BUDGET_MAX = 32000;+export const EVIDENCE_BLOCK_CHAR_CAP = 60_000;+export const EVIDENCE_OMISSION = '\n\n[…]\n\n';+export const EVIDENCE_FETCH_TIMEOUT_MS = 5000;+/** First server release that understands `return_unit` (thin-client skew warning). */+export const EVIDENCE_DELIVERY_MIN_SERVER_VERSION = '0.60.13.0';++const AUTO_SHORT_PAGE_CHUNKS = 3;+const PIECE_MAX_CHARS = 400;+const MAX_ROWS = 1024;+const MAX_WINDOW = 3;++export interface MatchSpan { chunk_id: number; start: number; end: number }++export interface DeliveredEvidence {+ unit: DeliveredUnit;+ chunk_ids: number[];+ match_spans: MatchSpan[];+ tokens: number;+ truncated: boolean;+ revision?: string;+ unmapped_chunk_ids?: number[];+ fallback_reason?: string;+}++export interface DeliveryMeta {+ requested_unit: ReturnUnit;+ applied_unit: ReturnUnit;+ return_window: number;+ budget_tokens: number;+ budget_used: number;+ tokens_delivered: number;+ tokenizer: 'cl100k' | 'heuristic';+ coordinates: 'utf16';+ blocks: number;+ dropped: number;+ dropped_reasons: Record<string, number>;+ fallbacks: string[];+ budget_clamped?: { requested: number; max: number };+}++export type DeliveredSearchResult = SearchResult & { delivered: DeliveredEvidence };++export interface EvidencePlan {+ requestedUnit: ReturnUnit;+ unit: Exclude<ReturnUnit, 'chunk'>;+ window: number;+ budgetTokens: number;+ /** return_unit came from the call, not config (snippet precedence). */+ explicitUnit: boolean;+ budgetClamped?: { requested: number; max: number };+}++export interface DeliveryScope extends PageReadScope {+ detail?: 'low' | 'medium' | 'high';+}++// ---------------------------------------------------------------------------+// Parameter validation + plan resolution+// ---------------------------------------------------------------------------++function exampleCall(op: string, unit: string, extra = ''): string {+ const head = op === 'recall' ? '"query": "renewal terms"' : '"query": "launch date"';+ return `Example: {${head}, "return_unit": "${unit}"${extra}}`;+}++export function parseReturnUnit(raw: unknown, op: string): ReturnUnit | undefined {+ if (raw === undefined || raw === null) return undefined;+ if (typeof raw === 'string' && (RETURN_UNITS as readonly string[]).includes(raw)) return raw as ReturnUnit;+ const shown = typeof raw === 'string' ? JSON.stringify(raw.slice(0, 40)) : typeof raw;+ throw new OperationError(+ 'invalid_params',+ `return_unit must be one of ${RETURN_UNITS.join(', ')} (got ${shown}).`,+ `${exampleCall(op, 'page')}. Use "window" for local context, "page" for whole conversations.`,+ );+}++export function parseReturnWindow(raw: unknown, op: string): number | undefined {+ if (raw === undefined || raw === null) return undefined;+ if (typeof raw === 'number' && Number.isInteger(raw) && raw >= 1 && raw <= MAX_WINDOW) return raw;+ const shown = typeof raw === 'number' ? String(raw) : typeof raw;+ throw new OperationError(+ 'invalid_params',+ `return_window must be an integer from 1 to ${MAX_WINDOW} (got ${shown}).`,+ exampleCall(op, 'window', ', "return_window": 2'),+ );+}++async function configNumber(engine: BrainEngine, key: string): Promise<number | null> {+ try {+ const raw = await engine.getConfig(key);+ if (raw == null || raw === '') return null;+ const n = Number(raw);+ return Number.isFinite(n) ? n : null;+ } catch {+ return null;+ }+}++export interface ResolvePlanInput {+ remote: boolean | undefined;+ viaSubagent?: boolean;+ returnUnit: unknown;+ returnWindow: unknown;+ /** The op's own budget param (token_budget / budget_tokens). */+ budget: unknown;+ /** Explicit snippet_chars param (number) or undefined. */+ snippetChars: unknown;+ /** The resolved snippet cap for this call (0 = none). */+ snippetCap: number;+ configKey?: string;+ op: string;+}++/**+ * Resolve the per-call evidence plan, or null when the resolved unit is+ * `chunk` (the stage stays inert and the response is unchanged). Throws+ * invalid_params for a bad `return_unit` / `return_window`.+ */+export async function resolveEvidencePlan(engine: BrainEngine, input: ResolvePlanInput): Promise<EvidencePlan | null> {+ const explicit = parseReturnUnit(input.returnUnit, input.op);+ const explicitWindow = parseReturnWindow(input.returnWindow, input.op);+ let unit: ReturnUnit = explicit ?? 'chunk';+ if (explicit === undefined) {+ try {+ const raw = await engine.getConfig(input.configKey ?? RETURN_UNIT_CONFIG_KEY);+ if (typeof raw === 'string' && (RETURN_UNITS as readonly string[]).includes(raw)) unit = raw as ReturnUnit;+ } catch { /* config unreadable: stay on chunk */ }+ // Snippet precedence: a config-level unit never overrides an explicit+ // snippet cap or the subagent default token economy.+ const explicitSnippet = typeof input.snippetChars === 'number' && Number.isFinite(input.snippetChars);+ if (unit !== 'chunk' && !explicitSnippet && input.viaSubagent === true && input.snippetCap > 0) unit = 'chunk';+ }+ if (unit === 'chunk') return null;+ let window = explicitWindow ?? 1;+ if (explicitWindow === undefined) {+ const w = await configNumber(engine, RETURN_WINDOW_CONFIG_KEY);+ if (w !== null) window = Math.min(MAX_WINDOW, Math.max(1, Math.floor(w)));+ }+ let budget = typeof input.budget === 'number' && Number.isFinite(input.budget) && input.budget > 0+ ? Math.floor(input.budget)+ : Math.floor((await configNumber(engine, RETURN_BUDGET_DEFAULT_KEY)) ?? DEFAULT_RETURN_BUDGET);+ if (budget <= 0) budget = DEFAULT_RETURN_BUDGET;+ let budgetClamped: EvidencePlan['budgetClamped'];+ if (input.remote !== false) {+ const cfgMax = await configNumber(engine, RETURN_BUDGET_MAX_REMOTE_KEY);+ const max = cfgMax !== null && cfgMax > 0 ? Math.floor(cfgMax) : DEFAULT_REMOTE_BUDGET_MAX;+ if (budget > max) {+ budgetClamped = { requested: budget, max };+ budget = max;+ }+ }+ return {+ requestedUnit: unit,+ unit,+ window,+ budgetTokens: budget,+ explicitUnit: explicit !== undefined,+ ...(budgetClamped ? { budgetClamped } : {}),+ };+}++// ---------------------------------------------------------------------------+// Tokens+// ---------------------------------------------------------------------------++export function evidenceTokenizer(): 'cl100k' | 'heuristic' {+ return cl100kAvailable() ? 'cl100k' : 'heuristic';+}++function pieceTokens(text: string, tokenizer: 'cl100k' | 'heuristic'): number {+ if (!text) return 0;+ return tokenizer === 'cl100k' ? cl100kTokens(text) : heuristicTokens(text);+}++/** Split into lines (newline kept); lines over PIECE_MAX_CHARS split at whitespace. */+export function splitPieces(text: string): Array<{ start: number; end: number; lineStart: boolean }> {+ const out: Array<{ start: number; end: number; lineStart: boolean }> = [];+ let i = 0;+ while (i < text.length) {+ const nl = text.indexOf('\n', i);+ const lineEnd = nl === -1 ? text.length : nl + 1;+ let s = i;+ let first = true;+ while (s < lineEnd) {+ let e = lineEnd;+ if (e - s > PIECE_MAX_CHARS) {+ e = s + PIECE_MAX_CHARS;+ const ws = text.slice(s + PIECE_MAX_CHARS - 80, e).search(/\s\S*$/);+ e = ws >= 0 ? s + PIECE_MAX_CHARS - 80 + ws + 1 : safeSplitIndex(text, e);+ if (e <= s) e = Math.min(lineEnd, s + PIECE_MAX_CHARS);+ }+ out.push({ start: s, end: e, lineStart: first });+ first = false;+ s = e;+ }+ i = lineEnd;+ }+ return out;+}++/** Deterministic token count: the sum of per-piece counts (see the doc). */+export function countEvidenceTokens(text: string, tokenizer: 'cl100k' | 'heuristic' = evidenceTokenizer()): number {+ let n = 0;+ for (const p of splitPieces(text)) n += pieceTokens(text.slice(p.start, p.end), tokenizer);+ return n;+}++function sliceToTokenCount(text: string, max: number, tokenizer: 'cl100k' | 'heuristic'): string {+ if (max <= 0) return '';+ if (countEvidenceTokens(text, tokenizer) <= max) return text;+ let lo = 0;+ let hi = text.length;+ while (lo < hi) {+ const mid = Math.ceil((lo + hi) / 2);+ if (countEvidenceTokens(text.slice(0, safeSplitIndex(text, mid)), tokenizer) <= max) lo = mid;+ else hi = mid - 1;+ }+ return text.slice(0, safeSplitIndex(text, lo));+}++// ---------------------------------------------------------------------------+// Locating chunks in the sanitized body+// ---------------------------------------------------------------------------++/** Separator serializeMarkdown writes between compiled truth and timeline. */+export const TIMELINE_SEPARATOR = '\n\n<!-- timeline -->\n\n';++/** Whitespace runs collapsed to one space, with a map back to original offsets. */+function squeeze(text: string): { s: string; map: number[] } {+ const parts: string[] = [];+ const map: number[] = [];+ let runStart = 0;+ const WS = /\s+/g;+ for (const m of text.matchAll(WS)) {+ const at = m.index!;+ if (at > runStart) {+ parts.push(text.slice(runStart, at));+ for (let i = runStart; i < at; i++) map.push(i);+ }+ parts.push(' ');+ map.push(at);+ runStart = at + m[0].length;+ }+ if (runStart < text.length) {+ parts.push(text.slice(runStart));+ for (let i = runStart; i < text.length; i++) map.push(i);+ }+ return { s: parts.join(''), map };+}++/**+ * Locate each chunk (chunk_index order) in the page text the chunks were cut+ * from. The chunker trims chunks and can fold whitespace-only runs, so the+ * match ignores whitespace differences; consecutive chunks overlap, so each+ * search starts just after the previous chunk's start. Unlocated chunks are absent.+ */+export function locateChunks(text: string, chunks: Array<{ id: number; chunk_index: number; chunk_text: string }>): Array<{ id: number; chunk_index: number; start: number; end: number }> {+ let body: ReturnType<typeof squeeze> | null = null;+ const out: Array<{ id: number; chunk_index: number; start: number; end: number }> = [];+ let from = 0;+ for (const c of [...chunks].sort((a, b) => a.chunk_index - b.chunk_index)) {+ const exact = c.chunk_text.trim();+ if (exact.length === 0) continue;+ let at = text.indexOf(exact, from);+ if (at < 0) at = text.indexOf(exact);+ if (at >= 0) {+ out.push({ id: c.id, chunk_index: c.chunk_index, start: at, end: at + exact.length });+ from = at + 1;+ continue;+ }+ body ??= squeeze(text);+ const needle = squeeze(exact).s;+ let lo = 0;+ let hi = body.map.length;+ while (lo < hi) { const mid = (lo + hi) >> 1; if (body.map[mid] < from) lo = mid + 1; else hi = mid; }+ let sq = body.s.indexOf(needle, lo);+ if (sq < 0) sq = body.s.indexOf(needle);+ if (sq < 0) continue;+ out.push({ id: c.id, chunk_index: c.chunk_index, start: body.map[sq], end: body.map[sq + needle.length - 1] + 1 });+ from = body.map[sq] + 1;+ }+ return out;+}++// ---------------------------------------------------------------------------+// Document model+// ---------------------------------------------------------------------------++interface Piece {+ run: number;+ start: number;+ end: number;+ text: string;+ lineStart: boolean;+ heading: number;+ speaker: string | null;+ tok: number;+}++interface Doc {+ text: string;+ pieces: Piece[];+ spans: Array<{ id: number; chunk_index: number; start: number; end: number }>;+}++const HEADING = /^ {0,3}(#{1,6})[ \t]+\S/;+const FENCE = /^ {0,3}(```|~~~)/;+const SPEAKER = /^\s{0,3}(?:\*\*([^*\n:]{1,40}):\s*\*\*|\*\*([^*\n:]{1,40})\*\*\s*:|(user|assistant|human|ai|system|bot|speaker\s*\d{1,3})\s*:)/i;++function buildDoc(text: string, spans: Doc['spans']): Doc {+ const pieces: Piece[] = [];+ let inFence = false;+ for (const p of splitPieces(text)) {+ const t = text.slice(p.start, p.end);+ let heading = 0;+ let speaker: string | null = null;+ if (p.lineStart) {+ if (FENCE.test(t)) inFence = !inFence;+ else if (!inFence) {+ const h = HEADING.exec(t);+ if (h) heading = h[1].length;+ const sp = SPEAKER.exec(t);+ if (sp) speaker = (sp[1] ?? sp[2] ?? sp[3]).trim().toLowerCase().replace(/\s+/g, ' ');+ }+ }+ pieces.push({ run: 0, start: p.start, end: p.end, text: t, lineStart: p.lineStart, heading, speaker, tok: -1 });+ }+ return { text, pieces, spans };+}++/** ≥ 4 speaker-turn lines, ≥ 2 distinct labels, ≥ 3 label changes. */+export function isConversationLabels(labels: string[]): boolean {+ if (labels.length < 4 || new Set(labels).size < 2) return false;+ let changes = 0;+ for (let i = 1; i < labels.length; i++) if (labels[i] !== labels[i - 1]) changes++;+ return changes >= 3;+}++function piecesOverlapping(doc: Doc, start: number, end: number): number[] {+ let lo = 0;+ let hi = doc.pieces.length;+ while (lo < hi) {+ const mid = (lo + hi) >> 1;+ if (doc.pieces[mid].end <= start) lo = mid + 1;+ else hi = mid;+ }+ const out: number[] = [];+ for (let i = lo; i < doc.pieces.length && doc.pieces[i].start < end; i++) out.push(i);+ return out;+}++// ---------------------------------------------------------------------------+// Blocks+// ---------------------------------------------------------------------------++interface Anchor {+ chunk_id: number;+ mapped: boolean;+ pieces: number[];+ start: number;+ end: number;+ chunkIndex: number;+}++interface Block {+ hit: SearchResult;+ hits: SearchResult[];+ doc: Doc;+ unit: DeliveredUnit;+ candidates: number[];+ anchors: Anchor[];+ revision?: string;+ fallbackReason?: string;+ titleTok: number;+ selected: Set<number>;+ cut: boolean;+ title: string;+}++function fallbackBlock(hit: SearchResult, hits: SearchResult[], reason: string): Omit<Block, 'titleTok' | 'title'> {+ const text = hit.chunk_text ?? '';+ const doc = buildDoc(text, []);+ const all = doc.pieces.map((_, i) => i);+ return {+ hit, hits, doc, unit: 'chunk', candidates: all,+ anchors: [+ { chunk_id: hit.chunk_id, mapped: true, pieces: all, start: 0, end: text.length, chunkIndex: hit.chunk_index },+ ...hits.slice(1).map(h => ({ chunk_id: h.chunk_id, mapped: false, pieces: [], start: 0, end: 0, chunkIndex: h.chunk_index })),+ ],+ fallbackReason: reason, selected: new Set(), cut: false,+ };+}++/**+ * The page text evidence is cut from: the complete stored body, sanitized+ * with the strict protected-body boundary BEFORE any slicing (Takes, non-world+ * and withdrawn Facts rows, malformed protected tails, materialized markers),+ * compiled truth and timeline each sanitized whole and joined the way+ * serializeMarkdown joins them. Frontmatter is not part of it.+ */+export function pageEvidenceText(page: { compiled_truth: string; timeline: string }, includeTimeline: boolean): { text: string; timelineAt: number } {+ const truth = sanitizeRemoteBody(page.compiled_truth ?? '');+ const timeline = includeTimeline ? sanitizeRemoteBody(page.timeline ?? '') : '';+ if (!timeline.trim()) return { text: truth, timelineAt: -1 };+ return { text: truth + TIMELINE_SEPARATOR + timeline, timelineAt: truth.length + TIMELINE_SEPARATOR.length };+}++function locateAnchor(doc: Doc, hit: SearchResult): Anchor {+ const byId = hit.chunk_id > 0 ? doc.spans.find(x => x.id === hit.chunk_id) : undefined;+ if (byId) return { chunk_id: hit.chunk_id, mapped: true, pieces: piecesOverlapping(doc, byId.start, byId.end), start: byId.start, end: byId.end, chunkIndex: byId.chunk_index };+ const text = (hit.chunk_text ?? '').trim();+ if (text.length >= 16) {+ const found = locateChunks(doc.text, [{ id: hit.chunk_id, chunk_index: hit.chunk_index, chunk_text: text }])[0];+ if (found) return { chunk_id: hit.chunk_id, mapped: true, pieces: piecesOverlapping(doc, found.start, found.end), start: found.start, end: found.end, chunkIndex: hit.chunk_index };+ }+ // Positional anchor (the current revision no longer holds the hit chunk, or+ // a synthetic chunk_id 0 row): the nearest located chunk drives the unit+ // cut, but no match span is reported.+ let best: Doc['spans'][number] | null = null;+ for (const sp of doc.spans) if (!best || Math.abs(sp.chunk_index - hit.chunk_index) < Math.abs(best.chunk_index - hit.chunk_index)) best = sp;+ if (!best) return { chunk_id: hit.chunk_id, mapped: false, pieces: [], start: 0, end: 0, chunkIndex: hit.chunk_index };+ const mapped = hit.chunk_id === 0 && best.chunk_index === hit.chunk_index;+ return { chunk_id: hit.chunk_id, mapped, pieces: piecesOverlapping(doc, best.start, best.end), start: best.start, end: best.end, chunkIndex: best.chunk_index };+}++function windowCandidates(doc: Doc, anchors: Anchor[], n: number): number[] {+ const set = new Set<number>();+ for (const a of anchors) {+ for (const sp of doc.spans) {+ if (Math.abs(sp.chunk_index - a.chunkIndex) <= n) for (const p of piecesOverlapping(doc, sp.start, sp.end)) set.add(p);+ }+ for (const p of a.pieces) set.add(p);+ }+ return [...set].sort((x, y) => x - y);+}++function sectionCandidates(doc: Doc, anchors: Anchor[], conversation: boolean): number[] | null {+ const set = new Set<number>();+ let opener: string | null = null;+ if (conversation) {+ const labels = doc.pieces.map(p => p.speaker).filter((x): x is string => x !== null);+ opener = labels.find(l => l === 'user' || l === 'human') ?? labels[0] ?? null;+ }+ for (const a of anchors) {+ if (a.pieces.length === 0) continue;+ const first = a.pieces[0];+ const last = a.pieces[a.pieces.length - 1];+ let start = 0;+ let level = 0;+ for (let i = first; i >= 0; i--) {+ const p = doc.pieces[i];+ if (conversation ? p.speaker === opener : p.heading > 0) { start = i; level = conversation ? 0 : p.heading; break; }+ }+ let end = doc.pieces.length - 1;+ for (let i = last + 1; i < doc.pieces.length; i++) {+ const p = doc.pieces[i];+ if (conversation ? p.speaker === opener : p.heading > 0 && (level === 0 || p.heading <= level)) { end = i - 1; break; }+ }+ for (let i = start; i <= end; i++) set.add(i);+ }+ return set.size === 0 ? null : [...set].sort((x, y) => x - y);+}++function planBlock(page: ChunkWindowPage, hits: SearchResult[], plan: EvidencePlan, includeTimeline: boolean): Omit<Block, 'titleTok' | 'title'> {+ const best = hits[0];+ if (!page.sealed) return fallbackBlock(best, hits, 'unsealed_page');+ if (page.chunks.length === 0) return fallbackBlock(best, hits, page.row_limited ? 'row_limit' : 'no_text_chunks');+ const { text, timelineAt } = pageEvidenceText(page, includeTimeline);+ const truthChunks = page.chunks.filter(c => c.chunk_source === 'compiled_truth');+ const timelineChunks = page.chunks.filter(c => c.chunk_source === 'timeline');+ const spans = [+ ...locateChunks(timelineAt < 0 ? text : text.slice(0, timelineAt - TIMELINE_SEPARATOR.length), truthChunks),+ ...(timelineAt < 0 ? [] : locateChunks(text.slice(timelineAt), timelineChunks).map(sp => ({ ...sp, start: sp.start + timelineAt, end: sp.end + timelineAt }))),+ ];+ const doc = buildDoc(text, spans);+ const anchors = hits.map(h => locateAnchor(doc, h));+ if (anchors.every(a => a.pieces.length === 0)) return fallbackBlock(best, hits, page.row_limited ? 'row_limit' : 'anchor_not_located');+ const labels = doc.pieces.map(p => p.speaker).filter((x): x is string => x !== null);+ const conversation = isConversationLabels(labels);+ const hasHeadings = doc.pieces.some(p => p.heading > 0);+ let unit: DeliveredUnit = plan.unit === 'auto'+ ? (conversation || page.max_chunk_index + 1 <= AUTO_SHORT_PAGE_CHUNKS ? 'page' : hasHeadings ? 'section' : 'window')+ : plan.unit;+ let fallbackReason: string | undefined;+ let candidates: number[];+ if (unit === 'page') {+ candidates = doc.pieces.map((_, i) => i);+ } else if (unit === 'section') {+ const sec = conversation || hasHeadings ? sectionCandidates(doc, anchors, conversation) : null;+ if (sec) candidates = sec;+ else {+ unit = 'window';+ if (plan.unit === 'section') fallbackReason = 'no_section_structure';+ candidates = windowCandidates(doc, anchors, plan.window);+ }+ } else {+ candidates = windowCandidates(doc, anchors, plan.window);+ }+ return {+ hit: best, hits, doc, unit, candidates, anchors,+ revision: page.revision,+ ...(fallbackReason ? { fallbackReason } : {}),+ selected: new Set(), cut: false,+ };+}++// ---------------------------------------------------------------------------+// Allocation + emission+// ---------------------------------------------------------------------------++function tok(b: Block, i: number, tokenizer: 'cl100k' | 'heuristic'): number {+ const p = b.doc.pieces[i];+ if (p.tok < 0) p.tok = pieceTokens(p.text, tokenizer);+ return p.tok;+}++function adjacent(b: Block, i: number): boolean {+ const p = b.doc.pieces[i];+ return (b.selected.has(i - 1) && b.doc.pieces[i - 1].run === p.run) || (b.selected.has(i + 1) && b.doc.pieces[i + 1]?.run === p.run);+}++function enrichmentOrder(b: Block): number[] {+ const core = new Set(b.anchors[0]?.pieces ?? []);+ const candPos = new Map(b.candidates.map((c, i) => [c, i]));+ const coreRank = new Map<number, number>();+ b.anchors.slice(1).forEach((a, r) => { for (const p of a.pieces) if (!coreRank.has(p)) coreRank.set(p, r); });+ const seeds = b.candidates.map((c, i) => (core.has(c) || coreRank.has(c) ? i : -1)).filter(i => i >= 0);+ const dist = new Array<number>(b.candidates.length).fill(Number.MAX_SAFE_INTEGER);+ for (const s of seeds) dist[s] = 0;+ for (let i = 1; i < dist.length; i++) dist[i] = Math.min(dist[i], dist[i - 1] + 1);+ for (let i = dist.length - 2; i >= 0; i--) dist[i] = Math.min(dist[i], dist[i + 1] + 1);+ return b.candidates+ .filter(c => !core.has(c))+ .sort((x, y) => {+ const ox = coreRank.has(x) ? 0 : 1;+ const oy = coreRank.has(y) ? 0 : 1;+ if (ox !== oy) return ox - oy;+ if (ox === 0 && coreRank.get(x)! !== coreRank.get(y)!) return coreRank.get(x)! - coreRank.get(y)!;+ const dx = dist[candPos.get(x)!];+ const dy = dist[candPos.get(y)!];+ return dx - dy || x - y;+ });+}++function allocate(blocks: Block[], budget: number, tokenizer: 'cl100k' | 'heuristic', dropped: Record<string, number>): Block[] {+ const omitTok = pieceTokens(EVIDENCE_OMISSION, tokenizer);+ let remaining = budget;+ const kept: Block[] = [];+ 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) {+ for (const i of core) b.selected.add(i);+ remaining -= floor;+ kept.push(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;+ kept.push(b);+ continue;+ }+ droppedAny = true;+ dropped.budget_floor = (dropped.budget_floor ?? 0) + 1;+ }+ 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;+ }+ }+ return kept;+}++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>();+ let text = '';+ let gaps = 0;+ let tokens = 0;+ order.forEach((i, k) => {+ const prev = order[k - 1];+ if (k > 0 && !(prev === i - 1 && b.doc.pieces[prev].run === b.doc.pieces[i].run)) {+ text += EVIDENCE_OMISSION;+ gaps++;+ }+ emitStart.set(i, text.length);+ text += b.doc.pieces[i].text;+ tokens += tok(b, i, tokenizer);+ });+ tokens += gaps * pieceTokens(EVIDENCE_OMISSION, tokenizer);+ const trimmed = text.replace(/\s+$/, '');+ const spans: MatchSpan[] = [];+ const unmapped: number[] = [];+ for (const a of b.anchors) {+ if (!a.mapped) { unmapped.push(a.chunk_id); continue; }+ const sel = a.pieces.filter(i => b.selected.has(i));+ if (sel.length === 0) { unmapped.push(a.chunk_id); continue; }+ let segStart = sel[0];+ for (let k = 0; k < sel.length; k++) {+ const i = sel[k];+ const next = sel[k + 1];+ if (next === i + 1 && emitStart.get(next)! === emitStart.get(i)! + b.doc.pieces[i].text.length) continue;+ const first = b.doc.pieces[segStart];+ const last = b.doc.pieces[i];+ const start = emitStart.get(segStart)! + Math.max(0, a.start - first.start);+ const end = Math.min(trimmed.length, emitStart.get(i)! + Math.min(last.text.length, a.end - last.start));+ if (end > start) spans.push({ chunk_id: a.chunk_id, start, end });+ segStart = next;+ }+ }+ return { text: trimmed, spans, unmapped, tokens };+}++// ---------------------------------------------------------------------------+// The stage+// ---------------------------------------------------------------------------++export interface DeliverOptions {+ /**+ * The hits came from this request's live, authorized retrieval: a fetch+ * failure may fall back to the hit chunk text. When false (cached hits),+ * a fetch failure drops the result instead — uncertain authorization+ * never fails open to cached text.+ */+ liveHits?: boolean;+ timeoutMs?: number;+}++function withTimeout<T>(p: Promise<T>, ms: number): Promise<T> {+ let timer: ReturnType<typeof setTimeout> | undefined;+ const t = new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new EvidenceTimeout()), ms); });+ return Promise.race([p, t]).finally(() => clearTimeout(timer));+}++class EvidenceTimeout extends Error {}++/**+ * Assemble delivered evidence for ranked hits. Returns NEW result objects+ * (one per page, at the page's best rank) plus the delivery meta. The hit+ * array and its objects are never mutated.+ */+export async function deliverEvidence(+ engine: BrainEngine,+ hits: SearchResult[],+ plan: EvidencePlan,+ scope: DeliveryScope,+ opts: DeliverOptions = {},+): Promise<{ results: DeliveredSearchResult[]; delivery: DeliveryMeta }> {+ const tokenizer = evidenceTokenizer();+ const fallbacks = new Set<string>();+ const dropped: Record<string, number> = {};+ if (plan.budgetClamped) fallbacks.add('budget_clamped');+ if (tokenizer === 'heuristic') fallbacks.add('tokenizer_heuristic');++ const groups: Array<{ pageId: number | null; hits: SearchResult[] }> = [];+ const byPage = new Map<number, { pageId: number; hits: SearchResult[] }>();+ for (const h of hits) {+ const id = Number.isFinite(h.page_id) ? h.page_id : null;+ if (id === null) { groups.push({ pageId: null, hits: [h] }); continue; }+ const g = byPage.get(id);+ if (g) g.hits.push(h);+ else { const ng = { pageId: id, hits: [h] }; byPage.set(id, ng); groups.push(ng); }+ }++ // Chunks only anchor hits in the page text; every unit but window (and the+ // section fallback to window) needs just the hit chunks themselves.+ const radius = plan.window;+ const requests: ChunkWindowRequest[] = [];+ groups.forEach((g, rank) => {+ if (g.pageId === null) return;+ for (const h of g.hits) {+ const at = Number.isFinite(h.chunk_index) ? h.chunk_index : 0;+ requests.push({ page_id: g.pageId, from_index: Math.max(0, at - radius), to_index: at + radius, priority: rank });+ }+ });+ const maxRows = Math.min(MAX_ROWS, requests.reduce((n, r) => n + (r.to_index - r.from_index + 1), 0));++ let pages: Map<number, ChunkWindowPage> | null = null;+ let fetchFailure: string | null = null;+ if (requests.length > 0) {+ try {+ const rows = await withTimeout(engine.getChunkWindows(requests, {+ ...(scope.sourceIds && scope.sourceIds.length > 0 ? { sourceIds: scope.sourceIds } : scope.sourceId ? { sourceId: scope.sourceId } : {}),+ excludePrivate: scope.excludePrivate,+ requireSafeChunks: requiresSafeChunks(scope),+ chunkSources: scope.detail === 'low' ? ['compiled_truth'] : ['compiled_truth', 'timeline'],+ maxRows,+ }), opts.timeoutMs ?? EVIDENCE_FETCH_TIMEOUT_MS);+ pages = new Map(rows.map(p => [p.page_id, p]));+ } catch (e) {+ fetchFailure = e instanceof EvidenceTimeout ? 'fetch_timeout' : 'fetch_failed';+ fallbacks.add(fetchFailure);+ }+ }++ const planned: Block[] = [];+ for (const g of groups) {+ let b: Omit<Block, 'titleTok' | 'title'>;+ if (g.pageId === null) {+ b = fallbackBlock(g.hits[0], g.hits, 'page_missing');+ } else if (fetchFailure) {+ if (opts.liveHits === false) { dropped.not_readable = (dropped.not_readable ?? 0) + 1; continue; }+ b = fallbackBlock(g.hits[0], g.hits, fetchFailure);+ } else {+ const page = pages?.get(g.pageId);+ if (!page) { dropped.not_readable = (dropped.not_readable ?? 0) + 1; continue; }+ b = planBlock(page, g.hits, plan, scope.detail !== 'low');+ }+ if (b.fallbackReason) fallbacks.add(b.fallbackReason);+ const title = b.hit.title ?? '';+ planned.push({ ...b, title, titleTok: countEvidenceTokens(title, tokenizer) });+ }++ const kept = allocate(planned, plan.budgetTokens, tokenizer, dropped);+ let results: DeliveredSearchResult[] = kept.map(b => {+ const out = emit(b, tokenizer);+ 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,+ truncated,+ ...(b.revision ? { revision: b.revision } : {}),+ ...(out.unmapped.length > 0 ? { unmapped_chunk_ids: out.unmapped } : {}),+ ...(b.fallbackReason && b.unit === 'chunk' ? { fallback_reason: b.fallbackReason } : {}),+ };+ return { ...b.hit, title: b.title, chunk_text: out.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.+ const redacted = redactRetrievalOutput(results, {}).results;+ results = 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');+ let text = rr.chunk_text;+ const titleTok = countEvidenceTokens(rr.title ?? '', tokenizer);+ const allowed = r.delivered.tokens + countEvidenceTokens(r.title ?? '', tokenizer) - titleTok;+ if (countEvidenceTokens(text, tokenizer) > allowed) text = sliceToTokenCount(text, allowed, tokenizer);+ const unmapped = [...new Set([...(r.delivered.unmapped_chunk_ids ?? []), ...r.delivered.match_spans.map(s => s.chunk_id)])];+ return {+ ...r,+ title: rr.title,+ chunk_text: text,+ delivered: {+ ...r.delivered,+ match_spans: [],+ tokens: countEvidenceTokens(text, tokenizer),+ ...(unmapped.length > 0 ? { unmapped_chunk_ids: unmapped } : {}),+ },+ };+ });++ 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 } : {}),+ },+ };+}++/**+ * Explicit `snippet_chars` precedence: cap delivered blocks at `cap`+ * characters (marker names the get_page recovery move), clip spans, mark+ * truncated and re-count. Non-mutating.+ */+export function capDeliveredSnippets<T extends SearchResult & { delivered?: DeliveredEvidence }>(+ results: T[],+ cap: number,+ delivery: DeliveryMeta,+): T[] {+ if (!Number.isFinite(cap) || cap <= 0) return results;+ let any = false;+ const tokenizer = delivery.tokenizer;+ 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);+ 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 unmapped = [...new Set([...(r.delivered.unmapped_chunk_ids ?? []), ...lost.filter(id => !spans.some(s => s.chunk_id === id))])];+ return {+ ...r,+ chunk_text: text,+ delivered: {+ ...r.delivered,+ match_spans: spans,+ tokens: countEvidenceTokens(text, tokenizer),+ truncated: true,+ ...(unmapped.length > 0 ? { unmapped_chunk_ids: unmapped } : {}),+ },+ };+ });+ if (!any) return results;+ if (!delivery.fallbacks.includes('snippet_cap')) delivery.fallbacks = [...delivery.fallbacks, 'snippet_cap'].sort();+ delivery.tokens_delivered = out.reduce((n, r) => n + (r.delivered?.tokens ?? 0), 0);+ return out;+}++/** Image-query branches never expand; the meta says so instead of staying silent. */+export function unsupportedDelivery(plan: EvidencePlan, reason: string): DeliveryMeta {+ return {+ requested_unit: plan.requestedUnit,+ applied_unit: 'chunk',+ return_window: plan.window,+ budget_tokens: plan.budgetTokens,+ budget_used: 0,+ tokens_delivered: 0,+ tokenizer: evidenceTokenizer(),+ coordinates: 'utf16',+ blocks: 0,+ dropped: 0,+ dropped_reasons: {},+ fallbacks: [reason],+ ...(plan.budgetClamped ? { budget_clamped: plan.budgetClamped } : {}),+ };+}++// ---------------------------------------------------------------------------+// Frozen-candidate interface (gbrain-evals E1/E3 parity)+// ---------------------------------------------------------------------------++export interface FrozenHit { source_id: string; slug: string; chunk_id: number }++export interface AssembleEvidenceInput {+ hits: FrozenHit[];+ return_unit: ReturnUnit;+ return_window?: number;+ budget_tokens?: number;+ detail?: 'low' | 'medium' | 'high';+ caller?: { remote?: boolean; sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean };+}++export interface AssembleEvidenceOutput {+ results: Array<SearchResult & { delivered?: DeliveredEvidence }>;+ delivery: DeliveryMeta | null;+ unresolved: number[];+}++export const MAX_ASSEMBLE_HITS = 50;++/**+ * Resolve frozen (source_id, slug, chunk_id) hits into search rows under the+ * caller's read scope (one query). Hits outside the scope, on deleted or+ * private-to-this-caller pages, or naming a chunk the page no longer holds+ * are unresolved. chunk_id 0 addresses the page's first chunk.+ */+export async function resolveFrozenHits(+ engine: BrainEngine,+ hits: FrozenHit[],+ scope: PageReadScope,+): Promise<{ rows: SearchResult[]; unresolved: number[] }> {+ if (hits.length === 0) return { rows: [], unresolved: [] };+ const params: unknown[] = [+ hits.map(h => String(h.source_id)),+ hits.map(h => String(h.slug)),+ hits.map(h => (Number.isInteger(h.chunk_id) ? h.chunk_id : -1)),+ hits.map((_, i) => i),+ ];+ const filter = pageReadFilter('p', scope, params, true);+ 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,+ 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+ LEFT JOIN content_chunks cc ON cc.page_id = p.id+ AND CASE WHEN h.chunk_id > 0 THEN cc.id = h.chunk_id ELSE cc.chunk_index = 0 END+ WHERE ${filter} AND ${currentTextProjectionFilter('p')} ${safe}`,+ params,+ );+ const byOrd = new Map<number, Record<string, unknown>>();+ for (const r of rows) byOrd.set(Number(r.ord), r);+ const out: SearchResult[] = [];+ const unresolved: number[] = [];+ 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({+ slug: String(r.slug),+ page_id: Number(r.page_id),+ source_id: String(r.source_id),+ title: String(r.title ?? ''),+ type: r.type as SearchResult['type'],+ chunk_text: r.chunk_text == null ? '' : String(r.chunk_text),+ chunk_source: (r.chunk_source ?? 'compiled_truth') as SearchResult['chunk_source'],+ chunk_id: r.chunk_id == null ? 0 : Number(r.chunk_id),+ chunk_index: r.chunk_index == null ? 0 : Number(r.chunk_index),+ score: 0,+ stale: false,+ });+ });+ return { rows: out, unresolved };+}++/**+ * The library entry gbrain-evals calls for a frozen candidate list: the+ * same plan resolution, assembler and output redaction the `query` op+ * applies, for these hits. `caller.remote` selects the trust class+ * (default trusted local).+ */+export async function assembleEvidenceForHits(engine: BrainEngine, input: AssembleEvidenceInput): Promise<AssembleEvidenceOutput> {+ if (!Array.isArray(input.hits)) throw new OperationError('invalid_params', 'hits must be an array of { source_id, slug, chunk_id }.');+ if (input.hits.length > MAX_ASSEMBLE_HITS) {+ throw new OperationError('invalid_params', `hits holds at most ${MAX_ASSEMBLE_HITS} entries (got ${input.hits.length}).`, 'Pass the top-ranked hits only.');+ }+ const remote = input.caller?.remote === true;+ const excludePrivate = input.caller?.excludePrivate ?? await resolveExcludePrivatePages(engine, remote ? true : false);+ const scope: DeliveryScope = {+ ...(input.caller?.sourceIds && input.caller.sourceIds.length > 0 ? { sourceIds: input.caller.sourceIds } : input.caller?.sourceId ? { sourceId: input.caller.sourceId } : {}),+ excludePrivate,+ requireSafeChunks: remote,+ ...(input.detail ? { detail: input.detail } : {}),+ };+ const plan = await resolveEvidencePlan(engine, {+ remote,+ returnUnit: input.return_unit ?? 'page',+ returnWindow: input.return_window,+ budget: input.budget_tokens,+ snippetChars: undefined,+ snippetCap: 0,+ op: 'assemble_evidence',+ });+ const { rows, unresolved } = await resolveFrozenHits(engine, input.hits, scope);+ if (!plan) {+ const out = redactRetrievalOutput(rows, {});+ return { results: out.results, delivery: null, unresolved };+ }+ 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 };+}++/** SHA-256 over the delivered evidence (see docs/evidence-delivery.md). */+export function evidenceFingerprint(results: Array<{ source_id?: string; slug: string; chunk_text: string; chunk_id: number; delivered?: { unit: string; chunk_ids: number[] } }>): string {+ const canon = results.map(r => [r.source_id ?? 'default', r.slug, r.chunk_text, r.delivered?.unit ?? 'chunk', r.delivered?.chunk_ids ?? [r.chunk_id]]);+ return createHash('sha256').update(JSON.stringify(canon)).digest('hex');+}++/**+ * Thin-client version skew: `return_unit` was requested but the response+ * carries no delivery meta (an older server ignored the param). Returns the+ * one-line warning, or null.+ */+export function deliveryVersionSkewWarning(+ opName: string,+ params: Record<string, unknown>,+ retrievalMeta: Record<string, unknown> | null | undefined,+ result: unknown,+): string | null {+ if (!['search', 'query', 'recall'].includes(opName)) return null;+ const unit = params.return_unit;+ if (typeof unit !== 'string' || unit === 'chunk') return null;+ const present = opName === 'recall'+ ? typeof result === 'object' && result !== null && 'delivery' in result+ : !!retrievalMeta && 'delivery' in retrievalMeta;+ if (present) return null;+ return `warning: the server ignored return_unit (evidence delivery needs gbrain server v${EVIDENCE_DELIVERY_MIN_SERVER_VERSION} or newer); results are plain chunks.`;+}diff --git a/src/core/search/explain-formatter.ts b/src/core/search/explain-formatter.tsindex 853ffda417..4940fcb884 100644--- a/src/core/search/explain-formatter.ts+++ b/src/core/search/explain-formatter.ts@@ -29,6 +29,7 @@*/import type { SearchResult, HybridSearchMeta } from '../types.ts';+import type { DeliveryMeta } from './evidence-delivery.ts';import type { AutocutDecision } from './autocut.ts';/**@@ -131,6 +132,14 @@ export function formatDegradedSummary(degraded: HybridSearchMeta['degraded'] | ureturn `degraded: ${degraded.map((d) => (d.reason ? `${d.stage} (${d.reason})` : d.stage)).join(', ')}`;}+/** One-line evidence-delivery summary for `--explain` (null when the stage did not run). */+export function formatDeliverySummary(delivery: DeliveryMeta | undefined): string | null {+ if (!delivery) return null;+ const fallbacks = delivery.fallbacks.length > 0 ? `; fallbacks: ${delivery.fallbacks.join(', ')}` : '';+ const dropped = delivery.dropped > 0 ? `; dropped ${delivery.dropped} (${Object.entries(delivery.dropped_reasons).map(([k, v]) => `${k}=${v}`).join(', ')})` : '';+ return `evidence: ${delivery.applied_unit} — ${delivery.blocks} blocks, ${delivery.budget_used}/${delivery.budget_tokens} tokens (${delivery.tokenizer})${dropped}${fallbacks}`;+}+/*** Format a full result list. Caller passes the SearchResult[] directly;* the formatter handles enumeration. Returns a single string (multi-line@@ -138,13 +147,13 @@ export function formatDegradedSummary(degraded: HybridSearchMeta['degraded'] | u*/export function formatResultsExplain(results: SearchResult[],- meta?: HybridSearchMeta,+ meta?: HybridSearchMeta & { delivery?: DeliveryMeta },): string {if (results.length === 0) return 'No results.\n';const body = results.map((r, i) => formatResultExplain(r, i + 1)).join('\n\n') + '\n';// v0.42.3.0 — prepend the autocut summary when meta carries a decision;// v0.48.2 — and the degraded summary when any stage was skipped.- const head = [formatAutocutSummary(meta?.autocut), formatDegradedSummary(meta?.degraded)]+ const head = [formatAutocutSummary(meta?.autocut), formatDegradedSummary(meta?.degraded), formatDeliverySummary(meta?.delivery)].filter((l): l is string => l !== null);return head.length > 0 ? `${head.join('\n')}\n\n${body}` : body;}diff --git a/src/core/search/hybrid/arms.ts b/src/core/search/hybrid/arms.tsindex 76f4b80a24..016b32ee9b 100644--- a/src/core/search/hybrid/arms.ts+++ b/src/core/search/hybrid/arms.ts@@ -25,6 +25,16 @@ export interface LexicalArms {exactLookupOpts: ExactLookupOpts;}+/**+ * SQLSTATE 22007 / 22008: a date bound the database could not cast. That is+ * the caller's input, never a degraded arm, so it surfaces instead of+ * becoming an empty result.+ */+function isDatetimeInputError(err: unknown): boolean {+ const code = (err as { code?: unknown } | null)?.code;+ return code === '22007' || code === '22008';+}+/** Keyword + title FTS arms, fetched concurrently (fail-open per arm, rethrow when both hit a dead database). */export async function runLexicalArms(req: HybridRequest): Promise<LexicalArms> {const { engine, query, opts, suggestions, searchOpts, identityTierOpts, degraded } = req;@@ -67,6 +77,7 @@ export async function runLexicalArms(req: HybridRequest): Promise<LexicalArms> {? [[], []]: await Promise.all([engine.searchKeyword(query, searchOpts).catch((err: unknown) => {+ if (isDatetimeInputError(err)) throw err;if (isDbAccessFailure(err)) keywordAccessError = err;pushDegraded(degraded, 'keyword_arm_failed', isTimeoutError(err) ? 'timeout' : 'provider_error');warnOncePerProcess(@@ -77,6 +88,7 @@ export async function runLexicalArms(req: HybridRequest): Promise<LexicalArms> {return [] as SearchResult[];}),engine.searchTitles(query, searchOpts).catch((err: unknown) => {+ if (isDatetimeInputError(err)) throw err;if (isDbAccessFailure(err)) titleAccessError = err;pushDegraded(degraded, 'title_arm_failed', isTimeoutError(err) ? 'timeout' : 'provider_error');warnOncePerProcess(diff --git a/src/core/think/gather.ts b/src/core/think/gather.tsindex 4855f5ab66..8a4c9a61a2 100644--- a/src/core/think/gather.ts+++ b/src/core/think/gather.ts@@ -606,6 +606,7 @@ export function renderPagesBlock(pages: SearchResult[],excerptLen = 600,query = '',+ opts: { verbatim?: boolean } = {},): string {return pages.map((p, idx) => {const page = p as unknown as {@@ -619,6 +620,9 @@ export function renderPagesBlock(const title = String(page.title ?? '');const slugIdentity = slug.split('/').pop()?.replace(/[-_]/g, ' ') ?? '';const content = String(page.chunk_text ?? page.compiled_truth ?? page.snippet ?? '');+ // Evidence delivery: the block was already budgeted and cut around its+ // hits; render it whole (capped only by excerptLen).+ if (opts.verbatim) return `<page slug="${slug}" rank="${idx + 1}">\n${content.slice(0, excerptLen)}\n</page>`;const excerpt = selectRelevantExcerptDetailed(content,query,diff --git a/src/core/think/index.ts b/src/core/think/index.tsindex a3be2dc62c..48cbd2fef6 100644--- a/src/core/think/index.ts+++ b/src/core/think/index.ts@@ -33,6 +33,7 @@ import { normalizeModelId } from '../model-id.ts';import { hasAnthropicKey } from '../ai/anthropic-key.ts';import { parseTemporalWindow } from './temporal-window.ts';import { resolveExcludePrivatePages } from '../search/private-visibility.ts';+import { deliverEvidence, resolveEvidencePlan, EVIDENCE_BLOCK_CHAR_CAP, THINK_RETURN_UNIT_CONFIG_KEY, type DeliveryMeta } from '../search/evidence-delivery.ts';/** Anthropic Messages client interface — same shape used by subagent.ts so test stubs can be shared. */export interface ThinkLLMClient {@@ -201,6 +202,8 @@ export interface ThinkResult {* The synthesize verb maps this to its frozen `cost` block.*/usage?: { input_tokens: number; output_tokens: number } | null;+ /** Evidence delivery meta, present only when think.return_unit is not chunk. */+ evidence_delivery?: import('../search/evidence-delivery.ts').DeliveryMeta;/** Only set when --save was true and the caller persisted a synthesis page. */savedSlug?: string;/** Diagnostics for `--explain` callers (CLI surface for v0.29). */@@ -473,6 +476,25 @@ async function persistCitations(return { inserted, warnings };}+/**+ * Render the <pages> block. Evidence delivery (think.return_unit, default+ * chunk) replaces the gathered pages with budgeted delivered blocks, which+ * the renderer passes through whole instead of cutting its own excerpts.+ */+async function renderThinkPages(engine: BrainEngine, opts: RunThinkOpts, pages: SearchResult[]): Promise<{ pagesBlock: string; evidenceDelivery?: DeliveryMeta }> {+ const plan = await resolveEvidencePlan(engine, {+ remote: opts.remote, returnUnit: undefined, returnWindow: undefined, budget: undefined,+ snippetChars: undefined, snippetCap: 0, configKey: THINK_RETURN_UNIT_CONFIG_KEY, op: 'think',+ });+ if (!plan) return { pagesBlock: renderPagesBlock(pages, pagesBlockExcerptLen(pages.length), opts.question) };+ const delivered = await deliverEvidence(engine, pages, plan, {+ ...(opts.allowedSources !== undefined && opts.allowedSources.length > 0 ? { sourceIds: opts.allowedSources } : opts.sourceId !== undefined ? { sourceId: opts.sourceId } : {}),+ excludePrivate: opts.excludePrivate ?? await resolveExcludePrivatePages(engine, opts.remote),+ requireSafeChunks: opts.remote !== false,+ });+ return { pagesBlock: renderPagesBlock(delivered.results, EVIDENCE_BLOCK_CHAR_CAP, opts.question, { verbatim: true }), evidenceDelivery: delivered.delivery };+}+/*** Run the think pipeline. Returns a ThinkResult — caller decides whether* to print, persist as synthesis page, or surface as MCP response.@@ -545,7 +567,7 @@ export async function runThink(// budget-aware — 600 chars is the FLOOR (a big gather never collapses each// page below it) and a small gather spreads the block budget into much// larger, often complete, per-page windows.- const pagesBlock = renderPagesBlock(gather.pages, pagesBlockExcerptLen(gather.pages.length), opts.question);+ const { pagesBlock, evidenceDelivery } = await renderThinkPages(engine, opts, gather.pages);const takesForPrompt = gather.takes.map(takesHitToTakeForPrompt);const { rendered: takesBlock, sanitizedCount } = renderTakesBlock(takesForPrompt);if (sanitizedCount > 0) {@@ -918,7 +940,7 @@ export async function runThink(synthesisOk: synthesisOk && response.answer.trim().length > 0,synthesis_status: synthesisStatus,...(extractive ? { extractive } : {}),- usage,+ usage, ...(evidenceDelivery ? { evidence_delivery: evidenceDelivery } : {}),diagnostics: {pagesFromHybrid: gather.diagnostics.pagesFromHybrid,takesFromKeyword: gather.diagnostics.takesFromKeyword,diff --git a/src/core/types.ts b/src/core/types.tsindex 9444ee6aa7..a4ba0060de 100644--- a/src/core/types.ts+++ b/src/core/types.ts@@ -1036,6 +1036,8 @@ export interface SearchResult {* incident's duplicate-stub class.*/create_safety?: import('./search/evidence.ts').CreateSafety;+ /** Evidence delivery (`return_unit`): present only when a non-chunk unit applied. */+ delivered?: import('./search/evidence-delivery.ts').DeliveredEvidence;}/**diff --git a/src/core/verbs/entity-card.ts b/src/core/verbs/entity-card.tsindex c481190583..a37a9abdb3 100644--- a/src/core/verbs/entity-card.ts+++ b/src/core/verbs/entity-card.ts@@ -219,7 +219,7 @@ export async function buildEntityCard(create_safety: 'exists',}));- const card = await assembleCard(engine, sourceId, best.row, opts.remote);+ const card = await assembleCard(engine, sourceId, best.row, opts.remote, excludePrivate);return {found: true,card,@@ -237,9 +237,14 @@ async function assembleCard(sourceId: string,row: CardPageRow,remote: boolean,+ excludePrivate: boolean,): Promise<EntityCard> {const pageSlug = row.slug;const visibility = remote ? (['world'] as ('private' | 'world')[]) : undefined;+ const { privatePagesFilterFragment, privateLinkOriginFilterFragment } = await import('../search/private-visibility.ts');+ const inboundPrivacy = excludePrivate+ ? ` AND ${privatePagesFilterFragment('f')} AND ${privateLinkOriginFilterFragment('l')}`+ : '';// Parallel depth-1 reads — every arm individually fail-soft so a partial// brain (no aliases, no timeline) still returns a card.@@ -251,7 +256,10 @@ async function assembleCard(// a both-sides-scoped query here (f.source_id = t.source_id = this source),// mentions excluded (matching the backlink-count convention). Outgoing edges// (getLinks) are the entity's OWN declared links — from-side scoped — so they- // stay as-is.+ // stay as-is. The referrer must also be live and, for an untrusted caller,+ // readable: the same private-page and private-origin predicates get_backlinks+ // applies, so a private or derived page never surfaces its slug, its+ // links.context sentence, or a count.const [aka, outLinks, inEdges, backlinkCount, timeline, facts, activeFactCount] = await Promise.all([engine.executeRaw<{ alias_norm: string }>(@@ -260,15 +268,15 @@ async function assembleCard().then(rs => rs.map(r => r.alias_norm)).catch(() => [] as string[]),- engine.getLinks(pageSlug, { sourceId }).catch(() => []),+ engine.getLinks(pageSlug, { sourceId, excludePrivate }).catch(() => []),engine.executeRaw<{ from_slug: string; link_type: string; context: string | null }>(`SELECT f.slug AS from_slug, l.link_type, l.contextFROM links lJOIN pages f ON f.id = l.from_page_idJOIN pages t ON t.id = l.to_page_id- WHERE t.slug = $1 AND t.source_id = $2 AND f.source_id = $2- AND COALESCE(l.link_source, '') <> 'mentions'`,+ WHERE t.slug = $1 AND t.source_id = $2 AND f.source_id = $2 AND f.deleted_at IS NULL+ AND COALESCE(l.link_source, '') <> 'mentions'${inboundPrivacy}`,[pageSlug, sourceId],).catch(() => [] as Array<{ from_slug: string; link_type: string; context: string | null }>),@@ -278,13 +286,13 @@ async function assembleCard(FROM links lJOIN pages f ON f.id = l.from_page_idJOIN pages t ON t.id = l.to_page_id- WHERE t.slug = $1 AND t.source_id = $2 AND f.source_id = $2- AND COALESCE(l.link_source, '') <> 'mentions'`,+ WHERE t.slug = $1 AND t.source_id = $2 AND f.source_id = $2 AND f.deleted_at IS NULL+ AND COALESCE(l.link_source, '') <> 'mentions'${inboundPrivacy}`,[pageSlug, sourceId],).then(rs => Number(rs[0]?.n ?? 0)).catch(() => 0),- engine.getTimeline(pageSlug, { limit: 5, sourceId }).catch(() => []),+ engine.getTimeline(pageSlug, { limit: 5, sourceId, excludePrivate }).catch(() => []),engine.listFactsByEntity(sourceId, pageSlug, {activeOnly: true,diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.mdindex 017e301294..4b0a8f8640 100644--- a/templates/bootstrap/template-repo/README.md+++ b/templates/bootstrap/template-repo/README.md@@ -1,6 +1,6 @@# gbrain agent workspace — template-<!-- gbrain-template-stamp: 0.60.12.0 -->+<!-- gbrain-template-stamp: 0.60.13.0 -->This repository is the **"Use this template"** distribution artifact for a[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the samediff --git a/test/chronicle-last-seen-matching.test.ts b/test/chronicle-last-seen-matching.test.tsnew file mode 100644index 0000000000..a022db9288--- /dev/null+++ b/test/chronicle-last-seen-matching.test.ts@@ -0,0 +1,80 @@+/**+ * chronicle_last_seen matches an event's `who` entries by exact slug (or a+ * wikilink to exactly that slug), never by substring: a slug that is a prefix+ * of another slug does not inherit its sightings, and `_` in a slug is not a+ * wildcard. The newest sighting is picked by the calendar day the chronicle+ * projected (chronicle.tz local day), so a late-evening event never outranks+ * a row dated the next day. (gbrain-evals N3 temporal-asof, bugs 2 and 3.)+ *+ * Synthetic data only.+ */+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { operations } from '../src/core/operations.ts';+import { runChronicleExtract } from '../src/core/chronicle/extract-events.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});++beforeEach(async () => {+ await resetPgliteState(engine);+});++afterAll(async () => {+ await engine.disconnect();+});++const op = (name: string, p: object) => {+ const ctx = { engine, config: { engine: 'pglite', database_path: ':memory:' }, logger: console, dryRun: false, remote: false, sourceId: 'default' } as any;+ return operations.find(o => o.name === name)!.handler(ctx, p as any);+};+const person = (slug: string) => op('put_page', { slug, content: `---\ntype: person\ntitle: ${slug}\n---\nPerson.\n` });+async function meeting(slug: string, date: string, who: string[], when: string, tz = 'UTC') {+ await op('put_page', { slug, content: `---\ntype: meeting\ntitle: Meeting\ndate: ${date}\n---\n` + 'Notes. '.repeat(20) });+ await runChronicleExtract(engine, { slug, tz, judge: async () => ({ events: [{ when, who, what: `Meeting ${slug}`, kind: 'meeting' }] }) });+}++describe('chronicle_last_seen who matching', () => {+ test('a slug that is a prefix of another slug does not inherit its sightings', async () => {+ await person('people/kim-example');+ await person('people/kim-example-2');+ await meeting('meetings/2024-05-01-sync', '2024-05-01', ['people/kim-example-2'], '2024-05-01');+ const res = await op('chronicle_last_seen', { entity: 'people/kim-example', asof: '2024-06-01' }) as any;+ expect(res.last_date).toBeNull();+ const other = await op('chronicle_last_seen', { entity: 'people/kim-example-2', asof: '2024-06-01' }) as any;+ expect(other.last_date).toBe('2024-05-01');+ });++ test('underscore in a slug is literal, not a wildcard', async () => {+ await person('people/a_b-example');+ await meeting('meetings/2024-05-02-sync', '2024-05-02', ['people/axb-example'], '2024-05-02');+ const res = await op('chronicle_last_seen', { entity: 'people/a_b-example', asof: '2024-06-01' }) as any;+ expect(res.last_date).toBeNull();+ });++ test('a wikilink to exactly the slug still counts; a wikilink to a longer slug does not', async () => {+ await person('people/lee-example');+ await meeting('meetings/2022-09-04-sync', '2022-09-04', ['[[people/lee-example|Lee]]'], '2022-09-04');+ await meeting('meetings/2025-04-05-sync', '2025-04-05', ['[[people/lee-example-2]]'], '2025-04-05');+ const res = await op('chronicle_last_seen', { entity: 'people/lee-example', asof: '2026-06-30' }) as any;+ expect(res.last_date).toBe('2022-09-04');+ });+});++describe('chronicle_last_seen day ordering', () => {+ test('a late-evening event in a non-UTC chronicle zone does not outrank the next local day', async () => {+ await engine.setConfig('chronicle.tz', 'America/New_York');+ await person('people/dave-example');+ await meeting('meetings/2024-05-01-call', '2024-05-01', ['people/dave-example'], '2024-05-01T23:30:00-04:00', 'America/New_York');+ await op('add_timeline_entry', { slug: 'people/dave-example', date: '2024-05-02', summary: 'spoke at startup-1' });+ const res = await op('chronicle_last_seen', { entity: 'people/dave-example', asof: '2024-05-02' }) as any;+ expect(res.last_date).toBe('2024-05-02');+ expect(res.days_ago).toBe(0);+ });+});diff --git a/test/config-search-registry.test.ts b/test/config-search-registry.test.tsindex f65998538a..6be3c76b9b 100644--- a/test/config-search-registry.test.ts+++ b/test/config-search-registry.test.ts@@ -34,6 +34,10 @@ const DIRECTLY_READ_SINGLETONS = ['search.adaptive_return_min_keep','search.crag_escalation', // ops/search.ts'search.crag_think', // ops/search.ts+ 'search.return_unit', // search/evidence-delivery.ts+ 'search.return_window',+ 'search.return_budget_default',+ 'search.return_budget_max_remote',];describe('KNOWN_CONFIG_KEYS search.* rows mirror what the code reads (#4605)', () => {diff --git a/test/e2e/chronicle-last-seen-postgres.test.ts b/test/e2e/chronicle-last-seen-postgres.test.tsindex 1841da4bb4..feb017df09 100644--- a/test/e2e/chronicle-last-seen-postgres.test.ts+++ b/test/e2e/chronicle-last-seen-postgres.test.ts@@ -59,6 +59,22 @@ d('getLastSeen (live Postgres) bounds to <= asof/today', () => {// Future event: a scheduled Q3 launch on 2026-08-01.ids.fut = await insertPage({ slug: 'life/events/2026-08-01-fut', type: 'event', effectiveDate: '2026-08-01T10:00:00Z', frontmatter: '{"event":{"who":["people/sarah-chen"],"kind":"event"}}' });await insertProjection(ids.meeting, ids.fut, '2026-08-01', 'Planned Q3 launch');+ // Exact who matching: kim-example-2's sighting must not count for the+ // kim-example prefix, nor axb-example's for the a_b-example underscore.+ await insertPage({ slug: 'people/kim-example', type: 'person' });+ ids.kim2 = await insertPage({ slug: 'life/events/2026-06-19-kim2', type: 'event', effectiveDate: '2026-06-19T10:00:00Z', frontmatter: '{"event":{"who":["people/kim-example-2","people/axb-example"],"kind":"meeting"}}' });+ await insertProjection(ids.meeting, ids.kim2, '2026-06-19', 'Sync with kim 2');+ ids.kimLink = await insertPage({ slug: 'life/events/2026-06-10-kim', type: 'event', effectiveDate: '2026-06-10T10:00:00Z', frontmatter: '{"event":{"who":["[[people/kim-example|Kim]]"],"kind":"meeting"}}' });+ await insertProjection(ids.meeting, ids.kimLink, '2026-06-10', 'Sync with kim');+ // Day ordering: a 23:30 New York event projected on 06-21 (03:30 UTC on+ // 06-22) must not outrank dave's own row dated 06-22.+ ids.dave = await insertPage({ slug: 'people/dave-example', type: 'person' });+ ids.late = await insertPage({ slug: 'life/events/2026-06-21-late', type: 'event', effectiveDate: '2026-06-22T03:30:00Z', frontmatter: '{"event":{"who":["people/dave-example"],"kind":"call"}}' });+ await insertProjection(ids.meeting, ids.late, '2026-06-21', 'Late call');+ await engine.executeRaw(+ `INSERT INTO timeline_entries (page_id, date, source, summary, detail) VALUES ($1, '2026-06-22'::date, 'manual', 'spoke at startup-1', '')`,+ [ids.dave],+ );});afterAll(async () => { await teardownDB(); });@@ -74,4 +90,17 @@ d('getLastSeen (live Postgres) bounds to <= asof/today', () => {expect(later.last_date).toBe('2026-08-01');expect(later.days_ago).toBe(1);});++ test('who matches the exact slug or a wikilink to it, never a substring or LIKE wildcard', async () => {+ const kim = await engine.getLastSeen('people/kim-example', { asof: '2026-06-25', sourceId: 'default' });+ expect(kim.last_date).toBe('2026-06-10');+ const underscore = await engine.getLastSeen('people/a_b-example', { asof: '2026-06-25', sourceId: 'default' });+ expect(underscore.last_date).toBeNull();+ });++ test('the newest projected day wins over a later instant on the previous local day', async () => {+ const dave = await engine.getLastSeen('people/dave-example', { asof: '2026-06-22', sourceId: 'default' });+ expect(dave.last_date).toBe('2026-06-22');+ expect(dave.days_ago).toBe(0);+ });});diff --git a/test/e2e/evidence-delivery-leak.test.ts b/test/e2e/evidence-delivery-leak.test.tsnew file mode 100644index 0000000000..a8834f8569--- /dev/null+++ b/test/e2e/evidence-delivery-leak.test.ts@@ -0,0 +1,362 @@+/**+ * Evidence delivery leak canaries — the release gate for `return_unit`+ * (plan amendment 2): delivered evidence never exceeds what `get_page`+ * returns to the same caller, on PGLite and Postgres, through local ops,+ * MCP stdio and MCP HTTP, with public presence controls proving the+ * expansion really delivered neighbor and whole-page text.+ *+ * Canaries: private fact rows, takes (even for trusted local callers:+ * the body is sanitized whole for every caller), withdrawn fact rows, a malformed+ * protected tail, timeline fact rows, a `visibility: private` page, a derived+ * atom (private by default), and the same slug in an ungranted source. The+ * mid-flight cases re-authorize stale hits: grant revocation, a page turning+ * private, and an edit between ranking and expansion.+ *+ * Postgres arm runs when DATABASE_URL is set.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { createHash, randomBytes } from 'node:crypto';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { createServer } from 'node:net';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { spawn, type ChildProcess } from 'node:child_process';+import { Client } from '@modelcontextprotocol/sdk/client/index.js';+import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';+import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import type { BrainEngine } from '../../src/core/engine.ts';+import type { GBrainConfig } from '../../src/core/config.ts';+import type { SearchResult } from '../../src/core/types.ts';+import { configureGateway, resetGateway } from '../../src/core/ai/gateway.ts';+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 { keylessBrainEnv } from '../helpers/provider-env.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { createManagedFixtureSource, withManagedFixtureWrite } from '../helpers/managed-e2e-fixture-write.ts';+import { fixtureDiagnostic, toolDiagnostic } from '../helpers/fixture-diagnostics.ts';+import { withEnv } from '../helpers/with-env.ts';++const BOUND = 'evd-bound';+const FOREIGN = 'evd-foreign';+const UNITS = ['window', 'section', 'page', 'auto'] as const;++// Public presence controls (must appear in page-unit evidence).+const PRESENT = ['PUBLICMARKALPHA', 'PUBLICMARKOMEGA', 'WORLDFACTKESTREL', 'TIMELINEPUBLICWREN', 'TIMELINEWORLDFINCH'];+// Protected for remote callers.+const REMOTE_CANARIES = ['PRIVATEPAGECANARY', 'ATOMCANARY'];+// Protected for every caller (whole-body sanitizing) plus other-source text.+const ALWAYS_CANARIES = ['FACTCANARYPRIVATE', 'TAKECANARYPRIVATE', 'WITHDRAWNCANARY', 'MALFORMEDTAILCANARY', 'TIMELINEFACTCANARY', 'FOREIGNSOURCECANARY', 'EDITSECRETCANARY'];++const filler = (n: number) => Array.from({ length: n }, (_, i) => `Heron field notes paragraph ${i} describing ordinary public observations of the marsh and the weather that day.`).join('\n\n');++function heronPage(): string {+ const facts = renderFactsTable([+ { rowNum: 1, claim: 'WORLDFACTKESTREL heron nests near the pier', kind: 'fact', confidence: 1, visibility: 'world', notability: 'high', active: true },+ { rowNum: 2, claim: 'FACTCANARYPRIVATE heron owner home address', kind: 'fact', confidence: 1, visibility: 'private', notability: 'high', active: true },+ { rowNum: 3, claim: 'WITHDRAWNCANARY heron old claim', kind: 'fact', confidence: 1, visibility: 'world', notability: 'low', active: false, forgotten: true, context: 'forgotten: user asked to remove' },+ ]);+ const timelineFacts = renderFactsTable([+ { rowNum: 1, claim: 'TIMELINEWORLDFINCH heron migration date', kind: 'fact', confidence: 1, visibility: 'world', notability: 'high', active: true },+ { rowNum: 2, claim: 'TIMELINEFACTCANARY heron private timeline fact', kind: 'fact', confidence: 1, visibility: 'private', notability: 'high', active: true },+ ]);+ return `---\ntitle: heron\ntype: note\n---\n\nheron PUBLICMARKALPHA introduction.\n\n## Field notes\n\n${filler(30)}\n\n${facts}\n\n${TAKES_FENCE_BEGIN}\n| # | claim | kind | who | weight | since | source |\n|---|-------|------|-----|--------|-------|--------|\n| 1 | TAKECANARYPRIVATE heron opinion | take | owner-example | 0.8 | | |\n${TAKES_FENCE_END}\n\n## Closing\n\n${filler(8)}\n\nheron PUBLICMARKOMEGA closing line.\n\n<!-- timeline -->\n\n- 2026-01-01 heron TIMELINEPUBLICWREN sighting\n\n${timelineFacts}\n\n${TAKES_FENCE_BEGIN}\nMALFORMEDTAILCANARY heron unterminated protected tail\n`;+}++const FIXTURES: Array<[slug: string, source: string, body: string]> = [+ ['notes/heron', BOUND, heronPage()],+ ['notes/heron-private', BOUND, `---\ntitle: heron private\ntype: note\nvisibility: private\n---\n\nheron PRIVATEPAGECANARY private memo.\n`],+ ['atoms/heron-atom', BOUND, `---\ntitle: heron atom\ntype: atom\nsource_slug: notes/heron\n---\n\nheron ATOMCANARY derived atom.\n`],+ ['notes/heron-edit', BOUND, `---\ntitle: heron edit\ntype: note\n---\n\nheron editable page. EDITSECRETCANARY line to be removed.\n\n${filler(6)}\n`],+ ['notes/heron', FOREIGN, `---\ntitle: heron\ntype: note\n---\n\nheron FOREIGNSOURCECANARY other source page.\n\n${filler(4)}\n`],+];++const backends = process.env.DATABASE_URL ? ['pglite', 'postgres'] as const : ['pglite'] as const;++async function unusedPort(): Promise<number> {+ const server = createServer();+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));+ const port = (server.address() as { port: number }).port;+ await new Promise<void>((resolve, reject) => server.close(error => error ? reject(error) : resolve()));+ return port;+}++async function stop(child: ChildProcess): Promise<void> {+ if (child.exitCode !== null || child.signalCode !== null) return;+ await new Promise<void>(resolve => {+ const deadline = setTimeout(() => child.kill('SIGKILL'), 5_000);+ child.once('exit', () => { clearTimeout(deadline); resolve(); });+ child.kill('SIGTERM');+ });+}++function assertNoLeak(label: string, payload: unknown, canaries: string[]): void {+ const text = JSON.stringify(payload);+ for (const c of canaries) expect(text.includes(c), `${label} leaked ${c}`).toBe(false);+}++function assertPresent(label: string, payload: unknown): void {+ const text = JSON.stringify(payload);+ for (const c of PRESENT) expect(text.includes(c), `${label} missing presence control ${c}`).toBe(true);+}++for (const backend of backends) describe(`evidence delivery leak canaries (${backend})`, () => {+ let home: string;+ let env: Record<string, string>;+ let engine: BrainEngine;+ let config: GBrainConfig;+ let cleanupPostgres: (() => Promise<void>) | undefined;+ let provider: ReturnType<typeof Bun.serve>;+ const token = `gbrain_${randomBytes(32).toString('hex')}`;++ async function mutate<T>(run: () => Promise<T>): Promise<T> {+ await engine.connect(config);+ try { return await run(); } finally { await engine.disconnect(); }+ }++ async function importPage(slug: string, source: string, body: string) {+ await withEnv({ GBRAIN_HOME: home }, async () => {+ await importFromContent(engine, slug, body, {+ sourceId: source, noEmbed: false,+ prepare: async prepared => {+ await withManagedFixtureWrite(engine, [source], tx => prepared.apply(tx));+ return prepared.result;+ },+ });+ });+ }++ function ctxOf(remote: boolean, meta?: { value?: Record<string, unknown> }): OperationContext {+ return {+ engine: engine as never, config: config as never, logger: console as never, dryRun: false, remote, sourceId: BOUND,+ emitResponseMeta: (key: string, value: unknown) => { if (key === 'retrieval' && meta) meta.value = value as Record<string, unknown>; },+ } as OperationContext;+ }++ async function withStdio(run: (client: Client) => Promise<void>) {+ const transport = new StdioClientTransport({+ command: 'bun', args: ['--no-env-file', 'run', 'src/cli.ts', 'serve'],+ cwd: process.cwd(), env: { ...env, GBRAIN_SOURCE: BOUND }, stderr: 'pipe',+ });+ let stderr = '';+ transport.stderr?.on('data', data => { stderr = (stderr + String(data)).slice(-6000); });+ const client = new Client({ name: 'evidence-leak', version: '1' });+ try {+ await client.connect(transport);+ await run(client);+ } catch (error) {+ console.error(fixtureDiagnostic('stdio fixture', stderr, [token]));+ throw error;+ } finally {+ await client.close();+ await transport.close();+ }+ }++ async function withHttp(run: (client: Client) => Promise<void>) {+ const port = await unusedPort();+ const base = `http://127.0.0.1:${port}`;+ const child = spawn('bun', ['--no-env-file', 'run', 'src/cli.ts', 'serve', '--http',+ '--bind', '127.0.0.1', '--port', String(port), '--public-url', base, '--suppress-bootstrap-token'],+ { cwd: process.cwd(), env, stdio: ['ignore', 'ignore', 'pipe'] });+ let stderr = '';+ child.stderr?.on('data', data => { stderr = (stderr + String(data)).slice(-6000); });+ const client = new Client({ name: 'evidence-leak-http', version: '1' });+ try {+ let ready = false;+ for (let i = 0; i < 120; i++) {+ try { ready = (await fetch(`${base}/health`, { signal: AbortSignal.timeout(500) })).ok; } catch {}+ if (ready || child.exitCode !== null) break;+ await Bun.sleep(250);+ }+ expect(ready, fixtureDiagnostic('HTTP startup', stderr, [token])).toBe(true);+ await client.connect(new StreamableHTTPClientTransport(new URL(`${base}/mcp`), {+ requestInit: { headers: { Authorization: `Bearer ${token}` } },+ }));+ await run(client);+ } catch (error) {+ console.error(fixtureDiagnostic('HTTP fixture', stderr, [token]));+ throw error;+ } finally {+ await client.close();+ await stop(child);+ }+ }++ beforeAll(async () => {+ home = mkdtempSync(join(tmpdir(), 'gbrain-evidence-leak-'));+ provider = Bun.serve({ hostname: '127.0.0.1', port: 0, async fetch(request) {+ if (request.method === 'GET') return Response.json({ data: [{ id: 'text-embedding-3-small' }] });+ const body = await request.json() as { input: string | string[] };+ const input = Array.isArray(body.input) ? body.input : [body.input];+ return Response.json({ object: 'list', model: 'text-embedding-3-small', data: input.map((text, index) => {+ const embedding = Array(1536).fill(0);+ embedding[text.toLowerCase().includes('heron') ? 0 : 1] = 1;+ return { object: 'embedding', index, embedding };+ }), usage: { prompt_tokens: 1, total_tokens: 1 } });+ } });+ env = keylessBrainEnv(process.env, home, {+ DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined, GBRAIN_ENGINE: undefined,+ GBRAIN_SCHEMA_PACK: 'gbrain-base-v2', GBRAIN_SWEEP: '0',+ GBRAIN_SKIP_STARTUP_HOOKS: '1', GBRAIN_NO_RETRY_CONNECT: '1',+ OPENAI_API_KEY: 'synthetic-fixture', OPENAI_BASE_URL: `http://127.0.0.1:${provider.port}/v1`,+ });+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: 1536, env });+ if (backend === 'postgres') {+ const isolated = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ engine = isolated.engine;+ cleanupPostgres = isolated.close;+ config = { engine: 'postgres', database_url: isolated.databaseUrl };+ } else {+ config = { engine: 'pglite', database_path: join(home, 'db') };+ engine = new PGLiteEngine();+ await engine.connect(config);+ await engine.initSchema();+ }+ config = { ...config, embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: 1536 };+ mkdirSync(join(home, '.gbrain'));+ writeFileSync(join(home, '.gbrain/config.json'), JSON.stringify(config));+ await createManagedFixtureSource(engine, BOUND, { federated: false });+ await createManagedFixtureSource(engine, FOREIGN, { federated: false });+ for (const [slug, source, body] of FIXTURES) await importPage(slug, source, body);+ await engine.executeRaw(`INSERT INTO access_tokens (name, token_hash, permissions, scopes) VALUES ($1, $2, $3::text::jsonb, $4::text[])`,+ ['evidence-read', createHash('sha256').update(token).digest('hex'), JSON.stringify({ source_id: BOUND, takes_holders: ['world'] }), ['read']]);+ const rows = await engine.executeRaw<{ slug: string; ready: boolean; chunker_version: number }>(+ 'SELECT slug, knowledge_revision = text_projection_revision AS ready, chunker_version FROM pages');+ expect(rows.every(row => row.ready && row.chunker_version >= 4), JSON.stringify(rows)).toBe(true);+ // The canaries really are in the stored bodies, and get_page shows the+ // presence controls to a remote caller (the invariant's reference).+ const stored = await engine.executeRaw<{ body: string }>(`SELECT compiled_truth || timeline AS body FROM pages WHERE slug = 'notes/heron' AND source_id = $1`, [BOUND]);+ for (const c of ['FACTCANARYPRIVATE', 'TAKECANARYPRIVATE', 'TIMELINEFACTCANARY', 'MALFORMEDTAILCANARY']) expect(stored[0].body).toContain(c);+ const page = await operations.find(o => o.name === 'get_page')!.handler(ctxOf(true), { slug: 'notes/heron' });+ for (const c of PRESENT) expect(JSON.stringify(page)).toContain(c);+ await engine.disconnect();+ }, 180_000);++ afterAll(async () => {+ await engine?.disconnect().catch(() => {});+ await cleanupPostgres?.();+ provider?.stop(true);+ resetGateway();+ if (home) rmSync(home, { recursive: true, force: true });+ });++ test('local ops (trusted and untrusted) deliver presence controls and no canaries', async () => {+ await mutate(async () => {+ for (const remote of [false, true]) {+ const canaries = remote ? [...ALWAYS_CANARIES.filter(c => c !== 'EDITSECRETCANARY'), ...REMOTE_CANARIES] : ALWAYS_CANARIES.filter(c => c !== 'EDITSECRETCANARY');+ for (const unit of UNITS) {+ const meta: { value?: Record<string, unknown> } = {};+ const search = await operations.find(o => o.name === 'search')!.handler(ctxOf(remote, meta), { query: 'heron', return_unit: unit, token_budget: 32000, source_id: BOUND, limit: 50 });+ assertNoLeak(`local remote=${remote} search ${unit}`, search, canaries);+ expect(meta.value?.delivery, `delivery meta for ${unit}`).toBeDefined();+ if (unit === 'page') assertPresent(`local remote=${remote} search page`, search);+ const query = await operations.find(o => o.name === 'query')!.handler(ctxOf(remote), { query: 'heron', return_unit: unit, token_budget: 32000, source_id: BOUND, expand: false });+ assertNoLeak(`local remote=${remote} query ${unit}`, query, canaries);+ const recall = await operations.find(o => o.name === 'recall')!.handler(ctxOf(remote), { query: 'heron', return_unit: unit, budget_tokens: 32000, source_id: BOUND });+ assertNoLeak(`local remote=${remote} recall ${unit}`, recall, canaries);+ const hits = (search as SearchResult[]).map(h => ({ source_id: h.source_id, slug: h.slug, chunk_id: h.chunk_id }));+ const assembled = await operations.find(o => o.name === 'assemble_evidence')!.handler(ctxOf(remote), {+ hits: [...hits, { source_id: FOREIGN, slug: 'notes/heron', chunk_id: 0 }], return_unit: unit, token_budget: 32000,+ });+ assertNoLeak(`local remote=${remote} assemble ${unit}`, assembled, remote ? canaries : canaries.filter(c => c !== 'FOREIGNSOURCECANARY'));+ }+ if (!remote) {+ const priv = await operations.find(o => o.name === 'search')!.handler(ctxOf(false), { query: 'heron PRIVATEPAGECANARY', return_unit: 'page', source_id: BOUND });+ expect(JSON.stringify(priv)).toContain('PRIVATEPAGECANARY');+ }+ }+ });+ }, 120_000);++ test('delivered text is a subset of get_page for the same caller', async () => {+ await mutate(async () => {+ for (const remote of [false, true]) {+ const rows = await operations.find(o => o.name === 'search')!.handler(ctxOf(remote), { query: 'heron', return_unit: 'page', token_budget: 32000, source_id: BOUND, limit: 50 }) as SearchResult[];+ expect(rows.length).toBeGreaterThan(0);+ for (const row of rows) {+ const page = await operations.find(o => o.name === 'get_page')!.handler(ctxOf(remote), { slug: row.slug, source_id: row.source_id, include_content: true }) as { content: string };+ const reference = page.content;+ for (const line of row.chunk_text.split('\n')) {+ const t = line.trim();+ if (!t || t === '[…]') continue;+ expect(reference.includes(t), `${row.slug} remote=${remote}: delivered line not in get_page: ${t.slice(0, 80)}`).toBe(true);+ }+ }+ }+ });+ }, 60_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) => {+ for (const unit of UNITS) {+ for (const [name, args] of [+ ['search', { query: 'heron', return_unit: unit, token_budget: 32000, limit: 50 }],+ ['query', { query: 'heron', return_unit: unit, token_budget: 32000, expand: false }],+ ['recall', { query: 'heron', return_unit: unit, budget_tokens: 32000 }],+ ] as const) {+ const result = await client.callTool({ name, arguments: args });+ expect(result.isError, toolDiagnostic(name, result)).not.toBe(true);+ assertNoLeak(`${name} ${unit}`, result, canaries);+ if (name === 'search') {+ expect((result._meta?.retrieval as { delivery?: unknown })?.delivery).toBeDefined();+ if (unit === 'page') assertPresent(`${name} page`, result);+ }+ }+ const rows = JSON.parse(((await client.callTool({ name: 'search', arguments: { query: 'heron', limit: 50 } })).content as Array<{ text: string }>)[0].text) as SearchResult[];+ const assembled = await client.callTool({ name: 'assemble_evidence', arguments: {+ hits: [...rows.map(r => ({ source_id: r.source_id, slug: r.slug, chunk_id: r.chunk_id })), { source_id: FOREIGN, slug: 'notes/heron', chunk_id: 0 }],+ return_unit: unit, token_budget: 32000,+ } });+ expect(assembled.isError, toolDiagnostic('assemble_evidence', assembled)).not.toBe(true);+ assertNoLeak(`assemble ${unit}`, assembled, canaries);+ if (unit === 'page') assertPresent('assemble page', assembled);+ }+ };+ await withStdio(verify);+ await withHttp(verify);+ }, 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 };+ 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[];+ expect(wide.some(h => h.source_id === FOREIGN)).toBe(true);+ const revoked = await deliverEvidence(engine, wide, plan, { sourceIds: [BOUND], excludePrivate: true, requireSafeChunks: true });+ assertNoLeak('revoked', revoked.results, ['FOREIGNSOURCECANARY', ...REMOTE_CANARIES]);+ expect(revoked.delivery.dropped_reasons.not_readable).toBeGreaterThan(0);++ });+ // Mid-flight edit: the secret line is removed after ranking.+ const staleHits = await mutate(async () =>+ await operations.find(o => o.name === 'search')!.handler(ctxOf(false), { query: 'heron editable', source_id: BOUND, limit: 50 }) as SearchResult[]);+ const edited = staleHits.filter(h => h.slug === 'notes/heron-edit');+ expect(JSON.stringify(edited)).toContain('EDITSECRETCANARY');+ await mutate(async () => {+ await importPage('notes/heron-edit', BOUND, `---\ntitle: heron edit\ntype: note\n---\n\nheron editable page. EDITEDPUBLICLINE replaced.\n\n${filler(6)}\n`);+ const after = await deliverEvidence(engine, edited, plan, { sourceId: BOUND, excludePrivate: false, requireSafeChunks: false });+ assertNoLeak('mid-flight edit', after.results, ['EDITSECRETCANARY']);+ expect(JSON.stringify(after.results)).toContain('EDITEDPUBLICLINE');+ // Private flip between ranking and expansion.+ const hits = await operations.find(o => o.name === 'search')!.handler(ctxOf(true), { query: 'heron editable EDITEDPUBLICLINE', source_id: BOUND, limit: 50 }) as SearchResult[];+ const editHit = hits.filter(h => h.slug === 'notes/heron-edit');+ expect(editHit.length).toBeGreaterThan(0);+ await importPage('notes/heron-edit', BOUND, `---\ntitle: heron edit\ntype: note\nvisibility: private\n---\n\nheron editable page. EDITEDPUBLICLINE replaced.\n\n${filler(6)}\n`);+ const flipped = await deliverEvidence(engine, editHit, plan, { sourceId: BOUND, excludePrivate: true, requireSafeChunks: true });+ expect(flipped.results).toEqual([]);+ expect(flipped.delivery.dropped_reasons).toEqual({ not_readable: 1 });+ const trusted = await deliverEvidence(engine, editHit, plan, { sourceId: BOUND, excludePrivate: false, requireSafeChunks: false });+ expect(trusted.results).toHaveLength(1);+ });+ }, 120_000);++ test('the fixture canaries are protected content, not absent content', () => {+ expect(heronPage()).toContain(FACTS_FENCE_BEGIN);+ for (const c of [...ALWAYS_CANARIES.filter(c => !['FOREIGNSOURCECANARY', 'EDITSECRETCANARY'].includes(c))]) expect(heronPage()).toContain(c);+ });+});diff --git a/test/e2e/evidence-delivery-parity.test.ts b/test/e2e/evidence-delivery-parity.test.tsnew file mode 100644index 0000000000..1befc773b8--- /dev/null+++ b/test/e2e/evidence-delivery-parity.test.ts@@ -0,0 +1,119 @@+/**+ * Evidence delivery engine parity (PGLite vs Postgres) and product-path+ * parity (plan amendment 8 / E3):+ * - the off-path golden holds on Postgres too (byte-identical to the+ * pre-feature release fixture);+ * - getChunkWindows returns the same windows, authorization and seal+ * decisions on both engines;+ * - for the same ordered hits, `query`/`search` and `assemble_evidence`+ * produce the same evidence fingerprint, and both engines deliver the+ * same text for every unit.+ *+ * Postgres arm runs when DATABASE_URL is set.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import { 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 { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { captureOffPath, seedOffPath } from '../helpers/evidence-delivery-fixture.ts';++const FIXTURE = join(import.meta.dir, '../fixtures/goldens/evidence-delivery/off-path.json');+const backends = process.env.DATABASE_URL ? ['pglite', 'postgres'] as const : ['pglite'] as const;+const UNITS = ['window', 'section', 'page', 'auto'] as const;+const engines: Partial<Record<(typeof backends)[number], BrainEngine>> = {};+const closers: Array<() => Promise<void>> = [];++function ctxOf(engine: BrainEngine, remote = false): OperationContext {+ return { engine: engine as never, config: {} as never, logger: console as never, dryRun: false, remote, sourceId: 'default' } as OperationContext;+}++const op = (name: string) => operations.find(o => o.name === name)!;++beforeAll(async () => {+ for (const backend of backends) {+ let engine: BrainEngine;+ if (backend === 'postgres') {+ const isolated = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ engine = isolated.engine;+ closers.push(isolated.close);+ } else {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ closers.push(() => engine.disconnect());+ }+ await seedOffPath(engine);+ engines[backend] = engine;+ }+}, 240_000);++afterAll(async () => {+ for (const close of closers) await close();+}, 120_000);++describe('evidence delivery parity', () => {+ for (const backend of backends) {+ test(`off-path output is byte-identical to the pre-feature release (${backend})`, async () => {+ const want = JSON.parse(readFileSync(FIXTURE, 'utf8')) as Record<string, string>;+ const got = await captureOffPath(engines[backend]!);+ for (const key of Object.keys(want)) expect(`${key}: ${got[key]}`).toBe(`${key}: ${want[key]}`);+ }, 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]) {+ const rows = await op('search').handler(ctxOf(engine, remote), { query: 'ocelot', return_unit: 'page', token_budget: 32000 }) as SearchResult[];+ expect(rows.length).toBeGreaterThan(0);+ for (const r of rows) {+ const [page] = await engine.executeRaw<{ compiled_truth: string; timeline: string }>('SELECT compiled_truth, timeline FROM pages WHERE id = $1', [r.page_id]);+ expect(r.chunk_text).toBe(pageEvidenceText(page, true).text.trimEnd());+ }+ }+ }, 120_000);++ test(`search/query and assemble_evidence deliver identical evidence for the same hits (${backend})`, async () => {+ const engine = engines[backend]!;+ for (const remote of [false, true]) {+ const hits = await op('search').handler(ctxOf(engine, remote), { query: 'ocelot' }) as SearchResult[];+ expect(hits.length).toBeGreaterThan(0);+ for (const unit of UNITS) {+ const viaSearch = await op('search').handler(ctxOf(engine, remote), { query: 'ocelot', return_unit: unit, token_budget: 2500 }) as SearchResult[];+ const viaAssemble = await op('assemble_evidence').handler(ctxOf(engine, remote), {+ hits: hits.map(h => ({ source_id: h.source_id, slug: h.slug, chunk_id: h.chunk_id })), return_unit: unit, token_budget: 2500,+ }) as { results: SearchResult[] };+ expect(evidenceFingerprint(viaAssemble.results)).toBe(evidenceFingerprint(viaSearch));+ }+ const qHits = await op('query').handler(ctxOf(engine, remote), { query: 'ocelot pricing', expand: false }) as SearchResult[];+ const viaQuery = await op('query').handler(ctxOf(engine, remote), { query: 'ocelot pricing', expand: false, return_unit: 'page', token_budget: 2500 }) as SearchResult[];+ const viaAssemble = await op('assemble_evidence').handler(ctxOf(engine, remote), {+ hits: qHits.map(h => ({ source_id: h.source_id, slug: h.slug, chunk_id: h.chunk_id })), return_unit: 'page', token_budget: 2500,+ }) as { results: SearchResult[] };+ expect(evidenceFingerprint(viaAssemble.results)).toBe(evidenceFingerprint(viaQuery));+ }+ }, 120_000);+ }++ if (backends.length === 2) {+ test('both engines deliver the same windows and the same text for every unit', async () => {+ const [a, b] = [engines.pglite!, engines.postgres!];+ const textOf = (rows: SearchResult[]) => rows.map(r => [r.slug, r.chunk_text, r.delivered?.unit, r.delivered?.tokens, r.delivered?.truncated]);+ for (const unit of UNITS) {+ const ra = await op('search').handler(ctxOf(a), { query: 'ocelot', return_unit: unit, token_budget: 2500 }) as SearchResult[];+ const rb = await op('search').handler(ctxOf(b), { query: 'ocelot', return_unit: unit, token_budget: 2500 }) as SearchResult[];+ expect(textOf(rb)).toEqual(textOf(ra));+ }+ 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 })),+ { excludePrivate: true, requireSafeChunks: true, chunkSources: ['compiled_truth', 'timeline'], maxRows: 5 });+ return pages.map(p => ({ slug: p.slug, sealed: p.sealed, max: p.max_chunk_index, limited: p.row_limited, chunks: p.chunks.map(c => [c.chunk_index, c.chunk_source, c.chunk_text]) }));+ };+ expect(await windows(b)).toEqual(await windows(a));+ }, 120_000);+ }+});diff --git a/test/e2e/ontology-merge-parity.test.ts b/test/e2e/ontology-merge-parity.test.tsindex fc0a24cdb0..e69697bd55 100644--- a/test/e2e/ontology-merge-parity.test.ts+++ b/test/e2e/ontology-merge-parity.test.ts@@ -276,4 +276,19 @@ describeBoth('Engine parity — mergeOntologyFact matrix (D7)', () => {expect(all.filter((c) => c.entity_slug === ENTITY)).toEqual([]);}});+ test('backdated observation of the current value is an earlier stint, not an expired corroboration', async () => {+ const STINT = 'people/onto-stint';+ const at = async (eng: BrainEngine, asof: string) =>+ (await eng.getOntology(STINT, { sourceId: 'default', asof })).find(r => r.dimension === 'employer')?.value ?? null;+ for (const eng of [pgEngine, pgliteEngine]) {+ await eng.mergeOntologyFact({ entitySlug: STINT, dimension: 'employer', value: 'startup-1', source: 'notes/b', validFrom: '2023-01-01T00:00:00.000Z' });+ await eng.mergeOntologyFact({ entitySlug: STINT, dimension: 'employer', value: 'startup-0', source: 'notes/c', validFrom: '2024-01-01T00:00:00.000Z' });+ const late = await eng.mergeOntologyFact({ entitySlug: STINT, dimension: 'employer', value: 'startup-0', source: 'notes/a', validFrom: '2022-01-01T00:00:00.000Z' });+ expect(late.action).toBe('inserted');+ expect(await at(eng, '2022-06-01T00:00:00Z')).toBe('startup-0');+ expect(await at(eng, '2023-06-01T00:00:00Z')).toBe('startup-1');+ expect(await at(eng, '2024-06-01T00:00:00Z')).toBe('startup-0');+ }+ expect(await dumpFacts(pgEngine, STINT)).toEqual(await dumpFacts(pgliteEngine, STINT));+ });});diff --git a/test/engine-surface-coverage.test.ts b/test/engine-surface-coverage.test.tsindex cfb6209b2f..e8dddf703a 100644--- a/test/engine-surface-coverage.test.ts+++ b/test/engine-surface-coverage.test.ts@@ -56,7 +56,7 @@ const INTERFACE_METHODS: readonly string[] = [// Search'searchKeyword', 'searchTitles', 'searchVector', 'getEmbeddingsByChunkIds',// Chunks- 'upsertChunks', 'getChunks', 'countStaleChunks', 'sumStaleChunkChars', 'setPageEmbeddingSignature',+ 'upsertChunks', 'getChunks', 'getChunkWindows', 'countStaleChunks', 'sumStaleChunkChars', 'setPageEmbeddingSignature','invalidateStaleSignatureEmbeddings', 'invalidateContentDriftEmbeddings', 'listStaleChunks','countChunklessPagesWithContent', 'listChunklessPagesWithContent', 'deleteChunks',// Extraction watermarkdiff --git a/test/entity-card-private-backlinks.test.ts b/test/entity-card-private-backlinks.test.tsnew file mode 100644index 0000000000..fa0b1a87fc--- /dev/null+++ b/test/entity-card-private-backlinks.test.ts@@ -0,0 +1,99 @@+/**+ * The entity card (entity, context_pack, delta) must not disclose inbound+ * links from pages a remote caller cannot read: a `visibility: private`+ * page, a derived page (private by default), a soft-deleted page, or an edge+ * whose origin page is private. Such an edge carries the hidden page's slug+ * and a sentence of its body in `links.context`, and it must not be counted+ * in `backlink_count` either. get_backlinks already hides them; the card+ * must agree with it on every transport, while the trusted local caller+ * keeps seeing everything. (gbrain-evals N6 visibility-leak-fuzz, bug 1.)+ *+ * Synthetic data only.+ */+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';++let engine: PGLiteEngine;+const config = { engine: 'pglite' } as any;++const put = (slug: string, content: string) =>+ dispatchToolCall(engine, 'put_page', { slug, content }, { remote: false, sourceId: 'default', config });++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await put('notes/hub', '---\ntitle: Hub\ntype: note\n---\nTeam hub.\n');+ await put('notes/public-ref', '---\ntitle: Public ref\ntype: note\n---\nPUBLICMARKER agenda. See [[notes/hub]].\n');+ await put('notes/secret', '---\ntitle: Secret\ntype: note\nvisibility: private\n---\nSECRETMARKER layoff plan. See [[notes/hub]].\n');+ await put('atoms/derived-note', '---\ntitle: Derived\ntype: atom\n---\nATOMMARKER derived claim. See [[notes/hub]].\n');+ await put('notes/deleted-ref', '---\ntitle: Deleted ref\ntype: note\n---\nDELETEDMARKER old memo. See [[notes/hub]].\n');+ await engine.executeRaw(`UPDATE pages SET deleted_at = now() WHERE slug = 'notes/deleted-ref'`);+ // A public page whose edge to the hub was authored by a private page.+ await put('notes/relay', '---\ntitle: Relay\ntype: note\n---\nRelay page.\n');+ await engine.executeRaw(+ `INSERT INTO links (from_page_id, to_page_id, link_type, context, link_source, origin_page_id)+ SELECT r.id, h.id, 'mentions', 'ORIGINMARKER relayed sentence', 'frontmatter', s.id+ FROM pages r, pages h, pages s+ WHERE r.slug = 'notes/relay' AND h.slug = 'notes/hub' AND s.slug = 'notes/secret'`,+ );+});++afterAll(async () => {+ await engine.disconnect();+});++const HIDDEN = ['notes/secret', 'SECRETMARKER', 'atoms/derived-note', 'ATOMMARKER', 'notes/deleted-ref', 'DELETEDMARKER', 'ORIGINMARKER'];++const remoteCallers = {+ stdio: { remote: true, transport: 'stdio' as const, sourceId: 'default', takesHoldersAllowList: ['world'], config },+ http: {+ remote: true,+ transport: 'http' as const,+ sourceId: 'default',+ takesHoldersAllowList: ['world'],+ config,+ auth: { token: 't', clientId: 'c', scopes: ['read'], allowedSources: ['default'] } as any,+ },+};++async function call(op: string, args: Record<string, unknown>, opts: Record<string, unknown>) {+ const r = await dispatchToolCall(engine, op, args, opts as any);+ expect(r.isError).toBeFalsy();+ return r.content[0].text;+}++describe('entity card inbound edges respect private visibility', () => {+ for (const [name, opts] of Object.entries(remoteCallers)) {+ test(`${name}: entity hides private, derived, deleted and private-origin backlinks and does not count them`, async () => {+ const text = await call('entity', { name: 'notes/hub' }, opts);+ for (const marker of HIDDEN) expect(text).not.toContain(marker);+ const card = JSON.parse(text).card;+ expect(card.edges.filter((e: any) => e.direction === 'in').map((e: any) => e.slug)).toEqual(['notes/public-ref']);+ expect(card.backlink_count).toBe(1);+ });++ test(`${name}: context_pack hides the same edges`, async () => {+ const text = await call('context_pack', { entities: 'notes/hub' }, opts);+ for (const marker of HIDDEN) expect(text).not.toContain(marker);+ expect(text).toContain('notes/public-ref');+ });++ test(`${name}: entity card inbound edges agree with get_backlinks`, async () => {+ const card = JSON.parse(await call('entity', { name: 'notes/hub' }, opts)).card;+ const backlinks = JSON.parse(await call('get_backlinks', { slug: 'notes/hub' }, opts));+ const fromBacklinks = new Set(backlinks.map((l: any) => l.from_slug));+ for (const e of card.edges.filter((e: any) => e.direction === 'in')) expect(fromBacklinks.has(e.slug)).toBe(true);+ });+ }++ test('local caller still sees private and derived backlinks (soft-deleted stay hidden)', async () => {+ const text = await call('entity', { name: 'notes/hub' }, { remote: false, sourceId: 'default', config });+ const card = JSON.parse(text).card;+ const inbound = card.edges.filter((e: any) => e.direction === 'in').map((e: any) => e.slug).sort();+ expect(inbound).toEqual(['atoms/derived-note', 'notes/public-ref', 'notes/relay', 'notes/secret']);+ expect(card.backlink_count).toBe(4);+ expect(text).not.toContain('DELETEDMARKER');+ });+});diff --git a/test/entity-resolve-exact-name-floor.test.ts b/test/entity-resolve-exact-name-floor.test.tsnew file mode 100644index 0000000000..51b862d73b--- /dev/null+++ b/test/entity-resolve-exact-name-floor.test.ts@@ -0,0 +1,52 @@+/**+ * The exact-name floor: a mention that is exactly a live page's own name+ * resolves to that page, even when another page lists the same string in its+ * `aliases:` (a former name). The alias arm stays authoritative for mentions+ * that are nobody's own name. (gbrain-evals N4 entity-resolution, bug 1.)+ *+ * Synthetic data only.+ */+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { resolveEntitySlug, resolveEntitySlugWithSource } from '../src/core/entities/resolve.ts';+import { operations } from '../src/core/operations.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await importFromContent(engine, 'people/jordan-lee-example',+ '---\ntitle: Jordan Lee-Example\ntype: person\n---\n\n# Jordan Lee-Example\n', { noEmbed: true });+ await importFromContent(engine, 'people/jordan-smith-example',+ '---\ntitle: Jordan Smith-Example\ntype: person\naliases:\n - "Jordan Lee-Example"\n - "Jojo Example"\n---\n\n# Jordan Smith-Example\n\nFormerly Jordan Lee-Example.\n', { noEmbed: true });+});++afterAll(async () => {+ await engine.disconnect();+});++describe('exact own name beats another page\'s alias', () => {+ test('resolveEntitySlugWithSource returns the page whose own name matches', async () => {+ const r = await resolveEntitySlugWithSource(engine, 'default', 'Jordan Lee-Example');+ expect(r?.slug).toBe('people/jordan-lee-example');+ });++ test('resolveEntitySlug agrees', async () => {+ expect(await resolveEntitySlug(engine, 'default', 'Jordan Lee-Example')).toBe('people/jordan-lee-example');+ });++ test('an alias that is nobody\'s own name still resolves through the alias arm', async () => {+ expect(await resolveEntitySlugWithSource(engine, 'default', 'Jojo Example'))+ .toEqual({ slug: 'people/jordan-smith-example', source: 'alias_exact' });+ });++ test('remember stores the fact on the exact-name page', async () => {+ const ctx = { engine, config: {}, logger: console, dryRun: false, remote: false, sourceId: 'default' } as any;+ const remember = operations.find(o => o.name === 'remember')!;+ const saved = await remember.handler(ctx, { fact: 'Jordan Lee-Example joined the platform team', entity: 'Jordan Lee-Example', provenance: 'test' }) as any;+ expect(saved.entity_slug).toBe('people/jordan-lee-example');+ });+});diff --git a/test/evidence-delivery-golden.test.ts b/test/evidence-delivery-golden.test.tsnew file mode 100644index 0000000000..f8e1f9e9b1--- /dev/null+++ b/test/evidence-delivery-golden.test.ts@@ -0,0 +1,58 @@+/**+ * Evidence delivery off-path golden: with `return_unit` omitted (or `chunk`,+ * explicit or from config) search, query, recall, think's prompt and the MCP+ * serialization are byte-identical to the pre-feature release.+ *+ * Authoring gate: protects the frozen off-path contract (plan amendment 6).+ * Regression: any stage/param/meta change that leaks into default responses+ * (a `delivery` key, a changed result count, recall field order, think+ * excerpting). The fixture was generated by this same file on the release+ * before evidence delivery (refactor wave 1, 9a0e01b4) and must not be+ * regenerated on a branch that changes the off path.+ *+ * The Postgres arm lives in test/e2e/evidence-delivery-parity.test.ts.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';+import { dirname, join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { captureOffPath, seedOffPath } from './helpers/evidence-delivery-fixture.ts';++const FIXTURE = join(import.meta.dir, 'fixtures/goldens/evidence-delivery/off-path.json');+let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await seedOffPath(engine);+}, 240_000);++afterAll(async () => {+ await engine.disconnect();+}, 240_000);++describe('evidence delivery off path', () => {+ test('omitted / chunk return_unit is byte-identical to the pre-feature release', async () => {+ const got = await captureOffPath(engine);+ if (process.env.GBRAIN_TEST_UPDATE_GOLDENS === '1') {+ mkdirSync(dirname(FIXTURE), { recursive: true });+ writeFileSync(FIXTURE, JSON.stringify(got, null, 2) + '\n');+ }+ const want = JSON.parse(readFileSync(FIXTURE, 'utf8')) as Record<string, string>;+ expect(Object.keys(got).sort()).toEqual(Object.keys(want).sort());+ for (const key of Object.keys(want)) expect(`${key}: ${got[key]}`).toBe(`${key}: ${want[key]}`);+ });++ test('a config-level chunk unit is also byte-identical', async () => {+ const want = JSON.parse(readFileSync(FIXTURE, 'utf8')) as Record<string, string>;+ await engine.setConfig('search.return_unit', 'chunk');+ await engine.setConfig('think.return_unit', 'chunk');+ try {+ const got = await captureOffPath(engine);+ for (const key of Object.keys(want)) expect(`${key}: ${got[key]}`).toBe(`${key}: ${want[key]}`);+ } finally {+ await engine.executeRaw(`DELETE FROM config WHERE key IN ('search.return_unit', 'think.return_unit')`);+ }+ });+});diff --git a/test/evidence-delivery.test.ts b/test/evidence-delivery.test.tsnew file mode 100644index 0000000000..00bc032e1f--- /dev/null+++ b/test/evidence-delivery.test.ts@@ -0,0 +1,513 @@+/**+ * Evidence delivery (`return_unit`) — page text, chunk location, units, allocation, spans,+ * errors, snippet precedence and final-consumer wiring.+ *+ * Authoring gate: protects the delivered-evidence contract in+ * docs/evidence-delivery.md (the bytes gbrain-evals measures). Regressions it+ * catches: page text that differs from the body (lost paragraph breaks, duplicated overlap), budget overrun, spans that+ * point at the wrong text, a config flip overriding the subagent snippet cap,+ * mutated shared hit rows, recall/think consumers dropping the evidence.+ * Existing search tests never exercise the stage (it is opt-in). No seams:+ * the property half drives `deliverEvidence` through a stub engine that only+ * answers `getChunkWindows`; the op half runs the real ops on PGLite.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+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 type { ChunkWindowOpts, ChunkWindowPage, ChunkWindowRequest } from '../src/core/search/chunk-windows.ts';+import { operations, type OperationContext } from '../src/core/operations.ts';+import { chunkText } from '../src/core/chunkers/recursive.ts';+import { prepareMarkdownChunks } from '../src/core/markdown-chunks.ts';+import { installFixtureChunks } from './helpers/page-projection.ts';+import { renderPagesBlock } from '../src/core/think/gather.ts';+import { runThink } from '../src/core/think/index.ts';+import { formatDeliverySummary } from '../src/core/search/explain-formatter.ts';+import {+ countEvidenceTokens,+ deliverEvidence,+ deliveryVersionSkewWarning,+ EVIDENCE_BLOCK_CHAR_CAP,+ EVIDENCE_OMISSION,+ evidenceFingerprint,+ isConversationLabels,+ locateChunks,+ pageEvidenceText,+ splitPieces,+ TIMELINE_SEPARATOR,+ type EvidencePlan,+} from '../src/core/search/evidence-delivery.ts';++function rng(seed: number): () => number {+ let a = seed >>> 0;+ return () => {+ a = (a + 0x6d2b79f5) >>> 0;+ let t = a;+ t = Math.imul(t ^ (t >>> 15), t | 1);+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+}++const WORDS = ['alpha', 'river', 'launch', 'march', 'budget', 'widget', 'acme', 'notes', 'said', 'the', 'moved', 'plan', 'review', 'quarter', 'team', 'draft'];++function prose(r: () => number, paragraphs: number): string {+ const out: string[] = [];+ for (let p = 0; p < paragraphs; p++) {+ const sentences: string[] = [];+ const n = 2 + Math.floor(r() * 8);+ for (let s = 0; s < n; s++) {+ const len = 4 + Math.floor(r() * 16);+ const words = Array.from({ length: len }, () => WORDS[Math.floor(r() * WORDS.length)]);+ words[0] = words[0][0].toUpperCase() + words[0].slice(1);+ sentences.push(words.join(' ') + '.');+ }+ out.push(sentences.join(' '));+ }+ return out.join('\n\n');+}++const norm = (s: string) => s.replace(/\s+/g, ' ').trim();++describe('page text and chunk location', () => {+ test('every chunk the chunker cut is located in the body, even where it folded whitespace', () => {+ const r = rng(7);+ for (let doc = 0; doc < 25; doc++) {+ const body = prose(r, 10 + Math.floor(r() * 40));+ const chunks = chunkText(body).map((c, i) => ({ id: i + 1, chunk_index: i, chunk_text: c.text }));+ const spans = locateChunks(body, chunks);+ expect(spans.map(x => x.id)).toEqual(chunks.map(c => c.id));+ for (const sp of spans) expect(norm(body.slice(sp.start, sp.end))).toBe(norm(chunks[sp.id - 1].chunk_text));+ for (let i = 1; i < spans.length; i++) expect(spans[i].start).toBeGreaterThan(spans[i - 1].start);+ }+ });++ test('long turns whose paragraph breaks the chunker folds are delivered byte-identical to the body', async () => {+ const turn = (i: number) => `**${i % 2 ? 'assistant' : 'user'}:** ${Array.from({ length: 40 }, (_, k) => `Sentence ${i}-${k} has several plain words in it.`).join(' ')}`;+ const body = Array.from({ length: 8 }, (_, i) => turn(i)).join('\n\n') + '\n';+ const chunks = chunkText(body).map(c => c.text);+ expect(chunks.some(c => !body.includes(c))).toBe(true);+ const page: FakePage = { page_id: 1, slug: 'chat/long', title: 'Long', body, chunks };+ const { results } = await deliverEvidence(fakeEngine([page]), [hitFor(page, 2)], planOf('page', 32000), {});+ expect(results[0].chunk_text).toBe(body.trimEnd());+ expect(results[0].delivered.truncated).toBe(false);+ });++ test('page text is the whole body sanitized before slicing, timeline joined like the serializer', () => {+ const facts = `<!--- gbrain:facts:begin -->\n\n| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|\n| 1 | PUBLICROW | fact | 1.0 | world | high | | | | |\n| 2 | PRIVATEROW | fact | 1.0 | private | high | | | | |\n<!--- gbrain:facts:end -->`;+ const out = pageEvidenceText({ compiled_truth: `intro\n\n${facts}\n\n<!--- gbrain:takes:begin -->\nTAKEROW\n<!--- gbrain:takes:end -->\nend`, timeline: '- 2026 TIMELINEROW' }, true);+ expect(out.text).toContain('PUBLICROW');+ expect(out.text).not.toContain('PRIVATEROW');+ expect(out.text).not.toContain('TAKEROW');+ expect(out.text).toContain(`end${TIMELINE_SEPARATOR}- 2026 TIMELINEROW`);+ expect(pageEvidenceText({ compiled_truth: 'x', timeline: 'TL' }, false).text).toBe('x');+ });++ test('CJK chunks (char-cut overlap) are located', () => {+ const r = rng(11);+ const cjk = Array.from({ length: 1500 }, () => '天地玄黄宇宙洪荒日月盈昃辰宿列张'[Math.floor(r() * 16)]).join('')+ .replace(/(.{40})/g, '$1。');+ const chunks = chunkText(cjk).map((c, i) => ({ id: i + 1, chunk_index: i, chunk_text: c.text }));+ expect(chunks.length).toBeGreaterThan(2);+ expect(locateChunks(cjk, chunks)).toHaveLength(chunks.length);+ });++ test('splitPieces is lossless and bounded', () => {+ const text = `short line\n${'long '.repeat(300)}\n\nlast`;+ const pieces = splitPieces(text);+ expect(pieces.map(p => text.slice(p.start, p.end)).join('')).toBe(text);+ for (const p of pieces) expect(p.end - p.start).toBeLessThanOrEqual(400);+ });++ test('token counts are CJK-aware (cl100k, not char/4)', () => {+ const cjk = '天地玄黄宇宙洪荒'.repeat(40);+ expect(countEvidenceTokens(cjk)).toBeGreaterThan(cjk.length / 4 * 2);+ });++ test('conversation detection is structural', () => {+ expect(isConversationLabels(['user', 'assistant', 'user', 'assistant'])).toBe(true);+ expect(isConversationLabels(['note', 'note', 'note', 'summary'])).toBe(false);+ expect(isConversationLabels(['user', 'assistant'])).toBe(false);+ });+});++// ---------------------------------------------------------------------------+// Property tests over the assembler (stub engine answering getChunkWindows)+// ---------------------------------------------------------------------------++interface FakePage { page_id: number; slug: string; title: string; chunks: string[]; body?: string; sealed?: boolean }++function fakeEngine(pages: FakePage[], opts: { fail?: boolean } = {}): BrainEngine & { calls: number } {+ const engine = {+ calls: 0,+ async getChunkWindows(requests: ChunkWindowRequest[], o: ChunkWindowOpts): Promise<ChunkWindowPage[]> {+ engine.calls++;+ if (opts.fail) throw new Error('synthetic fetch failure');+ const out: ChunkWindowPage[] = [];+ for (const p of pages) {+ const mine = requests.filter(r => r.page_id === p.page_id);+ if (mine.length === 0) continue;+ out.push({+ page_id: p.page_id, slug: p.slug, source_id: 'default', type: 'note', revision: `rev-${p.page_id}`,+ sealed: p.sealed !== false, max_chunk_index: p.chunks.length - 1, row_limited: false,+ compiled_truth: p.body ?? p.chunks.join('\n\n'), timeline: '',+ chunks: p.sealed === false ? [] : p.chunks.map((t, i) => ({ id: p.page_id * 1000 + i, chunk_index: i, chunk_text: t, chunk_source: 'compiled_truth' }))+ .filter(c => mine.some(r => c.chunk_index >= r.from_index && c.chunk_index <= r.to_index))+ .filter(() => o.chunkSources.includes('compiled_truth')),+ });+ }+ return out;+ },+ };+ return engine as unknown as BrainEngine & { calls: number };+}++function hitFor(p: FakePage, index: number): SearchResult {+ return {+ slug: p.slug, page_id: p.page_id, title: p.title, type: 'note', chunk_text: p.chunks[index], chunk_source: 'compiled_truth',+ chunk_id: p.page_id * 1000 + index, chunk_index: index, score: 1, stale: false, source_id: 'default',+ };+}++function planOf(unit: EvidencePlan['unit'], budget: number, window = 1): EvidencePlan {+ return { requestedUnit: unit, unit, window, budgetTokens: budget, explicitUnit: true };+}++function randomCorpus(r: () => number, pageCount: number): FakePage[] {+ return Array.from({ length: pageCount }, (_, i) => {+ const conversational = r() < 0.4;+ const body = conversational+ ? Array.from({ length: 6 + Math.floor(r() * 30) }, (_, t) => `**${t % 2 ? 'assistant' : 'user'}:** ${prose(r, 1)}`).join('\n\n')+ : Array.from({ length: 1 + Math.floor(r() * 4) }, (_, s) => `## Section ${s}\n\n${prose(r, 2 + Math.floor(r() * 8))}`).join('\n\n');+ return { page_id: i + 1, slug: `pages/p${i + 1}`, title: `Page ${i + 1}`, body, chunks: chunkText(body).map(c => c.text) };+ });+}++describe('allocation and boundary properties', () => {+ test('budget, rank order, span, cap and non-mutation invariants hold across random corpora', async () => {+ const r = rng(20260930);+ for (let trial = 0; trial < 60; trial++) {+ const pages = randomCorpus(r, 1 + Math.floor(r() * 8));+ const hits: SearchResult[] = [];+ for (let k = 0; k < 1 + Math.floor(r() * 10); k++) {+ const p = pages[Math.floor(r() * pages.length)];+ hits.push(hitFor(p, Math.floor(r() * p.chunks.length)));+ }+ const unit = (['window', 'section', 'page', 'auto'] as const)[Math.floor(r() * 4)];+ const budget = [40, 200, 800, 3000, 12000][Math.floor(r() * 5)];+ const snapshot = JSON.stringify(hits);+ const engine = fakeEngine(pages);+ const { results, delivery } = await deliverEvidence(engine, hits, planOf(unit, budget, 1 + Math.floor(r() * 3)), {});+ expect(JSON.stringify(hits)).toBe(snapshot);+ expect(engine.calls).toBe(1);+ expect(delivery.budget_used).toBeLessThanOrEqual(budget);+ const order = [...new Set(hits.map(h => h.page_id))];+ expect(results.map(x => x.page_id)).toEqual(order.filter(id => results.some(x => x.page_id === id)));+ expect(new Set(results.map(x => x.page_id)).size).toBe(results.length);+ expect(results.length + delivery.dropped).toBe(order.length);+ for (const res of results) {+ expect(res.chunk_text.length).toBeLessThanOrEqual(EVIDENCE_BLOCK_CHAR_CAP);+ expect(res.delivered.tokens).toBeLessThanOrEqual(budget);+ for (const id of res.delivered.chunk_ids) expect(hits.some(h => h.chunk_id === id && h.page_id === res.page_id)).toBe(true);+ for (const s of res.delivered.match_spans) {+ expect(s.start).toBeGreaterThanOrEqual(0);+ expect(s.end).toBeLessThanOrEqual(res.chunk_text.length);+ const anchor = hits.find(h => h.chunk_id === s.chunk_id)!;+ expect(norm(anchor.chunk_text)).toContain(norm(res.chunk_text.slice(s.start, s.end)));+ }+ }+ const again = await deliverEvidence(fakeEngine(pages), hits, planOf(unit, budget, delivery.return_window), {});+ expect(evidenceFingerprint(again.results)).toBe(evidenceFingerprint(results));+ }+ });++ test('a budget below every floor cuts rank one to fit and drops the rest', async () => {+ const [a, b] = randomCorpus(rng(3), 2);+ const { results, delivery } = await deliverEvidence(fakeEngine([a, b]), [hitFor(a, 0), hitFor(b, 0)], planOf('page', 12), {});+ expect(results).toHaveLength(1);+ expect(results[0].delivered.truncated).toBe(true);+ expect(delivery.budget_used).toBeLessThanOrEqual(12);+ expect(delivery.dropped_reasons).toEqual({ budget_floor: 1 });+ });++ test('distinct pages keep their matching span before rank one is enriched', async () => {+ const pages = randomCorpus(rng(5), 5).map(p => ({ ...p, body: undefined, chunks: [...p.chunks, ...p.chunks, ...p.chunks] }));+ const hits = pages.map(p => hitFor(p, Math.floor(p.chunks.length / 2)));+ const floors = hits.reduce((n, h) => n + countEvidenceTokens(h.chunk_text) + countEvidenceTokens(h.title), 0);+ const { results } = await deliverEvidence(fakeEngine(pages), hits, planOf('page', Math.ceil(floors * 1.5)), {});+ expect(results).toHaveLength(5);+ expect(results[0].delivered.truncated).toBe(true);+ for (const res of results) expect(res.delivered.match_spans.length).toBeGreaterThan(0);+ });++ test('many sessions, repeated text and missing anchors stay deterministic and explicit', async () => {+ const repeated = 'the same sentence repeats verbatim across every chunk here.';+ const page: FakePage = { page_id: 9, slug: 'chat/repeat', title: 'Repeat', chunks: Array.from({ length: 6 }, () => repeated) };+ const ghost: SearchResult = { ...hitFor(page, 2), chunk_id: 999_999, chunk_text: 'text that is no longer in the page at all' };+ const { results } = await deliverEvidence(fakeEngine([page]), [hitFor(page, 1), ghost], planOf('window', 5000), {});+ expect(results).toHaveLength(1);+ expect(results[0].delivered.chunk_ids).toEqual([9001, 999_999]);+ expect(results[0].delivered.unmapped_chunk_ids).toEqual([999_999]);+ expect(results[0].delivered.match_spans.every(s => s.chunk_id === 9001)).toBe(true);+ });++ test('redaction runs before accounting and unmaps shifted spans', async () => {+ const secret = ['AKIA', 'ABCDEFGHIJKLMNOP'].join('');+ const page: FakePage = { page_id: 4, slug: 'notes/keys', title: 'Keys', chunks: [`The deploy key is ${secret} for staging and nothing else here.`] };+ const { results, delivery } = await deliverEvidence(fakeEngine([page]), [hitFor(page, 0)], planOf('page', 5000), {});+ expect(results[0].chunk_text).not.toContain(secret);+ expect(results[0].chunk_text).toContain('<REDACTED:');+ expect(results[0].delivered.match_spans).toEqual([]);+ expect(results[0].delivered.unmapped_chunk_ids).toEqual([4000]);+ expect(delivery.fallbacks).toContain('redaction_unmapped');+ });++ test('oversized pages are cut at the 60,000-character cap, never redacted wholesale', async () => {+ const big = Array.from({ length: 40 }, (_, i) => `Paragraph ${i}. ${'lorem ipsum dolor sit amet '.repeat(90)}`);+ const page: FakePage = { page_id: 2, slug: 'notes/big', title: 'Big', chunks: big };+ const { results } = await deliverEvidence(fakeEngine([page]), [hitFor(page, 20)], planOf('page', 32000), {});+ expect(results[0].chunk_text.length).toBeLessThanOrEqual(EVIDENCE_BLOCK_CHAR_CAP);+ expect(results[0].chunk_text).not.toContain('<REDACTED:output_limit>');+ expect(results[0].delivered.truncated).toBe(true);+ expect(results[0].chunk_text).toContain('Paragraph 20.');+ });++ test('fetch failure falls back to fresh hit chunks, and never to cached ones', async () => {+ const [a] = randomCorpus(rng(8), 1);+ const live = await deliverEvidence(fakeEngine([a], { fail: true }), [hitFor(a, 0)], planOf('page', 5000), {});+ expect(live.results[0].chunk_text).toBe(a.chunks[0]);+ expect(live.results[0].delivered).toMatchObject({ unit: 'chunk', fallback_reason: 'fetch_failed' });+ expect(live.delivery.applied_unit).toBe('chunk');+ const cached = await deliverEvidence(fakeEngine([a], { fail: true }), [hitFor(a, 0)], planOf('page', 5000), {}, { liveHits: false });+ expect(cached.results).toEqual([]);+ expect(cached.delivery.dropped_reasons).toEqual({ not_readable: 1 });+ });++ test('a fetch that exceeds the timeout degrades to fresh hit chunks with a receipt', async () => {+ const [a] = randomCorpus(rng(14), 1);+ const hanging = { getChunkWindows: () => new Promise<never>(() => {}) } as unknown as BrainEngine;+ const { results, delivery } = await deliverEvidence(hanging, [hitFor(a, 0)], planOf('page', 5000), {}, { timeoutMs: 20 });+ expect(results[0].delivered.fallback_reason).toBe('fetch_timeout');+ expect(delivery.fallbacks).toContain('fetch_timeout');+ expect(formatDeliverySummary(delivery)).toContain('fallbacks: fetch_timeout');+ });++ test('a page absent from the re-authorized fetch is dropped, not served from the hit', async () => {+ const [a, b] = randomCorpus(rng(9), 2);+ const { results, delivery } = await deliverEvidence(fakeEngine([a]), [hitFor(b, 0), hitFor(a, 0)], planOf('window', 5000), {});+ expect(results.map(x => x.slug)).toEqual([a.slug]);+ expect(delivery.dropped_reasons).toEqual({ not_readable: 1 });+ expect(JSON.stringify(results)).not.toContain(b.chunks[0].slice(0, 60));+ });++ test('unsealed pages fall back to the hit chunk with a named reason', async () => {+ const [a] = randomCorpus(rng(10), 1);+ const { results } = await deliverEvidence(fakeEngine([{ ...a, sealed: false }]), [hitFor(a, 0)], planOf('page', 5000), {});+ expect(results[0].delivered.fallback_reason).toBe('unsealed_page');+ });++ test('section falls back to window when a page has no structure', async () => {+ const flat = prose(rng(12), 40);+ const page: FakePage = { page_id: 3, slug: 'notes/flat', title: 'Flat', body: flat, chunks: chunkText(flat).map(c => c.text) };+ const { results, delivery } = await deliverEvidence(fakeEngine([page]), [hitFor(page, 2)], planOf('section', 20000), {});+ expect(results[0].delivered.unit).toBe('window');+ expect(delivery.fallbacks).toContain('no_section_structure');+ });++ test('non-contiguous hits on one page join with the fixed omission line', async () => {+ const longBody = prose(rng(13), 80);+ const page: FakePage = { page_id: 5, slug: 'notes/long', title: 'Long', body: longBody, chunks: chunkText(longBody).map(c => c.text) };+ expect(page.chunks.length).toBeGreaterThan(8);+ const { results } = await deliverEvidence(fakeEngine([page]), [hitFor(page, 1), hitFor(page, page.chunks.length - 2)], planOf('window', 20000), {});+ expect(results).toHaveLength(1);+ expect(results[0].chunk_text).toContain(EVIDENCE_OMISSION);+ expect(results[0].delivered.match_spans.map(s => s.chunk_id)).toEqual([5001, 5000 + page.chunks.length - 2]);+ });+});++// ---------------------------------------------------------------------------+// Real ops on PGLite+// ---------------------------------------------------------------------------++let engine: PGLiteEngine;+const op = (name: string) => operations.find(o => o.name === name)!;+let lastMeta: Record<string, any> | null = null;++function ctxOf(overrides: Partial<OperationContext> = {}): OperationContext {+ return {+ engine: engine as never, config: {} as never, logger: console as never, dryRun: false, remote: false, sourceId: 'default',+ emitResponseMeta: (key: string, value: unknown) => { if (key === 'retrieval') lastMeta = value as Record<string, any>; },+ ...overrides,+ } as OperationContext;+}++const SESSION = Array.from({ length: 24 }, (_, i) =>+ `**user:** question ${i} ${'about the renewal and the widget roadmap '.repeat(6)}\n\n**assistant:** reply ${i} ${'we discussed timelines and owners '.repeat(6)}${i === 13 ? ' the launch moved to march narwhal' : ''}`,+).join('\n\n');+const HANDBOOK = `## Overview\n\n${prose(rng(21), 6)}\n\n## Pricing\n\n${prose(rng(22), 6)} narwhal pricing note.\n\n## Support\n\n${prose(rng(23), 6)}`;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ for (const [slug, body] of [['chat/session-1', SESSION], ['notes/handbook', HANDBOOK]] as const) {+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: body, timeline: slug === 'notes/handbook' ? '- 2026-01-02 narwhal timeline entry' : '', frontmatter: {} });+ await installFixtureChunks(engine, slug, await prepareMarkdownChunks({ compiled_truth: body, timeline: slug === 'notes/handbook' ? '- 2026-01-02 narwhal timeline entry' : '' }));+ }+ await engine.setConfig('search.mcp_keyword_only', 'true');+}, 240_000);++afterAll(async () => {+ await engine.disconnect();+}, 240_000);++describe('ops', () => {+ test('omitted return_unit leaves search output without delivery fields', async () => {+ lastMeta = null;+ const rows = await op('search').handler(ctxOf(), { query: 'narwhal' }) as SearchResult[];+ expect(rows.length).toBeGreaterThan(0);+ expect(rows.every(r => r.delivered === undefined)).toBe(true);+ expect((lastMeta as Record<string, unknown> | null)?.delivery).toBeUndefined();+ });++ test('every unit delivers through search with delivered + delivery meta', async () => {+ for (const unit of ['window', 'section', 'page', 'auto']) {+ lastMeta = null;+ const rows = await op('search').handler(ctxOf(), { query: 'narwhal', return_unit: unit, token_budget: 4000 }) as SearchResult[];+ expect(rows.length).toBeGreaterThan(0);+ expect(lastMeta!.delivery.requested_unit).toBe(unit);+ expect(lastMeta!.delivery.budget_used).toBeLessThanOrEqual(4000);+ for (const r of rows) {+ expect(r.delivered).toBeDefined();+ for (const s of r.delivered!.match_spans) expect(s.end).toBeLessThanOrEqual(r.chunk_text.length);+ }+ }+ });++ test('page evidence is byte-identical to the stored body (sanitized), on the real import path', async () => {+ const rows = await op('search').handler(ctxOf(), { query: 'narwhal', return_unit: 'page', token_budget: 32000 }) as SearchResult[];+ expect(rows.length).toBeGreaterThan(0);+ for (const r of rows) {+ const [page] = await engine.executeRaw<{ compiled_truth: string; timeline: string }>('SELECT compiled_truth, timeline FROM pages WHERE id = $1', [r.page_id]);+ expect(r.chunk_text).toBe(pageEvidenceText(page, true).text.trimEnd());+ }+ });++ test('auto takes the page branch for a conversation stored as type note', async () => {+ const rows = await op('search').handler(ctxOf(), { query: 'narwhal launch march', return_unit: 'auto', token_budget: 20000 }) as SearchResult[];+ const chat = rows.find(r => r.slug === 'chat/session-1')!;+ expect(chat.delivered!.unit).toBe('page');+ expect(chat.chunk_text).toContain('question 0 ');+ expect(chat.chunk_text).toContain('reply 23 ');+ });++ test('bad return_unit and return_window fail with invalid_params naming the fix', async () => {+ await expect(op('search').handler(ctxOf(), { query: 'x', return_unit: 'paragraph' })).rejects.toMatchObject({+ code: 'invalid_params', message: expect.stringContaining('chunk, window, section, page, auto'), suggestion: expect.stringContaining('"return_unit"'),+ });+ await expect(op('query').handler(ctxOf(), { query: 'x', return_unit: 'window', return_window: 7 })).rejects.toMatchObject({+ code: 'invalid_params', message: 'return_window must be an integer from 1 to 3 (got 7).', suggestion: expect.stringContaining('"return_window": 2'),+ });+ });++ test('detail low never adds timeline text', async () => {+ const low = await op('query').handler(ctxOf(), { query: 'narwhal pricing', return_unit: 'page', detail: 'low', expand: false }) as SearchResult[];+ const book = low.find(r => r.slug === 'notes/handbook')!;+ expect(book.chunk_text).not.toContain('narwhal timeline entry');+ const medium = await op('query').handler(ctxOf(), { query: 'narwhal pricing', return_unit: 'page', expand: false }) as SearchResult[];+ expect(medium.find(r => r.slug === 'notes/handbook')!.chunk_text).toContain('narwhal timeline entry');+ });++ test('snippet precedence: explicit snippet_chars > explicit unit > subagent default > config unit', async () => {+ const sub = ctxOf({ viaSubagent: true } as Partial<OperationContext>);+ const capped = await op('search').handler(sub, { query: 'narwhal', return_unit: 'page', snippet_chars: 120 }) as SearchResult[];+ expect(capped[0].chunk_text).toContain('[truncated');+ expect(capped[0].delivered!.truncated).toBe(true);+ expect(lastMeta!.delivery.fallbacks).toContain('snippet_cap');+ const explicit = await op('search').handler(sub, { query: 'narwhal', return_unit: 'page' }) as SearchResult[];+ expect(explicit[0].chunk_text).not.toContain('[truncated');+ expect(explicit[0].chunk_text.length).toBeGreaterThan(300);+ await engine.setConfig('search.return_unit', 'page');+ try {+ const subDefault = await op('search').handler(sub, { query: 'narwhal' }) as SearchResult[];+ expect(subDefault[0].delivered).toBeUndefined();+ expect(subDefault[0].chunk_text.length).toBeLessThanOrEqual(300 + 80);+ const human = await op('search').handler(ctxOf(), { query: 'narwhal' }) as SearchResult[];+ expect(human[0].delivered).toBeDefined();+ } finally {+ await engine.setConfig('search.return_unit', 'chunk');+ }+ });++ test('remote budgets clamp to search.return_budget_max_remote and say so', async () => {+ await op('search').handler(ctxOf({ remote: true }), { query: 'narwhal', return_unit: 'window', token_budget: 90000 });+ expect(lastMeta!.delivery.budget_tokens).toBe(32000);+ expect(lastMeta!.delivery.budget_clamped).toEqual({ requested: 90000, max: 32000 });+ expect(lastMeta!.delivery.fallbacks).toContain('budget_clamped');+ });++ test('recall keeps legacy fields and packing, adding delivered/delivery only when on', async () => {+ const off = await op('recall').handler(ctxOf(), { query: 'narwhal', budget_tokens: 5000 }) as Record<string, any>;+ expect(off.delivery).toBeUndefined();+ expect(off.results.every((r: Record<string, unknown>) => Object.keys(r).join(',') === 'slug,title,chunk,evidence,create_safety,provenance')).toBe(true);+ const on = await op('recall').handler(ctxOf(), { query: 'narwhal', budget_tokens: 5000, return_unit: 'page' }) as Record<string, any>;+ expect(on.delivery.requested_unit).toBe('page');+ expect(on.results[0].delivered.unit).toBe('page');+ expect(on.results[0].chunk.length).toBeGreaterThan(off.results[0].chunk.length);+ expect(on.budget_used).toBeLessThanOrEqual(5000);+ });++ test('query token_budget budgets the delivered evidence', async () => {+ const rows = await op('query').handler(ctxOf(), { query: 'narwhal', return_unit: 'page', token_budget: 900, expand: false }) as SearchResult[];+ expect(lastMeta!.delivery.budget_tokens).toBe(900);+ expect(lastMeta!.delivery.budget_used).toBeLessThanOrEqual(900);+ expect(rows.length).toBeGreaterThan(0);+ });++ test('assemble_evidence returns the same evidence as search for the same hits', async () => {+ const hits = await op('search').handler(ctxOf(), { query: 'narwhal' }) as SearchResult[];+ const viaSearch = await op('search').handler(ctxOf(), { query: 'narwhal', return_unit: 'section', token_budget: 3000 }) as SearchResult[];+ const out = 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: 'section', token_budget: 3000,+ }) as { results: SearchResult[]; unresolved: number[] };+ expect(out.unresolved).toEqual([]);+ expect(evidenceFingerprint(out.results)).toBe(evidenceFingerprint(viaSearch));+ const bad = await op('assemble_evidence').handler(ctxOf(), { hits: [{ source_id: 'nope', slug: 'chat/session-1', chunk_id: 1 }], return_unit: 'page' }) as { unresolved: number[] };+ expect(bad.unresolved).toEqual([0]);+ });++ test('think renders delivered blocks whole under think.return_unit, and only then', async () => {+ const prompts: string[] = [];+ const client = { create: async (params: { messages: Array<{ content: unknown }> }) => {+ prompts.push(JSON.stringify(params.messages));+ return { content: [{ type: 'text', text: '{"answer":"ok","citations":[],"gaps":[]}' }], usage: { input_tokens: 1, output_tokens: 1 } };+ } };+ await runThink(engine, { question: 'narwhal launch march', client: client as never, remote: false });+ expect(prompts[0]).not.toContain('reply 23 ');+ await engine.setConfig('search.return_unit', 'page');+ try {+ await runThink(engine, { question: 'narwhal launch march', client: client as never, remote: false });+ expect(prompts[1]).not.toContain('reply 23 ');+ await engine.setConfig('think.return_unit', 'page');+ const r = await runThink(engine, { question: 'narwhal launch march', client: client as never, remote: false });+ expect(prompts[2]).toContain('reply 23 ');+ expect(r.evidence_delivery?.requested_unit).toBe('page');+ } finally {+ await engine.setConfig('search.return_unit', 'chunk');+ await engine.setConfig('think.return_unit', 'chunk');+ }+ });++ test('renderPagesBlock verbatim mode passes delivered text through', () => {+ const text = 'x'.repeat(5000);+ const block = renderPagesBlock([{ slug: 'a/b', chunk_text: text } as SearchResult], 60000, 'q', { verbatim: true });+ expect(block).toContain(text);+ });++ 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();+ expect(deliveryVersionSkewWarning('query', { return_unit: 'chunk' }, {}, [])).toBeNull();+ expect(deliveryVersionSkewWarning('recall', { return_unit: 'page' }, null, { facts: [] })).toContain('ignored return_unit');+ });+});diff --git a/test/fixtures/export-consumer/consumer.ts b/test/fixtures/export-consumer/consumer.tsindex 4cfaf005a5..0087ec9c43 100644--- a/test/fixtures/export-consumer/consumer.ts+++ b/test/fixtures/export-consumer/consumer.ts@@ -35,6 +35,7 @@ import { IngestionTestHarness as e23 } from 'gbrain/ingestion/test-harness';import { GuardrailLoadError as e24 } from 'gbrain/core/guardrails';import { loadHeldOut as e25 } from 'gbrain/core/skillopt';import { LiveServeLockError as e26 } from 'gbrain/pglite-lock';+import { assembleEvidenceForHits as e27 } from 'gbrain/search/evidence-delivery';import type { BrainEngine } from 'gbrain/engine';import type { PageInput, SearchResult } from 'gbrain/types';import { PGLiteEngine } from 'gbrain/pglite-engine';@@ -67,6 +68,7 @@ export const RUNTIME_IMPORTS: readonly unknown[] = [e24,e25,e26,+ e27,];export function makeEngine(): BrainEngine {diff --git a/test/fixtures/goldens/cli/help-and-errors.json b/test/fixtures/goldens/cli/help-and-errors.jsonindex ee566b41ec..6762591713 100644--- a/test/fixtures/goldens/cli/help-and-errors.json+++ b/test/fixtures/goldens/cli/help-and-errors.json@@ -653,7 +653,7 @@"stdout": ["Usage: gbrain query <query> [options]","",- "Hybrid search with vector + keyword + multi-query expansion. Prefer `query` for concept / synonym / landscape questions ('all the X that do Y', 'the landscape of Z') — expansion recovers synonym- and outcome-phrased matches a single embedding misses. Still top-K, and the default count when `limit` is omitted depends on the configured search mode (10 conservative / 25 balanced / 50 tokenmax — see the `limit` param description); pass `limit` explicitly for a stable count regardless of mode. For exhaustive enumeration use list_pages; for exact known tokens `search` is cheaper (no expansion LLM call). For personal/emotional questions ('what's going on with me', 'anything notable', 'how am I feeling'), prefer get_recent_salience, find_anomalies, or get_recent_transcripts. Semantic search returns polished pages and misses recent activity bursts. Do NOT assume words like 'crazy', 'notable', or 'big' mean impressive — they often mean difficult or emotionally charged.",+ "Hybrid search with vector + keyword + multi-query expansion. Prefer `query` for concept / synonym / landscape questions ('all the X that do Y', 'the landscape of Z') — expansion recovers synonym- and outcome-phrased matches a single embedding misses. Still top-K, and the default count when `limit` is omitted depends on the configured search mode (10 conservative / 25 balanced / 50 tokenmax — see the `limit` param description); pass `limit` explicitly for a stable count regardless of mode. When the answer needs the surrounding conversation or section, pass `return_unit` ('page' / 'section' / 'window') to get that evidence in one call instead of get_page per hit. For exhaustive enumeration use list_pages; for exact known tokens `search` is cheaper (no expansion LLM call). For personal/emotional questions ('what's going on with me', 'anything notable', 'how am I feeling'), prefer get_recent_salience, find_anomalies, or get_recent_transcripts. Semantic search returns polished pages and misses recent activity bursts. Do NOT assume words like 'crazy', 'notable', or 'big' mean impressive — they often mean difficult or emotionally charged.","","Options:"," <query> Question or topic text for hybrid retrieval with expansion (e.g. 'agents that do web research'). This is the search text param — there is no `text` or `q` param. Optional ONLY because `image` is the alternative entry point; a call with neither fails with invalid_params.",@@ -663,6 +663,15 @@" --offset Skip first N results (for pagination)"," --types Filter results to pages whose `type` is in this list (e.g. ['person','company']). CLI: --types person,company. Applied at SQL level on every retrieval leg — the same filter `whoknows` uses. Stacks with all other filters."," --snippet-chars Cap each result's chunk_text at N characters (a \"… [truncated]\" marker names the get_page recovery move). 0 forces full text. Unset: subagent tool loops default to the agent.search_snippet_chars config (300; 0=full); every other caller gets full text. (#3800)",+ " --return-unit Evidence unit returned in each result's chunk_text (default: config search.return_unit, which defaults to 'chunk').",+ " 'chunk' — the ranked chunk only (~300-450 tokens per result).",+ " 'window' — the hit chunk plus return_window neighbor chunks each side (local context, ~3x chunk).",+ " 'section' — the enclosing markdown section, or the conversation rounds around the hit.",+ " 'page' — the whole page/session, capped. Use for multi-session or temporal questions where the answer needs the whole conversation.",+ " 'auto' — page for conversations and short pages, section or window for long curated pages.",+ "Non-chunk units return one result per page, packed into token_budget (default 6000; remote max 32000), with a `delivered` object (unit, chunk_ids, match_spans, tokens, truncated) per result and `delivery` in the response meta.",+ " --return-window Neighbor chunks on each side for return_unit 'window' (integer 1-3, default 1).",+ " --token-budget Token budget. Chunk mode: caps the cumulative chunk payload (results that would overflow are skipped). Non-chunk return_unit: the budget for delivered evidence (default search.return_budget_default = 6000; remote max search.return_budget_max_remote = 32000)."," --expand Request multi-query expansion (default: true in every search mode, regardless of search.expansion). Set false to opt out. Requires configured embedding and expansion providers; a cloud expander receives the query and may charge for the call. Response metadata expansion_applied reports whether variants were actually used."," --detail Result detail level: low (compiled truth only), medium (default, all with dedup), high (all chunks)"," --mode Search mode (conservative|balanced|tokenmax). Local callers only; remote uses configured mode.",diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.jsonindex c85ab9077a..ffae3761bd 100644--- a/test/fixtures/goldens/cli/tools-json.json+++ b/test/fixtures/goldens/cli/tools-json.json@@ -2,8 +2,8 @@"golden": {"exitCode": 0,"stderr": "",- "stdoutBytes": 191990,- "stdoutSha256": "d8c3c5a0179f54f551ec6a37b3c011a30910605a9d08db0df63fa0680247e463",+ "stdoutBytes": 198725,+ "stdoutSha256": "3559128ade73b7bee9f7ee38013049ac8757cc66f8c2cf6ea639f9f526a11115","toolNames": ["remember","entity",@@ -22,6 +22,7 @@"cancel_write_request","search","query",+ "assemble_evidence","search_stats","search_modes","search_tune",@@ -739,7 +740,7 @@}},{- "description": "Cheap hybrid search (vector + keyword + RRF) with no LLM expansion. Best for exact known tokens, names, and structured-field lookups. A populated result set is NOT proof of coverage — for concept / synonym / landscape questions use `query` (adds multi-query expansion); for exhaustive enumeration use list_pages pagination. For personal/emotional questions, prefer get_recent_salience or find_anomalies — they surface activity bursts without needing a search term. For code-symbol questions (callers, callees, definitions, blast radius), use code_callers / code_callees / code_def / code_refs instead — those return structural graph data, not text chunks. For agent memory reads (saved facts + budget-packed retrieval), prefer the `recall` verb.",+ "description": "Cheap hybrid search (vector + keyword + RRF) with no LLM expansion. Best for exact known tokens, names, and structured-field lookups. A populated result set is NOT proof of coverage — for concept / synonym / landscape questions use `query` (adds multi-query expansion); for exhaustive enumeration use list_pages pagination. Pass `return_unit` ('window' / 'section' / 'page') for whole evidence instead of chunks. For personal/emotional questions, prefer get_recent_salience or find_anomalies — they surface activity bursts without needing a search term. For code-symbol questions (callers, callees, definitions, blast radius), use code_callers / code_callees / code_def / code_refs instead — those return structural graph data, not text chunks. For agent memory reads (saved facts + budget-packed retrieval), prefer the `recall` verb.","name": "search","parameters": {"limit": "number?",@@ -747,9 +748,12 @@"offset": "number?","query": "string","recency": "string?",+ "return_unit": "string?",+ "return_window": "number?","salience": "string?","snippet_chars": "number?","source_id": "string?",+ "token_budget": "number?","types": "array?"},"schema": {@@ -779,6 +783,21 @@],"type": "string"},+ "return_unit": {+ "description": "Evidence unit returned in each result's chunk_text (default: config search.return_unit, which defaults to 'chunk').\n 'chunk' — the ranked chunk only (~300-450 tokens per result).\n 'window' — the hit chunk plus return_window neighbor chunks each side (local context, ~3x chunk).\n 'section' — the enclosing markdown section, or the conversation rounds around the hit.\n 'page' — the whole page/session, capped. Use for multi-session or temporal questions where the answer needs the whole conversation.\n 'auto' — page for conversations and short pages, section or window for long curated pages.\nNon-chunk units return one result per page, packed into token_budget (default 6000; remote max 32000), with a `delivered` object (unit, chunk_ids, match_spans, tokens, truncated) per result and `delivery` in the response meta.",+ "enum": [+ "chunk",+ "window",+ "section",+ "page",+ "auto"+ ],+ "type": "string"+ },+ "return_window": {+ "description": "Neighbor chunks on each side for return_unit 'window' (integer 1-3, default 1).",+ "type": "number"+ },"salience": {"description": "Salience boost (emotional_weight + take_count, no time component): 'off' | 'on' | 'strong'. Omit and gbrain auto-detects from query text. Independent of `recency`.","enum": [@@ -796,6 +815,10 @@"description": "Scope search to a single source. Defaults to OperationContext.sourceId (set from CLI --source / GBRAIN_SOURCE / .gbrain-source dotfile); when unset, an unqualified read spans every federated source. Pass '__all__' to span every source for trusted local callers; for remote callers '__all__' spans only your granted sources.","type": "string"},+ "token_budget": {+ "description": "Token budget for delivered evidence when return_unit is not 'chunk' (default search.return_budget_default = 6000). Ignored in chunk mode.",+ "type": "number"+ },"types": {"description": "Filter results to pages whose `type` is in this list (e.g. ['person','company']). CLI: --types person,company. Applied at SQL level on every retrieval leg — the same filter `whoknows` uses. Stacks with all other filters.","items": {@@ -811,7 +834,7 @@}},{- "description": "Hybrid search with vector + keyword + multi-query expansion. Prefer `query` for concept / synonym / landscape questions ('all the X that do Y', 'the landscape of Z') — expansion recovers synonym- and outcome-phrased matches a single embedding misses. Still top-K, and the default count when `limit` is omitted depends on the configured search mode (10 conservative / 25 balanced / 50 tokenmax — see the `limit` param description); pass `limit` explicitly for a stable count regardless of mode. For exhaustive enumeration use list_pages; for exact known tokens `search` is cheaper (no expansion LLM call). For personal/emotional questions ('what's going on with me', 'anything notable', 'how am I feeling'), prefer get_recent_salience, find_anomalies, or get_recent_transcripts. Semantic search returns polished pages and misses recent activity bursts. Do NOT assume words like 'crazy', 'notable', or 'big' mean impressive — they often mean difficult or emotionally charged.",+ "description": "Hybrid search with vector + keyword + multi-query expansion. Prefer `query` for concept / synonym / landscape questions ('all the X that do Y', 'the landscape of Z') — expansion recovers synonym- and outcome-phrased matches a single embedding misses. Still top-K, and the default count when `limit` is omitted depends on the configured search mode (10 conservative / 25 balanced / 50 tokenmax — see the `limit` param description); pass `limit` explicitly for a stable count regardless of mode. When the answer needs the surrounding conversation or section, pass `return_unit` ('page' / 'section' / 'window') to get that evidence in one call instead of get_page per hit. For exhaustive enumeration use list_pages; for exact known tokens `search` is cheaper (no expansion LLM call). For personal/emotional questions ('what's going on with me', 'anything notable', 'how am I feeling'), prefer get_recent_salience, find_anomalies, or get_recent_transcripts. Semantic search returns polished pages and misses recent activity bursts. Do NOT assume words like 'crazy', 'notable', or 'big' mean impressive — they often mean difficult or emotionally charged.","name": "query","parameters": {"adaptive_return": "boolean?",@@ -830,11 +853,14 @@"query": "string?","recency": "string?","relational": "boolean?",+ "return_unit": "string?",+ "return_window": "number?","salience": "string?","since": "string?","snippet_chars": "number?","source_id": "string?","symbol_kind": "string?",+ "token_budget": "number?","types": "array?","until": "string?","walk_depth": "number?"@@ -916,6 +942,21 @@"description": "v0.43 — relational recall arm. SMART DEFAULT (on in balanced/tokenmax). When the question is about a RELATIONSHIP ('who invested in widget-co', 'who introduced me to alice', 'what connects fund-a and fund-b'), the brain resolves the named entity and walks its typed-edge graph (invested_in, works_at, founded, …), surfacing the answer even when no passage mentions both sides. Pure no-op for non-relational questions. Pass FALSE to force lexical/vector-only retrieval (e.g. debugging why a graph answer appeared). You almost never set this.","type": "boolean"},+ "return_unit": {+ "description": "Evidence unit returned in each result's chunk_text (default: config search.return_unit, which defaults to 'chunk').\n 'chunk' — the ranked chunk only (~300-450 tokens per result).\n 'window' — the hit chunk plus return_window neighbor chunks each side (local context, ~3x chunk).\n 'section' — the enclosing markdown section, or the conversation rounds around the hit.\n 'page' — the whole page/session, capped. Use for multi-session or temporal questions where the answer needs the whole conversation.\n 'auto' — page for conversations and short pages, section or window for long curated pages.\nNon-chunk units return one result per page, packed into token_budget (default 6000; remote max 32000), with a `delivered` object (unit, chunk_ids, match_spans, tokens, truncated) per result and `delivery` in the response meta.",+ "enum": [+ "chunk",+ "window",+ "section",+ "page",+ "auto"+ ],+ "type": "string"+ },+ "return_window": {+ "description": "Neighbor chunks on each side for return_unit 'window' (integer 1-3, default 1).",+ "type": "number"+ },"salience": {"description": "v0.29.1 salience boost — emotional_weight + take_count, NO time component.\n 'off' — default for entity / canonical / definitional queries\n 'on' — surface emotionally-weighted + take-rich pages\n 'strong' — aggressive mattering tilt\nOmit and gbrain auto-detects from query text. Independent of `recency`.","enum": [@@ -941,6 +982,10 @@"description": "Filter to chunks where content_chunks.symbol_type matches (e.g., function, class, method, type, interface)","type": "string"},+ "token_budget": {+ "description": "Token budget. Chunk mode: caps the cumulative chunk payload (results that would overflow are skipped). Non-chunk return_unit: the budget for delivered evidence (default search.return_budget_default = 6000; remote max search.return_budget_max_remote = 32000).",+ "type": "number"+ },"types": {"description": "Filter results to pages whose `type` is in this list (e.g. ['person','company']). CLI: --types person,company. Applied at SQL level on every retrieval leg — the same filter `whoknows` uses. Stacks with all other filters.","items": {@@ -961,6 +1006,60 @@"type": "object"}},+ {+ "description": "Deliver whole evidence for an ordered list of search hits (each {source_id, slug, chunk_id} from a prior search/query result): the same windows, sections or pages `query` returns with return_unit, packed into token_budget. Use it to widen hits you already have instead of calling get_page per hit. Returns { results, delivery, unresolved }; results carry chunk_text (the evidence) and `delivered`.",+ "name": "assemble_evidence",+ "parameters": {+ "detail": "string?",+ "hits": "array",+ "return_unit": "string?",+ "return_window": "number?",+ "token_budget": "number?"+ },+ "schema": {+ "properties": {+ "detail": {+ "description": "As query: 'low' delivers compiled truth only (no timeline text).",+ "enum": [+ "low",+ "medium",+ "high"+ ],+ "type": "string"+ },+ "hits": {+ "description": "Ordered hits, best first (max 50): [{ \"source_id\": \"default\", \"slug\": \"chat/session-0412\", \"chunk_id\": 8812 }]. chunk_id 0 addresses the page's first chunk.",+ "items": {+ "type": "object"+ },+ "type": "array"+ },+ "return_unit": {+ "description": "Evidence unit: 'chunk' | 'window' | 'section' | 'page' | 'auto' (default 'page').",+ "enum": [+ "chunk",+ "window",+ "section",+ "page",+ "auto"+ ],+ "type": "string"+ },+ "return_window": {+ "description": "Neighbor chunks on each side for return_unit 'window' (integer 1-3, default 1).",+ "type": "number"+ },+ "token_budget": {+ "description": "Token budget for the delivered evidence (default search.return_budget_default = 6000; remote max 32000).",+ "type": "number"+ }+ },+ "required": [+ "hits"+ ],+ "type": "object"+ }+ },{"description": "Search observability over a window: cache hit rate, intent/mode mix, budget drops, rank-1 score drift, graph-signals failure counts. Same payload as the search-stats dashboard JSON. Coverage caveat: telemetry is best-effort (short-lived CLI calls may not flush), so zero counts can reflect the coverage gap rather than zero usage.","name": "search_stats",@@ -4131,6 +4230,8 @@"include_pending": "boolean?","limit": "number?","query": "string?",+ "return_unit": "string?",+ "return_window": "number?","session_id": "string?","since": "string?","source_id": "string?",@@ -4151,7 +4252,7 @@"type": "number"},"entity": {- "description": "Entity slug (canonical). Returns facts about this entity newest first.",+ "description": "Entity slug (canonical). Returns facts about this entity newest first, each labelled with its source_id. Across several granted sources, same-slug entities that no entity-identity group links are different entities: facts comes back empty and ambiguous_entity names each (source_id, entity_slug); pass source_id to read one.","type": "string"},"grep": {@@ -4174,6 +4275,21 @@"description": "MEMORY_VERBS v1: free-text retrieval over pages (hybrid search arm). Response adds results[] (slug, title, chunk, evidence, create_safety, provenance). Combinable with entity (both arms run). Degrades to keyword-only search when no embedding provider is configured (search_degraded notes it; never an error).","type": "string"},+ "return_unit": {+ "description": "Evidence unit for the results[] arm (needs `query`; default config search.return_unit = 'chunk'). 'window' adds neighbor chunks, 'section' the enclosing section or conversation rounds, 'page' the whole page/session (best for multi-session questions), 'auto' picks per page. Non-chunk units return one result per page with `delivered` metadata and a top-level `delivery` block; the evidence is budgeted by budget_tokens (default 6000) and then packed by recall's usual rules.",+ "enum": [+ "chunk",+ "window",+ "section",+ "page",+ "auto"+ ],+ "type": "string"+ },+ "return_window": {+ "description": "Neighbor chunks on each side for return_unit 'window' (integer 1-3, default 1).",+ "type": "number"+ },"session_id": {"description": "Source session id (e.g. topic-A). Returns facts captured in that session.","type": "string"diff --git a/test/fixtures/goldens/evidence-delivery/off-path.json b/test/fixtures/goldens/evidence-delivery/off-path.jsonnew file mode 100644index 0000000000..71d522ed17--- /dev/null+++ b/test/fixtures/goldens/evidence-delivery/off-path.json@@ -0,0 +1,22 @@+{+ "search": "{\"result\":[{\"slug\":\"chat/session-a\",\"page_id\":1,\"title\":\"chat/session-a\",\"type\":\"note\",\"chunk_text\":\"**user:** turn 0 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\n\\n**assistant:** answer 0 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines \\n\\n**user:** turn 1 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\n\\n**assistant:** answer 1 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines \\n\\n**user:** turn 2 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\n\\n**assistant:** answer 2 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines \\n\\n**user:** turn 3 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\n\\n**assistant:** answer 3 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines \\n\\n**user:** turn 4 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\n\\n**assistant:** answer 4 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines \\n\\n**user:** turn 5 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\n\\n**assistant:** answer 5 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines\",\"chunk_source\":\"compiled_truth\",\"chunk_id\":1,\"chunk_index\":0,\"score\":0.36266231536865234,\"stale\":false,\"source_id\":\"default\",\"effective_date\":null,\"effective_date_source\":null,\"keyword_hit\":true,\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY2hhdC9zZXNzaW9uLWEiXQ\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\"},{\"slug\":\"notes/ocelot-handbook\",\"page_id\":2,\"title\":\"notes/ocelot-handbook\",\"type\":\"note\",\"chunk_text\":\"## Overview\\n\\nThe ocelot program. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. \\n\\n## Pricing\\n\\nOcelot pricing is tiered. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here.\",\"chunk_source\":\"compiled_truth\",\"chunk_id\":4,\"chunk_index\":0,\"score\":0.3039635419845581,\"stale\":false,\"source_id\":\"default\",\"effective_date\":null,\"effective_date_source\":null,\"keyword_hit\":true,\"id\":\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvb2NlbG90LWhhbmRib29rIl0\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\"},{\"slug\":\"notes/ocelot-private\",\"page_id\":3,\"title\":\"notes/ocelot-private\",\"type\":\"note\",\"chunk_text\":\"Private ocelot memo body.\",\"chunk_source\":\"compiled_truth\",\"chunk_id\":6,\"chunk_index\":0,\"score\":0.2431708425283432,\"stale\":false,\"source_id\":\"default\",\"effective_date\":null,\"effective_date_source\":null,\"keyword_hit\":true,\"id\":\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvb2NlbG90LXByaXZhdGUiXQ\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\"},{\"slug\":\"notes/short\",\"page_id\":4,\"title\":\"notes/short\",\"type\":\"note\",\"chunk_text\":\"A short ocelot note.\",\"chunk_source\":\"compiled_truth\",\"chunk_id\":7,\"chunk_index\":0,\"score\":0.2431708425283432,\"stale\":false,\"source_id\":\"default\",\"effective_date\":null,\"effective_date_source\":null,\"keyword_hit\":true,\"id\":\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvc2hvcnQiXQ\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\"}],\"meta\":[{\"key\":\"retrieval\",\"value\":{\"returned_count\":4,\"retrieved_count\":4,\"projection_readiness\":{\"status\":\"ready\",\"ready\":true}}}]}",+ "search-remote": "{\"result\":[{\"slug\":\"notes/ocelot-handbook\",\"page_id\":2,\"title\":\"notes/ocelot-handbook\",\"type\":\"note\",\"chunk_text\":\"## Overview\\n\\nThe ocelot program. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. \\n\\n## Pricing\\n\\nOcelot pricing is tiered. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here.\",\"chunk_source\":\"compiled_truth\",\"chunk_id\":4,\"chunk_index\":0,\"score\":0.8520091772079468,\"stale\":false,\"source_id\":\"default\",\"effective_date\":null,\"effective_date_source\":null,\"keyword_hit\":true,\"id\":\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvb2NlbG90LWhhbmRib29rIl0\",\"evidence\":\"keyword_exact\",\"create_safety\":\"probable\"}],\"meta\":[{\"key\":\"retrieval\",\"value\":{\"returned_count\":1,\"retrieved_count\":1,\"projection_readiness\":{\"status\":\"ready\",\"ready\":true}}}]}",+ "search-subagent": "{\"result\":[{\"slug\":\"chat/session-a\",\"page_id\":1,\"title\":\"chat/session-a\",\"type\":\"note\",\"chunk_text\":\"**user:** turn 0 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\n\\n**assistant:** answer 0 owners and timelines owners and timelines owners and timelines owners an… [truncated 2337 chars — get_page chat/session-a for full text]\",\"chunk_source\":\"compiled_truth\",\"chunk_id\":1,\"chunk_index\":0,\"score\":0.36266231536865234,\"stale\":false,\"source_id\":\"default\",\"effective_date\":null,\"effective_date_source\":null,\"keyword_hit\":true,\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY2hhdC9zZXNzaW9uLWEiXQ\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\"},{\"slug\":\"notes/ocelot-handbook\",\"page_id\":2,\"title\":\"notes/ocelot-handbook\",\"type\":\"note\",\"chunk_text\":\"## Overview\\n\\nThe ocelot program. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for t… [truncated 1692 chars — get_page notes/ocelot-handbook for full text]\",\"chunk_source\":\"compiled_truth\",\"chunk_id\":4,\"chunk_index\":0,\"score\":0.3039635419845581,\"stale\":false,\"source_id\":\"default\",\"effective_date\":null,\"effective_date_source\":null,\"keyword_hit\":true,\"id\":\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvb2NlbG90LWhhbmRib29rIl0\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\"},{\"slug\":\"notes/ocelot-private\",\"page_id\":3,\"title\":\"notes/ocelot-private\",\"type\":\"note\",\"chunk_text\":\"Private ocelot memo body.\",\"chunk_source\":\"compiled_truth\",\"chunk_id\":6,\"chunk_index\":0,\"score\":0.2431708425283432,\"stale\":false,\"source_id\":\"default\",\"effective_date\":null,\"effective_date_source\":null,\"keyword_hit\":true,\"id\":\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvb2NlbG90LXByaXZhdGUiXQ\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\"},{\"slug\":\"notes/short\",\"page_id\":4,\"title\":\"notes/short\",\"type\":\"note\",\"chunk_text\":\"A short ocelot note.\",\"chunk_source\":\"compiled_truth\",\"chunk_id\":7,\"chunk_index\":0,\"score\":0.2431708425283432,\"stale\":false,\"source_id\":\"default\",\"effective_date\":null,\"effective_date_source\":null,\"keyword_hit\":true,\"id\":\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvc2hvcnQiXQ\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\"}],\"meta\":[{\"key\":\"retrieval\",\"value\":{\"returned_count\":4,\"retrieved_count\":4,\"projection_readiness\":{\"status\":\"ready\",\"ready\":true}}}]}",+ "query": "{\"result\":[{\"slug\":\"notes/ocelot-handbook\",\"page_id\":2,\"title\":\"notes/ocelot-handbook\",\"type\":\"note\",\"chunk_text\":\"## Overview\\n\\nThe ocelot program. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. \\n\\n## Pricing\\n\\nOcelot pricing is tiered. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here.\",\"chunk_source\":\"compiled_truth\",\"chunk_id\":4,\"chunk_index\":0,\"score\":1,\"stale\":false,\"source_id\":\"default\",\"effective_date\":null,\"effective_date_source\":null,\"keyword_hit\":true,\"base_score\":1,\"evidence\":\"keyword_exact\",\"create_safety\":\"probable\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvb2NlbG90LWhhbmRib29rIl0\"}],\"meta\":[{\"key\":\"retrieval\",\"value\":{\"returned_count\":1,\"retrieved_count\":1,\"vector_enabled\":false,\"expansion_applied\":false,\"cache\":\"disabled\",\"token_budget\":{\"budget\":12000,\"used\":504,\"dropped\":0,\"kept\":1},\"degraded\":[{\"stage\":\"embed_unavailable\",\"reason\":\"no_provider\"}],\"projection_readiness\":{\"status\":\"ready\",\"ready\":true},\"crag\":{\"confidence\":\"moderate\",\"reason\":\"keyword_exact_top\",\"query_shape\":\"factual\"}}}]}",+ "query-budget": "{\"result\":[{\"slug\":\"notes/ocelot-handbook\",\"page_id\":2,\"title\":\"notes/ocelot-handbook\",\"type\":\"note\",\"chunk_text\":\"## Overview\\n\\nThe ocelot program. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. \\n\\n## Pricing\\n\\nOcelot pricing is tiered. Pricing details repeat here. Pricing details repeat h\",\"chunk_source\":\"compiled_truth\",\"chunk_id\":4,\"chunk_index\":0,\"score\":1,\"stale\":false,\"source_id\":\"default\",\"effective_date\":null,\"effective_date_source\":null,\"keyword_hit\":true,\"base_score\":1,\"evidence\":\"keyword_exact\",\"create_safety\":\"probable\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvb2NlbG90LWhhbmRib29rIl0\"}],\"meta\":[{\"key\":\"retrieval\",\"value\":{\"returned_count\":1,\"retrieved_count\":4,\"vector_enabled\":false,\"expansion_applied\":false,\"cache\":\"disabled\",\"token_budget\":{\"budget\":300,\"used\":300,\"dropped\":3,\"kept\":1,\"truncated\":true},\"degraded\":[{\"stage\":\"embed_unavailable\",\"reason\":\"no_provider\"},{\"stage\":\"budget_truncated\",\"reason\":\"first_result_truncated\"}],\"projection_readiness\":{\"status\":\"ready\",\"ready\":true},\"crag\":{\"confidence\":\"moderate\",\"reason\":\"keyword_exact_top\",\"query_shape\":\"factual\"}}}]}",+ "query-low": "{\"result\":[{\"slug\":\"notes/ocelot-handbook\",\"page_id\":2,\"title\":\"notes/ocelot-handbook\",\"type\":\"note\",\"chunk_text\":\"## Overview\\n\\nThe ocelot program. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. \\n\\n## Pricing\\n\\nOcelot pricing is tiered. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here.\",\"chunk_source\":\"compiled_truth\",\"chunk_id\":4,\"chunk_index\":0,\"score\":2,\"stale\":false,\"source_id\":\"default\",\"effective_date\":null,\"effective_date_source\":null,\"keyword_hit\":true,\"base_score\":2,\"evidence\":\"keyword_exact\",\"create_safety\":\"probable\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvb2NlbG90LWhhbmRib29rIl0\"}],\"meta\":[{\"key\":\"retrieval\",\"value\":{\"returned_count\":1,\"retrieved_count\":1,\"vector_enabled\":false,\"expansion_applied\":false,\"cache\":\"disabled\",\"token_budget\":{\"budget\":12000,\"used\":504,\"dropped\":0,\"kept\":1},\"degraded\":[{\"stage\":\"embed_unavailable\",\"reason\":\"no_provider\"}],\"projection_readiness\":{\"status\":\"ready\",\"ready\":true},\"crag\":{\"confidence\":\"moderate\",\"reason\":\"keyword_exact_top\",\"query_shape\":\"factual\"}}}]}",+ "recall": "{\"result\":{\"facts\":[],\"total\":0,\"protocol_version\":1,\"results\":[{\"slug\":\"chat/session-a\",\"title\":\"chat/session-a\",\"chunk\":\"**user:** turn 0 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\n\\n**assistant:** answer 0 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines \\n\\n**user:** turn 1 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\n\\n**assistant:** answer 1 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines \\n\\n**user:** turn 2 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\n\\n**assistant:** answer 2 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines \\n\\n**user:** turn 3 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\n\\n**assistant:** answer 3 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines \\n\\n**user:** turn 4 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\n\\n**assistant:** answer 4 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines \\n\\n**user:** turn 5 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\n\\n**assistant:** answer 5 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"provenance\":\"chat/session-a\"},{\"slug\":\"notes/ocelot-handbook\",\"title\":\"notes/ocelot-handbook\",\"chunk\":\"## Overview\\n\\nThe ocelot program. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. \\n\\n## Pricing\\n\\nOcelot pricing is tiered. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here.\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"provenance\":\"notes/ocelot-handbook\"},{\"slug\":\"notes/ocelot-private\",\"title\":\"notes/ocelot-private\",\"chunk\":\"Private ocelot memo body.\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"provenance\":\"notes/ocelot-private\"},{\"slug\":\"notes/short\",\"title\":\"notes/short\",\"chunk\":\"A short ocelot note.\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"provenance\":\"notes/short\"}],\"search_degraded\":\"keyword_only_no_embedding_provider\"},\"meta\":[]}",+ "recall-budget": "{\"result\":{\"facts\":[],\"total\":0,\"protocol_version\":1,\"results\":[{\"slug\":\"chat/session-a\",\"title\":\"chat/session-a\",\"chunk\":\"**user:** turn 0 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\n\\n**assistant:** answer 0 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines \\n\\n**user:** turn 1 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\n\\n**assistant:** answer 1 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines \\n\\n**user:** turn 2 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\n\\n**assistant:** answer 2 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines \\n\\n**user:** turn 3 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\n\\n**assistant:** answer 3 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines \\n\\n**user:** turn 4 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\n\\n**assistant:** answer 4 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines \\n\\n**user:** turn 5 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\n\\n**assistant:** answer 5 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"provenance\":\"chat/session-a\"},{\"slug\":\"notes/ocelot-handbook\",\"title\":\"notes/ocelot-handbook\",\"chunk\":\"## Overview\\n\\nThe ocelot program. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. \\n\\n## Pricing\\n\\nOcelot pricing is tiered. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here.\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"provenance\":\"notes/ocelot-handbook\"},{\"slug\":\"notes/ocelot-private\",\"title\":\"notes/ocelot-private\",\"chunk\":\"Private ocelot memo body.\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"provenance\":\"notes/ocelot-private\"},{\"slug\":\"notes/short\",\"title\":\"notes/short\",\"chunk\":\"A short ocelot note.\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"provenance\":\"notes/short\"}],\"search_degraded\":\"keyword_only_no_embedding_provider\",\"budget_tokens\":1500,\"budget_used\":1188,\"dropped_count\":0,\"budget_packing\":{\"policy\":\"query_first\",\"applied\":true,\"reason\":\"packed\",\"facts\":{\"candidates\":0,\"kept\":0,\"dropped\":0,\"used\":0},\"results\":{\"candidates\":4,\"kept\":4,\"dropped\":0,\"used\":1188}}},\"meta\":[]}",+ "search:chunk": "{\"result\":[{\"slug\":\"chat/session-a\",\"page_id\":1,\"title\":\"chat/session-a\",\"type\":\"note\",\"chunk_text\":\"**user:** turn 0 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\n\\n**assistant:** answer 0 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines \\n\\n**user:** turn 1 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\n\\n**assistant:** answer 1 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines \\n\\n**user:** turn 2 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\n\\n**assistant:** answer 2 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines \\n\\n**user:** turn 3 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\n\\n**assistant:** answer 3 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines \\n\\n**user:** turn 4 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\n\\n**assistant:** answer 4 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines \\n\\n**user:** turn 5 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\n\\n**assistant:** answer 5 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines\",\"chunk_source\":\"compiled_truth\",\"chunk_id\":1,\"chunk_index\":0,\"score\":0.36266231536865234,\"stale\":false,\"source_id\":\"default\",\"effective_date\":null,\"effective_date_source\":null,\"keyword_hit\":true,\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY2hhdC9zZXNzaW9uLWEiXQ\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\"},{\"slug\":\"notes/ocelot-handbook\",\"page_id\":2,\"title\":\"notes/ocelot-handbook\",\"type\":\"note\",\"chunk_text\":\"## Overview\\n\\nThe ocelot program. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. \\n\\n## Pricing\\n\\nOcelot pricing is tiered. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here.\",\"chunk_source\":\"compiled_truth\",\"chunk_id\":4,\"chunk_index\":0,\"score\":0.3039635419845581,\"stale\":false,\"source_id\":\"default\",\"effective_date\":null,\"effective_date_source\":null,\"keyword_hit\":true,\"id\":\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvb2NlbG90LWhhbmRib29rIl0\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\"},{\"slug\":\"notes/ocelot-private\",\"page_id\":3,\"title\":\"notes/ocelot-private\",\"type\":\"note\",\"chunk_text\":\"Private ocelot memo body.\",\"chunk_source\":\"compiled_truth\",\"chunk_id\":6,\"chunk_index\":0,\"score\":0.2431708425283432,\"stale\":false,\"source_id\":\"default\",\"effective_date\":null,\"effective_date_source\":null,\"keyword_hit\":true,\"id\":\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvb2NlbG90LXByaXZhdGUiXQ\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\"},{\"slug\":\"notes/short\",\"page_id\":4,\"title\":\"notes/short\",\"type\":\"note\",\"chunk_text\":\"A short ocelot note.\",\"chunk_source\":\"compiled_truth\",\"chunk_id\":7,\"chunk_index\":0,\"score\":0.2431708425283432,\"stale\":false,\"source_id\":\"default\",\"effective_date\":null,\"effective_date_source\":null,\"keyword_hit\":true,\"id\":\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvc2hvcnQiXQ\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\"}],\"meta\":[{\"key\":\"retrieval\",\"value\":{\"returned_count\":4,\"retrieved_count\":4,\"projection_readiness\":{\"status\":\"ready\",\"ready\":true}}}]}",+ "search-remote:chunk": "{\"result\":[{\"slug\":\"notes/ocelot-handbook\",\"page_id\":2,\"title\":\"notes/ocelot-handbook\",\"type\":\"note\",\"chunk_text\":\"## Overview\\n\\nThe ocelot program. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. \\n\\n## Pricing\\n\\nOcelot pricing is tiered. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here.\",\"chunk_source\":\"compiled_truth\",\"chunk_id\":4,\"chunk_index\":0,\"score\":0.8520091772079468,\"stale\":false,\"source_id\":\"default\",\"effective_date\":null,\"effective_date_source\":null,\"keyword_hit\":true,\"id\":\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvb2NlbG90LWhhbmRib29rIl0\",\"evidence\":\"keyword_exact\",\"create_safety\":\"probable\"}],\"meta\":[{\"key\":\"retrieval\",\"value\":{\"returned_count\":1,\"retrieved_count\":1,\"projection_readiness\":{\"status\":\"ready\",\"ready\":true}}}]}",+ "search-subagent:chunk": "{\"result\":[{\"slug\":\"chat/session-a\",\"page_id\":1,\"title\":\"chat/session-a\",\"type\":\"note\",\"chunk_text\":\"**user:** turn 0 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\n\\n**assistant:** answer 0 owners and timelines owners and timelines owners and timelines owners an… [truncated 2337 chars — get_page chat/session-a for full text]\",\"chunk_source\":\"compiled_truth\",\"chunk_id\":1,\"chunk_index\":0,\"score\":0.36266231536865234,\"stale\":false,\"source_id\":\"default\",\"effective_date\":null,\"effective_date_source\":null,\"keyword_hit\":true,\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY2hhdC9zZXNzaW9uLWEiXQ\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\"},{\"slug\":\"notes/ocelot-handbook\",\"page_id\":2,\"title\":\"notes/ocelot-handbook\",\"type\":\"note\",\"chunk_text\":\"## Overview\\n\\nThe ocelot program. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for t… [truncated 1692 chars — get_page notes/ocelot-handbook for full text]\",\"chunk_source\":\"compiled_truth\",\"chunk_id\":4,\"chunk_index\":0,\"score\":0.3039635419845581,\"stale\":false,\"source_id\":\"default\",\"effective_date\":null,\"effective_date_source\":null,\"keyword_hit\":true,\"id\":\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvb2NlbG90LWhhbmRib29rIl0\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\"},{\"slug\":\"notes/ocelot-private\",\"page_id\":3,\"title\":\"notes/ocelot-private\",\"type\":\"note\",\"chunk_text\":\"Private ocelot memo body.\",\"chunk_source\":\"compiled_truth\",\"chunk_id\":6,\"chunk_index\":0,\"score\":0.2431708425283432,\"stale\":false,\"source_id\":\"default\",\"effective_date\":null,\"effective_date_source\":null,\"keyword_hit\":true,\"id\":\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvb2NlbG90LXByaXZhdGUiXQ\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\"},{\"slug\":\"notes/short\",\"page_id\":4,\"title\":\"notes/short\",\"type\":\"note\",\"chunk_text\":\"A short ocelot note.\",\"chunk_source\":\"compiled_truth\",\"chunk_id\":7,\"chunk_index\":0,\"score\":0.2431708425283432,\"stale\":false,\"source_id\":\"default\",\"effective_date\":null,\"effective_date_source\":null,\"keyword_hit\":true,\"id\":\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvc2hvcnQiXQ\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\"}],\"meta\":[{\"key\":\"retrieval\",\"value\":{\"returned_count\":4,\"retrieved_count\":4,\"projection_readiness\":{\"status\":\"ready\",\"ready\":true}}}]}",+ "query:chunk": "{\"result\":[{\"slug\":\"notes/ocelot-handbook\",\"page_id\":2,\"title\":\"notes/ocelot-handbook\",\"type\":\"note\",\"chunk_text\":\"## Overview\\n\\nThe ocelot program. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. \\n\\n## Pricing\\n\\nOcelot pricing is tiered. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here.\",\"chunk_source\":\"compiled_truth\",\"chunk_id\":4,\"chunk_index\":0,\"score\":1,\"stale\":false,\"source_id\":\"default\",\"effective_date\":null,\"effective_date_source\":null,\"keyword_hit\":true,\"base_score\":1,\"evidence\":\"keyword_exact\",\"create_safety\":\"probable\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvb2NlbG90LWhhbmRib29rIl0\"}],\"meta\":[{\"key\":\"retrieval\",\"value\":{\"returned_count\":1,\"retrieved_count\":1,\"vector_enabled\":false,\"expansion_applied\":false,\"cache\":\"disabled\",\"token_budget\":{\"budget\":12000,\"used\":504,\"dropped\":0,\"kept\":1},\"degraded\":[{\"stage\":\"embed_unavailable\",\"reason\":\"no_provider\"}],\"projection_readiness\":{\"status\":\"ready\",\"ready\":true},\"crag\":{\"confidence\":\"moderate\",\"reason\":\"keyword_exact_top\",\"query_shape\":\"factual\"}}}]}",+ "query-budget:chunk": "{\"result\":[{\"slug\":\"notes/ocelot-handbook\",\"page_id\":2,\"title\":\"notes/ocelot-handbook\",\"type\":\"note\",\"chunk_text\":\"## Overview\\n\\nThe ocelot program. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. \\n\\n## Pricing\\n\\nOcelot pricing is tiered. Pricing details repeat here. Pricing details repeat h\",\"chunk_source\":\"compiled_truth\",\"chunk_id\":4,\"chunk_index\":0,\"score\":1,\"stale\":false,\"source_id\":\"default\",\"effective_date\":null,\"effective_date_source\":null,\"keyword_hit\":true,\"base_score\":1,\"evidence\":\"keyword_exact\",\"create_safety\":\"probable\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvb2NlbG90LWhhbmRib29rIl0\"}],\"meta\":[{\"key\":\"retrieval\",\"value\":{\"returned_count\":1,\"retrieved_count\":4,\"vector_enabled\":false,\"expansion_applied\":false,\"cache\":\"disabled\",\"token_budget\":{\"budget\":300,\"used\":300,\"dropped\":3,\"kept\":1,\"truncated\":true},\"degraded\":[{\"stage\":\"embed_unavailable\",\"reason\":\"no_provider\"},{\"stage\":\"budget_truncated\",\"reason\":\"first_result_truncated\"}],\"projection_readiness\":{\"status\":\"ready\",\"ready\":true},\"crag\":{\"confidence\":\"moderate\",\"reason\":\"keyword_exact_top\",\"query_shape\":\"factual\"}}}]}",+ "query-low:chunk": "{\"result\":[{\"slug\":\"notes/ocelot-handbook\",\"page_id\":2,\"title\":\"notes/ocelot-handbook\",\"type\":\"note\",\"chunk_text\":\"## Overview\\n\\nThe ocelot program. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. \\n\\n## Pricing\\n\\nOcelot pricing is tiered. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here.\",\"chunk_source\":\"compiled_truth\",\"chunk_id\":4,\"chunk_index\":0,\"score\":2,\"stale\":false,\"source_id\":\"default\",\"effective_date\":null,\"effective_date_source\":null,\"keyword_hit\":true,\"base_score\":2,\"evidence\":\"keyword_exact\",\"create_safety\":\"probable\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvb2NlbG90LWhhbmRib29rIl0\"}],\"meta\":[{\"key\":\"retrieval\",\"value\":{\"returned_count\":1,\"retrieved_count\":1,\"vector_enabled\":false,\"expansion_applied\":false,\"cache\":\"disabled\",\"token_budget\":{\"budget\":12000,\"used\":504,\"dropped\":0,\"kept\":1},\"degraded\":[{\"stage\":\"embed_unavailable\",\"reason\":\"no_provider\"}],\"projection_readiness\":{\"status\":\"ready\",\"ready\":true},\"crag\":{\"confidence\":\"moderate\",\"reason\":\"keyword_exact_top\",\"query_shape\":\"factual\"}}}]}",+ "recall:chunk": "{\"result\":{\"facts\":[],\"total\":0,\"protocol_version\":1,\"results\":[{\"slug\":\"chat/session-a\",\"title\":\"chat/session-a\",\"chunk\":\"**user:** turn 0 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\n\\n**assistant:** answer 0 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines \\n\\n**user:** turn 1 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\n\\n**assistant:** answer 1 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines \\n\\n**user:** turn 2 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\n\\n**assistant:** answer 2 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines \\n\\n**user:** turn 3 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\n\\n**assistant:** answer 3 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines \\n\\n**user:** turn 4 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\n\\n**assistant:** answer 4 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines \\n\\n**user:** turn 5 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\n\\n**assistant:** answer 5 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"provenance\":\"chat/session-a\"},{\"slug\":\"notes/ocelot-handbook\",\"title\":\"notes/ocelot-handbook\",\"chunk\":\"## Overview\\n\\nThe ocelot program. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. \\n\\n## Pricing\\n\\nOcelot pricing is tiered. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here.\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"provenance\":\"notes/ocelot-handbook\"},{\"slug\":\"notes/ocelot-private\",\"title\":\"notes/ocelot-private\",\"chunk\":\"Private ocelot memo body.\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"provenance\":\"notes/ocelot-private\"},{\"slug\":\"notes/short\",\"title\":\"notes/short\",\"chunk\":\"A short ocelot note.\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"provenance\":\"notes/short\"}],\"search_degraded\":\"keyword_only_no_embedding_provider\"},\"meta\":[]}",+ "recall-budget:chunk": "{\"result\":{\"facts\":[],\"total\":0,\"protocol_version\":1,\"results\":[{\"slug\":\"chat/session-a\",\"title\":\"chat/session-a\",\"chunk\":\"**user:** turn 0 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\n\\n**assistant:** answer 0 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines \\n\\n**user:** turn 1 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\n\\n**assistant:** answer 1 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines \\n\\n**user:** turn 2 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\n\\n**assistant:** answer 2 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines \\n\\n**user:** turn 3 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\n\\n**assistant:** answer 3 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines \\n\\n**user:** turn 4 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\n\\n**assistant:** answer 4 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines \\n\\n**user:** turn 5 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\n\\n**assistant:** answer 5 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"provenance\":\"chat/session-a\"},{\"slug\":\"notes/ocelot-handbook\",\"title\":\"notes/ocelot-handbook\",\"chunk\":\"## Overview\\n\\nThe ocelot program. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. \\n\\n## Pricing\\n\\nOcelot pricing is tiered. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here.\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"provenance\":\"notes/ocelot-handbook\"},{\"slug\":\"notes/ocelot-private\",\"title\":\"notes/ocelot-private\",\"chunk\":\"Private ocelot memo body.\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"provenance\":\"notes/ocelot-private\"},{\"slug\":\"notes/short\",\"title\":\"notes/short\",\"chunk\":\"A short ocelot note.\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"provenance\":\"notes/short\"}],\"search_degraded\":\"keyword_only_no_embedding_provider\",\"budget_tokens\":1500,\"budget_used\":1188,\"dropped_count\":0,\"budget_packing\":{\"policy\":\"query_first\",\"applied\":true,\"reason\":\"packed\",\"facts\":{\"candidates\":0,\"kept\":0,\"dropped\":0,\"used\":0},\"results\":{\"candidates\":4,\"kept\":4,\"dropped\":0,\"used\":1188}}},\"meta\":[]}",+ "mcp-search": "{\"content\":[{\"type\":\"text\",\"text\":\"[\\n {\\n \\\"slug\\\": \\\"chat/session-a\\\",\\n \\\"page_id\\\": 1,\\n \\\"title\\\": \\\"chat/session-a\\\",\\n \\\"type\\\": \\\"note\\\",\\n \\\"chunk_text\\\": \\\"**user:** turn 0 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\\\n\\\\n**assistant:** answer 0 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines \\\\n\\\\n**user:** turn 1 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\\\n\\\\n**assistant:** answer 1 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines \\\\n\\\\n**user:** turn 2 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\\\n\\\\n**assistant:** answer 2 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines \\\\n\\\\n**user:** turn 3 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\\\n\\\\n**assistant:** answer 3 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines \\\\n\\\\n**user:** turn 4 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\\\n\\\\n**assistant:** answer 4 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines \\\\n\\\\n**user:** turn 5 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\\\n\\\\n**assistant:** answer 5 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines\\\",\\n \\\"chunk_source\\\": \\\"compiled_truth\\\",\\n \\\"chunk_id\\\": 1,\\n \\\"chunk_index\\\": 0,\\n \\\"score\\\": 0.36266231536865234,\\n \\\"stale\\\": false,\\n \\\"source_id\\\": \\\"default\\\",\\n \\\"effective_date\\\": null,\\n \\\"effective_date_source\\\": null,\\n \\\"keyword_hit\\\": true,\\n \\\"id\\\": \\\"gbrain-page:v1:WyJkZWZhdWx0IiwiY2hhdC9zZXNzaW9uLWEiXQ\\\",\\n \\\"evidence\\\": \\\"weak_semantic\\\",\\n \\\"create_safety\\\": \\\"unknown\\\"\\n },\\n {\\n \\\"slug\\\": \\\"notes/ocelot-handbook\\\",\\n \\\"page_id\\\": 2,\\n \\\"title\\\": \\\"notes/ocelot-handbook\\\",\\n \\\"type\\\": \\\"note\\\",\\n \\\"chunk_text\\\": \\\"## Overview\\\\n\\\\nThe ocelot program. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. \\\\n\\\\n## Pricing\\\\n\\\\nOcelot pricing is tiered. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here.\\\",\\n \\\"chunk_source\\\": \\\"compiled_truth\\\",\\n \\\"chunk_id\\\": 4,\\n \\\"chunk_index\\\": 0,\\n \\\"score\\\": 0.3039635419845581,\\n \\\"stale\\\": false,\\n \\\"source_id\\\": \\\"default\\\",\\n \\\"effective_date\\\": null,\\n \\\"effective_date_source\\\": null,\\n \\\"keyword_hit\\\": true,\\n \\\"id\\\": \\\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvb2NlbG90LWhhbmRib29rIl0\\\",\\n \\\"evidence\\\": \\\"weak_semantic\\\",\\n \\\"create_safety\\\": \\\"unknown\\\"\\n },\\n {\\n \\\"slug\\\": \\\"notes/short\\\",\\n \\\"page_id\\\": 4,\\n \\\"title\\\": \\\"notes/short\\\",\\n \\\"type\\\": \\\"note\\\",\\n \\\"chunk_text\\\": \\\"A short ocelot note.\\\",\\n \\\"chunk_source\\\": \\\"compiled_truth\\\",\\n \\\"chunk_id\\\": 7,\\n \\\"chunk_index\\\": 0,\\n \\\"score\\\": 0.2431708425283432,\\n \\\"stale\\\": false,\\n \\\"source_id\\\": \\\"default\\\",\\n \\\"effective_date\\\": null,\\n \\\"effective_date_source\\\": null,\\n \\\"keyword_hit\\\": true,\\n \\\"id\\\": \\\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvc2hvcnQiXQ\\\",\\n \\\"evidence\\\": \\\"weak_semantic\\\",\\n \\\"create_safety\\\": \\\"unknown\\\"\\n }\\n]\"}],\"_meta\":{\"retrieval\":{\"returned_count\":3,\"retrieved_count\":3,\"projection_readiness\":{\"status\":\"ready\",\"ready\":true}}}}",+ "mcp-query": "{\"content\":[{\"type\":\"text\",\"text\":\"[\\n {\\n \\\"slug\\\": \\\"chat/session-a\\\",\\n \\\"page_id\\\": 1,\\n \\\"title\\\": \\\"chat/session-a\\\",\\n \\\"type\\\": \\\"note\\\",\\n \\\"chunk_text\\\": \\\"**user:** turn 0 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\\\n\\\\n**assistant:** answer 0 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines \\\\n\\\\n**user:** turn 1 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\\\n\\\\n**assistant:** answer 1 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines \\\\n\\\\n**user:** turn 2 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\\\n\\\\n**assistant:** answer 2 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines \\\\n\\\\n**user:** turn 3 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\\\n\\\\n**assistant:** answer 3 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines \\\\n\\\\n**user:** turn 4 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\\\n\\\\n**assistant:** answer 4 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines \\\\n\\\\n**user:** turn 5 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\\\n\\\\n**assistant:** answer 5 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines\\\",\\n \\\"chunk_source\\\": \\\"compiled_truth\\\",\\n \\\"chunk_id\\\": 1,\\n \\\"chunk_index\\\": 0,\\n \\\"score\\\": 0.36266231536865234,\\n \\\"stale\\\": false,\\n \\\"source_id\\\": \\\"default\\\",\\n \\\"effective_date\\\": null,\\n \\\"effective_date_source\\\": null,\\n \\\"keyword_hit\\\": true,\\n \\\"base_score\\\": 0.36266231536865234,\\n \\\"evidence\\\": \\\"weak_semantic\\\",\\n \\\"create_safety\\\": \\\"unknown\\\",\\n \\\"id\\\": \\\"gbrain-page:v1:WyJkZWZhdWx0IiwiY2hhdC9zZXNzaW9uLWEiXQ\\\"\\n },\\n {\\n \\\"slug\\\": \\\"notes/ocelot-handbook\\\",\\n \\\"page_id\\\": 2,\\n \\\"title\\\": \\\"notes/ocelot-handbook\\\",\\n \\\"type\\\": \\\"note\\\",\\n \\\"chunk_text\\\": \\\"## Overview\\\\n\\\\nThe ocelot program. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. \\\\n\\\\n## Pricing\\\\n\\\\nOcelot pricing is tiered. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here.\\\",\\n \\\"chunk_source\\\": \\\"compiled_truth\\\",\\n \\\"chunk_id\\\": 4,\\n \\\"chunk_index\\\": 0,\\n \\\"score\\\": 0.3039635419845581,\\n \\\"stale\\\": false,\\n \\\"source_id\\\": \\\"default\\\",\\n \\\"effective_date\\\": null,\\n \\\"effective_date_source\\\": null,\\n \\\"keyword_hit\\\": true,\\n \\\"base_score\\\": 0.3039635419845581,\\n \\\"evidence\\\": \\\"weak_semantic\\\",\\n \\\"create_safety\\\": \\\"unknown\\\",\\n \\\"id\\\": \\\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvb2NlbG90LWhhbmRib29rIl0\\\"\\n },\\n {\\n \\\"slug\\\": \\\"notes/short\\\",\\n \\\"page_id\\\": 4,\\n \\\"title\\\": \\\"notes/short\\\",\\n \\\"type\\\": \\\"note\\\",\\n \\\"chunk_text\\\": \\\"A short ocelot note.\\\",\\n \\\"chunk_source\\\": \\\"compiled_truth\\\",\\n \\\"chunk_id\\\": 7,\\n \\\"chunk_index\\\": 0,\\n \\\"score\\\": 0.2431708425283432,\\n \\\"stale\\\": false,\\n \\\"source_id\\\": \\\"default\\\",\\n \\\"effective_date\\\": null,\\n \\\"effective_date_source\\\": null,\\n \\\"keyword_hit\\\": true,\\n \\\"base_score\\\": 0.2431708425283432,\\n \\\"evidence\\\": \\\"weak_semantic\\\",\\n \\\"create_safety\\\": \\\"unknown\\\",\\n \\\"id\\\": \\\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvc2hvcnQiXQ\\\"\\n }\\n]\"}],\"_meta\":{\"retrieval\":{\"returned_count\":3,\"retrieved_count\":3,\"vector_enabled\":false,\"expansion_applied\":false,\"cache\":\"disabled\",\"token_budget\":{\"budget\":12000,\"used\":1176,\"dropped\":0,\"kept\":3},\"degraded\":[{\"stage\":\"embed_unavailable\",\"reason\":\"no_provider\"}],\"projection_readiness\":{\"status\":\"ready\",\"ready\":true},\"crag\":{\"confidence\":\"weak\",\"reason\":\"weak_semantic_top\",\"query_shape\":\"factual\",\"escalate_to_think\":true}}}}",+ "mcp-recall": "{\"content\":[{\"type\":\"text\",\"text\":\"{\\n \\\"facts\\\": [],\\n \\\"total\\\": 0,\\n \\\"protocol_version\\\": 1,\\n \\\"results\\\": [\\n {\\n \\\"slug\\\": \\\"chat/session-a\\\",\\n \\\"title\\\": \\\"chat/session-a\\\",\\n \\\"chunk\\\": \\\"**user:** turn 0 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\\\n\\\\n**assistant:** answer 0 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines \\\\n\\\\n**user:** turn 1 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\\\n\\\\n**assistant:** answer 1 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines \\\\n\\\\n**user:** turn 2 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\\\n\\\\n**assistant:** answer 2 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines \\\\n\\\\n**user:** turn 3 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\\\n\\\\n**assistant:** answer 3 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines \\\\n\\\\n**user:** turn 4 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\\\n\\\\n**assistant:** answer 4 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines \\\\n\\\\n**user:** turn 5 about the ocelot renewal and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap and the roadmap \\\\n\\\\n**assistant:** answer 5 owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines owners and timelines\\\",\\n \\\"evidence\\\": \\\"weak_semantic\\\",\\n \\\"create_safety\\\": \\\"unknown\\\",\\n \\\"provenance\\\": \\\"chat/session-a\\\"\\n },\\n {\\n \\\"slug\\\": \\\"notes/ocelot-handbook\\\",\\n \\\"title\\\": \\\"notes/ocelot-handbook\\\",\\n \\\"chunk\\\": \\\"## Overview\\\\n\\\\nThe ocelot program. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. \\\\n\\\\n## Pricing\\\\n\\\\nOcelot pricing is tiered. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here.\\\",\\n \\\"evidence\\\": \\\"weak_semantic\\\",\\n \\\"create_safety\\\": \\\"unknown\\\",\\n \\\"provenance\\\": \\\"notes/ocelot-handbook\\\"\\n },\\n {\\n \\\"slug\\\": \\\"notes/short\\\",\\n \\\"title\\\": \\\"notes/short\\\",\\n \\\"chunk\\\": \\\"A short ocelot note.\\\",\\n \\\"evidence\\\": \\\"weak_semantic\\\",\\n \\\"create_safety\\\": \\\"unknown\\\",\\n \\\"provenance\\\": \\\"notes/short\\\"\\n }\\n ],\\n \\\"search_degraded\\\": \\\"keyword_only_no_embedding_provider\\\"\\n}\"}]}",+ "think-prompt": "[{\"role\":\"user\",\"content\":\"Question: ocelot pricing\\n\\n<pages>\\n<page slug=\\\"notes/ocelot-handbook\\\" rank=\\\"1\\\">\\n## Overview\\n\\nThe ocelot program. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. Background prose for the handbook. \\n\\n## Pricing\\n\\nOcelot pricing is tiered. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here. Pricing details repeat here.\\n</page>\\n</pages>\\n\\n<takes>\\n(no take hits)\\n</takes>\\n\\nRespond with a single JSON object matching the schema. No prose outside JSON.\"}]"+}diff --git a/test/fixtures/goldens/exports/runtime.json b/test/fixtures/goldens/exports/runtime.jsonindex 0b1f33124c..517fb9547c 100644--- a/test/fixtures/goldens/exports/runtime.json+++ b/test/fixtures/goldens/exports/runtime.json@@ -59,6 +59,7 @@"getCalibrationCurve","getCalleesOf","getCallersOf",+ "getChunkWindows","getChunks","getChunksWithEmbeddings","getConfig",@@ -235,6 +236,7 @@"getCalibrationCurve","getCalleesOf","getCallersOf",+ "getChunkWindows","getChunks","getChunksWithEmbeddings","getConfig",@@ -713,6 +715,38 @@"peekLock","releaseLock"],+ "./search/evidence-delivery": [+ "DEFAULT_REMOTE_BUDGET_MAX",+ "DEFAULT_RETURN_BUDGET",+ "EVIDENCE_BLOCK_CHAR_CAP",+ "EVIDENCE_DELIVERY_MIN_SERVER_VERSION",+ "EVIDENCE_FETCH_TIMEOUT_MS",+ "EVIDENCE_OMISSION",+ "MAX_ASSEMBLE_HITS",+ "RETURN_BUDGET_DEFAULT_KEY",+ "RETURN_BUDGET_MAX_REMOTE_KEY",+ "RETURN_UNITS",+ "RETURN_UNIT_CONFIG_KEY",+ "RETURN_WINDOW_CONFIG_KEY",+ "THINK_RETURN_UNIT_CONFIG_KEY",+ "TIMELINE_SEPARATOR",+ "assembleEvidenceForHits",+ "capDeliveredSnippets",+ "countEvidenceTokens",+ "deliverEvidence",+ "deliveryVersionSkewWarning",+ "evidenceFingerprint",+ "evidenceTokenizer",+ "isConversationLabels",+ "locateChunks",+ "pageEvidenceText",+ "parseReturnUnit",+ "parseReturnWindow",+ "resolveEvidencePlan",+ "resolveFrozenHits",+ "splitPieces",+ "unsupportedDelivery"+ ],"./search/expansion": ["expandQuery","sanitizeExpansionOutput",diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex 072b15a7f5..7733b4c289 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -88,6 +88,7 @@"getCalibrationCurve: (opts: CalibrationCurveOpts, allowList: string[] | undefined) => Promise<CalibrationBucket[]>","getCalleesOf: (qualifiedName: string, opts?: { sourceId?: string; allSources?: boolean; limit?: number; bareFallback?: boolean; }) => Promise<CodeEdgeResult[]>","getCallersOf: (qualifiedName: string, opts?: { sourceId?: string; allSources?: boolean; limit?: number; }) => Promise<CodeEdgeResult[]>",+ "getChunkWindows: (requests: ChunkWindowRequest[], opts: ChunkWindowOpts) => Promise<ChunkWindowPage[]>","getChunks: (slug: string, opts?: PageReadScope & { includeEmbedding?: boolean; includeUnsealed?: boolean; }) => Promise<Chunk[]>","getChunksWithEmbeddings: (slug: string, opts?: { sourceId?: string; includeUnsealed?: boolean; }) => Promise<Chunk[]>","getConfig: (key: string) => Promise<string | null>",@@ -980,6 +981,7 @@"getCalibrationCurve: (opts: CalibrationCurveOpts, allowList: string[] | undefined) => Promise<CalibrationBucket[]>","getCalleesOf: (qualifiedName: string, opts?: { sourceId?: string; allSources?: boolean; limit?: number; bareFallback?: boolean; }) => Promise<CodeEdgeResult[]>","getCallersOf: (qualifiedName: string, opts?: { sourceId?: string; allSources?: boolean; limit?: number; }) => Promise<CodeEdgeResult[]>",+ "getChunkWindows: (requests: ChunkWindowRequest[], opts: ChunkWindowOpts) => Promise<ChunkWindowPage[]>","getChunks: (slug: string, opts?: { sourceId?: string; sourceIds?: string[]; includeEmbedding?: boolean; excludePrivate?: boolean; requireSafeChunks?: boolean; includeUnsealed?: boolean; }) => Promise<Chunk[]>","getChunksWithEmbeddings: (slug: string, opts?: { sourceId?: string; includeUnsealed?: boolean; }) => Promise<Chunk[]>","getConfig: (key: string) => Promise<string | null>",@@ -1288,6 +1290,7 @@"content_flag?: { reason: string; detail: string; } | undefined","cosine?: number | undefined","create_safety?: CreateSafety | undefined",+ "delivered?: DeliveredEvidence | undefined","effective_date?: string | null | undefined","effective_date_source?: string | null | undefined","evidence?: Evidence | undefined",@@ -3000,6 +3003,7 @@"getCalibrationCurve: (opts: CalibrationCurveOpts, allowList: string[] | undefined) => Promise<CalibrationBucket[]>","getCalleesOf: (qualifiedName: string, opts?: { sourceId?: string; allSources?: boolean; limit?: number; bareFallback?: boolean; }) => Promise<CodeEdgeResult[]>","getCallersOf: (qualifiedName: string, opts?: { sourceId?: string; allSources?: boolean; limit?: number; }) => Promise<CodeEdgeResult[]>",+ "getChunkWindows: (requests: ChunkWindowRequest[], opts: ChunkWindowOpts) => Promise<ChunkWindowPage[]>","getChunks: (slug: string, opts?: PageReadScope & { includeEmbedding?: boolean; includeUnsealed?: boolean; }) => Promise<Chunk[]>","getChunksWithEmbeddings: (slug: string, opts?: { sourceId?: string; includeUnsealed?: boolean; }) => Promise<Chunk[]>","getConfig: (key: string) => Promise<string | null>",@@ -5557,6 +5561,7 @@"getCalibrationCurve: (opts: CalibrationCurveOpts, allowList: string[] | undefined) => Promise<CalibrationBucket[]>","getCalleesOf: (qualifiedName: string, opts?: { sourceId?: string; allSources?: boolean; limit?: number; bareFallback?: boolean; }) => Promise<CodeEdgeResult[]>","getCallersOf: (qualifiedName: string, opts?: { sourceId?: string; allSources?: boolean; limit?: number; }) => Promise<CodeEdgeResult[]>",+ "getChunkWindows: (requests: ChunkWindowRequest[], opts: ChunkWindowOpts) => Promise<ChunkWindowPage[]>","getChunks: (slug: string, opts?: { sourceId?: string; sourceIds?: string[]; includeEmbedding?: boolean; excludePrivate?: boolean; requireSafeChunks?: boolean; includeUnsealed?: boolean; }) => Promise<Chunk[]>","getChunksWithEmbeddings: (slug: string, opts?: { sourceId?: string; includeUnsealed?: boolean; }) => Promise<Chunk[]>","getConfig: (key: string) => Promise<string | null>",@@ -5941,6 +5946,357 @@]}],+ "./search/evidence-delivery": [+ {+ "kind": "interface",+ "members": [+ "budget_tokens?: number | undefined",+ "caller?: { remote?: boolean; sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean; } | undefined",+ "detail?: \"low\" | \"medium\" | \"high\" | undefined",+ "hits: FrozenHit[]",+ "return_unit: \"auto\" | \"chunk\" | \"window\" | \"section\" | \"page\"",+ "return_window?: number | undefined"+ ],+ "name": "AssembleEvidenceInput"+ },+ {+ "kind": "interface",+ "members": [+ "delivery: DeliveryMeta | null",+ "results: (SearchResult & { delivered?: DeliveredEvidence; })[]",+ "unresolved: number[]"+ ],+ "name": "AssembleEvidenceOutput"+ },+ {+ "kind": "variable",+ "name": "DEFAULT_REMOTE_BUDGET_MAX",+ "signature": [+ "32000"+ ]+ },+ {+ "kind": "variable",+ "name": "DEFAULT_RETURN_BUDGET",+ "signature": [+ "6000"+ ]+ },+ {+ "kind": "interface",+ "members": [+ "liveHits?: boolean | undefined",+ "timeoutMs?: number | undefined"+ ],+ "name": "DeliverOptions"+ },+ {+ "kind": "interface",+ "members": [+ "chunk_ids: number[]",+ "fallback_reason?: string | undefined",+ "match_spans: MatchSpan[]",+ "revision?: string | undefined",+ "tokens: number",+ "truncated: boolean",+ "unit: DeliveredUnit",+ "unmapped_chunk_ids?: number[] | undefined"+ ],+ "name": "DeliveredEvidence"+ },+ {+ "kind": "type",+ "name": "DeliveredSearchResult",+ "signature": [+ "SearchResult & { delivered: DeliveredEvidence; }"+ ]+ },+ {+ "kind": "type",+ "name": "DeliveredUnit",+ "signature": [+ "\"chunk\" | \"window\" | \"section\" | \"page\""+ ]+ },+ {+ "kind": "interface",+ "members": [+ "applied_unit: \"auto\" | \"chunk\" | \"window\" | \"section\" | \"page\"",+ "blocks: number",+ "budget_clamped?: { requested: number; max: number; } | undefined",+ "budget_tokens: number",+ "budget_used: number",+ "coordinates: \"utf16\"",+ "dropped: number",+ "dropped_reasons: Record<string, number>",+ "fallbacks: string[]",+ "requested_unit: \"auto\" | \"chunk\" | \"window\" | \"section\" | \"page\"",+ "return_window: number",+ "tokenizer: \"cl100k\" | \"heuristic\"",+ "tokens_delivered: number"+ ],+ "name": "DeliveryMeta"+ },+ {+ "kind": "interface",+ "members": [+ "detail?: \"low\" | \"medium\" | \"high\" | undefined",+ "excludePrivate?: boolean | undefined",+ "requireSafeChunks?: boolean | undefined",+ "sourceId?: string | undefined",+ "sourceIds?: string[] | undefined"+ ],+ "name": "DeliveryScope"+ },+ {+ "kind": "variable",+ "name": "EVIDENCE_BLOCK_CHAR_CAP",+ "signature": [+ "60000"+ ]+ },+ {+ "kind": "variable",+ "name": "EVIDENCE_DELIVERY_MIN_SERVER_VERSION",+ "signature": [+ "\"0.60.13.0\""+ ]+ },+ {+ "kind": "variable",+ "name": "EVIDENCE_FETCH_TIMEOUT_MS",+ "signature": [+ "5000"+ ]+ },+ {+ "kind": "variable",+ "name": "EVIDENCE_OMISSION",+ "signature": [+ "\"\\n\\n[…]\\n\\n\""+ ]+ },+ {+ "kind": "interface",+ "members": [+ "budgetClamped?: { requested: number; max: number; } | undefined",+ "budgetTokens: number",+ "explicitUnit: boolean",+ "requestedUnit: \"auto\" | \"chunk\" | \"window\" | \"section\" | \"page\"",+ "unit: \"auto\" | \"window\" | \"section\" | \"page\"",+ "window: number"+ ],+ "name": "EvidencePlan"+ },+ {+ "kind": "interface",+ "members": [+ "chunk_id: number",+ "slug: string",+ "source_id: string"+ ],+ "name": "FrozenHit"+ },+ {+ "kind": "variable",+ "name": "MAX_ASSEMBLE_HITS",+ "signature": [+ "50"+ ]+ },+ {+ "kind": "interface",+ "members": [+ "chunk_id: number",+ "end: number",+ "start: number"+ ],+ "name": "MatchSpan"+ },+ {+ "kind": "variable",+ "name": "RETURN_BUDGET_DEFAULT_KEY",+ "signature": [+ "\"search.return_budget_default\""+ ]+ },+ {+ "kind": "variable",+ "name": "RETURN_BUDGET_MAX_REMOTE_KEY",+ "signature": [+ "\"search.return_budget_max_remote\""+ ]+ },+ {+ "kind": "variable",+ "name": "RETURN_UNITS",+ "signature": [+ "readonly [\"chunk\", \"window\", \"section\", \"page\", \"auto\"]"+ ]+ },+ {+ "kind": "variable",+ "name": "RETURN_UNIT_CONFIG_KEY",+ "signature": [+ "\"search.return_unit\""+ ]+ },+ {+ "kind": "variable",+ "name": "RETURN_WINDOW_CONFIG_KEY",+ "signature": [+ "\"search.return_window\""+ ]+ },+ {+ "kind": "interface",+ "members": [+ "budget: unknown",+ "configKey?: string | undefined",+ "op: string",+ "remote: boolean | undefined",+ "returnUnit: unknown",+ "returnWindow: unknown",+ "snippetCap: number",+ "snippetChars: unknown",+ "viaSubagent?: boolean | undefined"+ ],+ "name": "ResolvePlanInput"+ },+ {+ "kind": "type",+ "name": "ReturnUnit",+ "signature": [+ "\"auto\" | \"chunk\" | \"window\" | \"section\" | \"page\""+ ]+ },+ {+ "kind": "variable",+ "name": "THINK_RETURN_UNIT_CONFIG_KEY",+ "signature": [+ "\"think.return_unit\""+ ]+ },+ {+ "kind": "variable",+ "name": "TIMELINE_SEPARATOR",+ "signature": [+ "\"\\n\\n<!-- timeline -->\\n\\n\""+ ]+ },+ {+ "kind": "function",+ "name": "assembleEvidenceForHits",+ "signature": [+ "(engine: BrainEngine, input: AssembleEvidenceInput) => Promise<AssembleEvidenceOutput>"+ ]+ },+ {+ "kind": "function",+ "name": "capDeliveredSnippets",+ "signature": [+ "<T extends SearchResult & { delivered?: DeliveredEvidence; }>(results: T[], cap: number, delivery: DeliveryMeta) => T[]"+ ]+ },+ {+ "kind": "function",+ "name": "countEvidenceTokens",+ "signature": [+ "(text: string, tokenizer?: \"cl100k\" | \"heuristic\") => number"+ ]+ },+ {+ "kind": "function",+ "name": "deliverEvidence",+ "signature": [+ "(engine: BrainEngine, hits: SearchResult[], plan: EvidencePlan, scope: DeliveryScope, opts?: DeliverOptions) => Promise<{ results: DeliveredSearchResult[]; delivery: DeliveryMeta; }>"+ ]+ },+ {+ "kind": "function",+ "name": "deliveryVersionSkewWarning",+ "signature": [+ "(opName: string, params: Record<string, unknown>, retrievalMeta: Record<string, unknown> | null | undefined, result: unknown) => string | null"+ ]+ },+ {+ "kind": "function",+ "name": "evidenceFingerprint",+ "signature": [+ "(results: Array<{ source_id?: string; slug: string; chunk_text: string; chunk_id: number; delivered?: { unit: string; chunk_ids: number[]; }; }>) => string"+ ]+ },+ {+ "kind": "function",+ "name": "evidenceTokenizer",+ "signature": [+ "() => \"cl100k\" | \"heuristic\""+ ]+ },+ {+ "kind": "function",+ "name": "isConversationLabels",+ "signature": [+ "(labels: string[]) => boolean"+ ]+ },+ {+ "kind": "function",+ "name": "locateChunks",+ "signature": [+ "(text: string, chunks: Array<{ id: number; chunk_index: number; chunk_text: string; }>) => Array<{ id: number; chunk_index: number; start: number; end: number; }>"+ ]+ },+ {+ "kind": "function",+ "name": "pageEvidenceText",+ "signature": [+ "(page: { compiled_truth: string; timeline: string; }, includeTimeline: boolean) => { text: string; timelineAt: number; }"+ ]+ },+ {+ "kind": "function",+ "name": "parseReturnUnit",+ "signature": [+ "(raw: unknown, op: string) => ReturnUnit | undefined"+ ]+ },+ {+ "kind": "function",+ "name": "parseReturnWindow",+ "signature": [+ "(raw: unknown, op: string) => number | undefined"+ ]+ },+ {+ "kind": "function",+ "name": "resolveEvidencePlan",+ "signature": [+ "(engine: BrainEngine, input: ResolvePlanInput) => Promise<EvidencePlan | null>"+ ]+ },+ {+ "kind": "function",+ "name": "resolveFrozenHits",+ "signature": [+ "(engine: BrainEngine, hits: FrozenHit[], scope: PageReadScope) => Promise<{ rows: SearchResult[]; unresolved: number[]; }>"+ ]+ },+ {+ "kind": "function",+ "name": "splitPieces",+ "signature": [+ "(text: string) => Array<{ start: number; end: number; lineStart: boolean; }>"+ ]+ },+ {+ "kind": "function",+ "name": "unsupportedDelivery",+ "signature": [+ "(plan: EvidencePlan, reason: string) => DeliveryMeta"+ ]+ }+ ],"./search/expansion": [{"kind": "function",@@ -6404,6 +6760,7 @@"citations: ParsedCitation[]","cost_usd?: number | undefined","diagnostics: { pagesFromHybrid: number; takesFromKeyword: number; takesFromVector: number; graphHits: number; }",+ "evidence_delivery?: DeliveryMeta | undefined","extractive?: ExtractiveFallback | undefined","gaps: string[]","graphHits: number",@@ -7443,6 +7800,7 @@"content_flag?: { reason: string; detail: string; } | undefined","cosine?: number | undefined","create_safety?: CreateSafety | undefined",+ "delivered?: DeliveredEvidence | undefined","effective_date?: string | null | undefined","effective_date_source?: string | null | undefined","evidence?: Evidence | undefined",diff --git a/test/fixtures/goldens/postgres-engine-gauge/acquires-by-case.json b/test/fixtures/goldens/postgres-engine-gauge/acquires-by-case.jsonindex cf6571e90f..678f40774f 100644--- a/test/fixtures/goldens/postgres-engine-gauge/acquires-by-case.json+++ b/test/fixtures/goldens/postgres-engine-gauge/acquires-by-case.json@@ -85,6 +85,8 @@"getCalleesOf#sourceId": {},"getCallersOf#default": {},"getCallersOf#sourceId": {},+ "getChunkWindows#default": {},+ "getChunkWindows#scopedPrivateSafe": {},"getChunks#default": {"raw": 1},diff --git a/test/fixtures/goldens/rls-scope-inventory.json b/test/fixtures/goldens/rls-scope-inventory.jsonindex 6dbaddf397..1c23976d09 100644--- a/test/fixtures/goldens/rls-scope-inventory.json+++ b/test/fixtures/goldens/rls-scope-inventory.json@@ -739,6 +739,32 @@],"flagOnScopes": []},+ "getChunkWindows#default": {+ "flagOffLanes": [+ "pool"+ ],+ "flagOffOpensTransaction": false,+ "flagOn": "scoped",+ "flagOnLanes": [+ "tx"+ ],+ "flagOnScopes": [+ "*"+ ]+ },+ "getChunkWindows#scopedPrivateSafe": {+ "flagOffLanes": [+ "pool"+ ],+ "flagOffOpensTransaction": false,+ "flagOn": "scoped",+ "flagOnLanes": [+ "tx"+ ],+ "flagOnScopes": [+ "src-a,src-b"+ ]+ },"getChunks#default": {"flagOffLanes": ["pool"@@ -3208,7 +3234,7 @@}},"static": {- "callSites": 22,+ "callSites": 23,"directMethods": {"_searchKeywordCJK": 1,"countChunklessPagesWithContent": 1,@@ -3217,6 +3243,7 @@"findDuplicatePage": 1,"getAllSlugs": 1,"getBacklinks": 1,+ "getChunkWindows": 1,"getChunks": 1,"getLinks": 1,"listChunklessPagesWithContent": 1,@@ -3287,6 +3314,7 @@"getCalibrationCurve": "none","getCalleesOf": "none","getCallersOf": "none",+ "getChunkWindows": "direct","getChunks": "direct","getChunksWithEmbeddings": "none","getConfig": "none",diff --git a/test/fixtures/goldens/sql-text/_classification.json b/test/fixtures/goldens/sql-text/_classification.jsonindex ecb1dd8922..1bdc5dd5d5 100644--- a/test/fixtures/goldens/sql-text/_classification.json+++ b/test/fixtures/goldens/sql-text/_classification.json@@ -1,7 +1,7 @@{"golden": {"counts": {- "chunks": 13,+ "chunks": 14,"cjk-search": 2,"code-edges": 5,"facts": 18,@@ -80,6 +80,7 @@"getCalibrationCurve": "takes","getCalleesOf": "code-edges","getCallersOf": "code-edges",+ "getChunkWindows": "chunks","getChunks": "chunks","getChunksWithEmbeddings": "chunks","getConfig": "out-of-scope:config",diff --git a/test/fixtures/goldens/sql-text/_driver.json b/test/fixtures/goldens/sql-text/_driver.jsonindex e7c0aa1b05..bafb19cc25 100644--- a/test/fixtures/goldens/sql-text/_driver.json+++ b/test/fixtures/goldens/sql-text/_driver.json@@ -95,6 +95,30 @@}]},+ "getChunkWindows": {+ "default": [+ {+ "paramCount": 8,+ "unsafeOptions": {+ "cancelFence": false,+ "prepare": true,+ "simple": false+ },+ "via": "unsafe"+ }+ ],+ "scopedPrivateSafe": [+ {+ "paramCount": 9,+ "unsafeOptions": {+ "cancelFence": false,+ "prepare": true,+ "simple": false+ },+ "via": "unsafe"+ }+ ]+ },"getChunks": {"default": [{@@ -4362,7 +4386,7 @@"getLastSeen": {"asof+sourceId": [{- "paramCount": 6,+ "paramCount": 7,"unsafeOptions": {"cancelFence": false,"prepare": true,@@ -4373,7 +4397,7 @@],"default": [{- "paramCount": 3,+ "paramCount": 4,"unsafeOptions": {"cancelFence": false,"prepare": true,diff --git a/test/fixtures/goldens/sql-text/chunks.json b/test/fixtures/goldens/sql-text/chunks.jsonindex 4545e9e637..145005204a 100644--- a/test/fixtures/goldens/sql-text/chunks.json+++ b/test/fixtures/goldens/sql-text/chunks.json@@ -84,6 +84,43 @@}]},+ "getChunkWindows": {+ "default": [+ {+ "lane": "pool",+ "params": [+ "array<number>",+ "array<number>",+ "array<number>",+ "array<number>",+ "number",+ "array<number>",+ "array<string>",+ "number"+ ],+ "sql": "WITH req AS ( SELECT * FROM unnest($1::int[], $2::int[], $3::int[], $4::int[]) AS r(page_id, lo, hi, prio) ), auth AS ( SELECT p.id, p.slug, p.source_id, p.type, p.knowledge_revision::text AS revision, p.compiled_truth, p.timeline, (COALESCE(p.chunker_version, 0) >= $5) AS sealed, (SELECT MIN(req.prio) FROM req WHERE req.page_id = p.id) AS prio FROM pages p JOIN sources s ON s.id = p.source_id WHERE p.id = ANY($6::int[]) AND p.deleted_at IS NULL AND (p.text_projection_revision = p.knowledge_revision) IS TRUE AND NOT s.archived AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') ), chunk_rows AS ( SELECT cc.page_id, cc.id AS chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, a.prio FROM auth a JOIN content_chunks cc ON cc.page_id = a.id WHERE a.sealed AND cc.chunk_source = ANY($7::text[]) AND COALESCE(cc.modality, 'text') = 'text' AND EXISTS (SELECT 1 FROM req r WHERE r.page_id = cc.page_id AND cc.chunk_index BETWEEN r.lo AND r.hi) ORDER BY a.prio, cc.page_id, cc.chunk_index LIMIT $8 ) SELECT 'page' AS kind, a.id AS page_id, a.slug, a.source_id, a.type, a.revision, a.sealed, a.prio, (SELECT MAX(c2.chunk_index) FROM content_chunks c2 WHERE c2.page_id = a.id) AS max_chunk_index, a.compiled_truth, a.timeline, NULL::int AS chunk_id, NULL::int AS chunk_index, NULL::text AS chunk_text, NULL::text AS chunk_source FROM auth a UNION ALL SELECT 'chunk' AS kind, c.page_id, NULL, NULL, NULL, NULL, NULL, c.prio, NULL, NULL, NULL, c.chunk_id, c.chunk_index, c.chunk_text, c.chunk_source FROM chunk_rows c",+ "textSha256": "36f167b6708826aa64eda532d22495b8c0dc0d133555ff743603a9a14083d8a9"+ }+ ],+ "scopedPrivateSafe": [+ {+ "lane": "pool",+ "params": [+ "array<number>",+ "array<number>",+ "array<number>",+ "array<number>",+ "number",+ "array<number>",+ "array<string>",+ "array<string>",+ "number"+ ],+ "sql": "WITH req AS ( SELECT * FROM unnest($1::int[], $2::int[], $3::int[], $4::int[]) AS r(page_id, lo, hi, prio) ), auth AS ( SELECT p.id, p.slug, p.source_id, p.type, p.knowledge_revision::text AS revision, p.compiled_truth, p.timeline, (COALESCE(p.chunker_version, 0) >= $5) AS sealed, (SELECT MIN(req.prio) FROM req WHERE req.page_id = p.id) AS prio FROM pages p JOIN sources s ON s.id = p.source_id WHERE p.id = ANY($6::int[]) AND p.source_id = ANY($7::text[]) AND p.deleted_at IS NULL AND (p.text_projection_revision = p.knowledge_revision) IS TRUE AND NOT s.archived AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) ELSE false END)) AND COALESCE(p.chunker_version, 0) >= 4 ), chunk_rows AS ( SELECT cc.page_id, cc.id AS chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, a.prio FROM auth a JOIN content_chunks cc ON cc.page_id = a.id WHERE a.sealed AND cc.chunk_source = ANY($8::text[]) AND COALESCE(cc.modality, 'text') = 'text' AND EXISTS (SELECT 1 FROM req r WHERE r.page_id = cc.page_id AND cc.chunk_index BETWEEN r.lo AND r.hi) ORDER BY a.prio, cc.page_id, cc.chunk_index LIMIT $9 ) SELECT 'page' AS kind, a.id AS page_id, a.slug, a.source_id, a.type, a.revision, a.sealed, a.prio, (SELECT MAX(c2.chunk_index) FROM content_chunks c2 WHERE c2.page_id = a.id) AS max_chunk_index, a.compiled_truth, a.timeline, NULL::int AS chunk_id, NULL::int AS chunk_index, NULL::text AS chunk_text, NULL::text AS chunk_source FROM auth a UNION ALL SELECT 'chunk' AS kind, c.page_id, NULL, NULL, NULL, NULL, NULL, c.prio, NULL, NULL, NULL, c.chunk_id, c.chunk_index, c.chunk_text, c.chunk_source FROM chunk_rows c",+ "textSha256": "deffa97e09a1ffb4ab99f3ad6289b7972f5598deb0ef0c0a1b606513410ccd33"+ }+ ]+ },"getChunks": {"default": [{diff --git a/test/fixtures/goldens/sql-text/timeline.json b/test/fixtures/goldens/sql-text/timeline.jsonindex 6cdbf734e1..cd1ec18696 100644--- a/test/fixtures/goldens/sql-text/timeline.json+++ b/test/fixtures/goldens/sql-text/timeline.json@@ -41,22 +41,24 @@"string","string","string",+ "string","string"],- "sql": "SELECT te.date::text AS last_date, ep.slug AS last_event_slug FROM timeline_entries te JOIN pages p ON p.id = te.page_id AND p.deleted_at IS NULL LEFT JOIN pages ep ON ep.id = te.event_page_id AND ep.source_id = $1 WHERE (te.event_page_id IS NULL OR ep.deleted_at IS NULL) AND te.date <= $2::date AND ( p.slug = $3 OR (ep.id IS NOT NULL AND EXISTS ( SELECT 1 FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(ep.frontmatter->'event'->'who') = 'array' THEN ep.frontmatter->'event'->'who' ELSE '[]'::jsonb END ) AS w(name) WHERE w.name = $4 OR w.name LIKE $5 )) ) AND p.source_id = $6 ORDER BY COALESCE(ep.effective_date, te.date::timestamptz) DESC, te.id DESC LIMIT 1",- "textSha256": "46f3058edbde4893bb6d55ca7a6e345be6eb5d5532ba5dbd272fbfe050c7178d"+ "sql": "SELECT te.date::text AS last_date, ep.slug AS last_event_slug FROM timeline_entries te JOIN pages p ON p.id = te.page_id AND p.deleted_at IS NULL LEFT JOIN pages ep ON ep.id = te.event_page_id AND ep.source_id = $1 WHERE (te.event_page_id IS NULL OR ep.deleted_at IS NULL) AND te.date <= $2::date AND ( p.slug = $3 OR (ep.id IS NOT NULL AND EXISTS ( SELECT 1 FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(ep.frontmatter->'event'->'who') = 'array' THEN ep.frontmatter->'event'->'who' ELSE '[]'::jsonb END ) AS w(name) WHERE w.name = $4 OR w.name LIKE $5 ESCAPE '\\' OR w.name LIKE $6 ESCAPE '\\' )) ) AND p.source_id = $7 ORDER BY te.date DESC, COALESCE(ep.effective_date, te.date::timestamptz) DESC, te.id DESC LIMIT 1",+ "textSha256": "b1983964b23c4ca8fd62d217cfef9b91af454f28aaf19ec263a77e5bc974ea73"}],"default": [{"lane": "pool","params": [+ "string","string","string","string"],- "sql": "SELECT te.date::text AS last_date, ep.slug AS last_event_slug FROM timeline_entries te JOIN pages p ON p.id = te.page_id AND p.deleted_at IS NULL LEFT JOIN pages ep ON ep.id = te.event_page_id WHERE (te.event_page_id IS NULL OR ep.deleted_at IS NULL) AND te.date <= current_date AND ( p.slug = $1 OR (ep.id IS NOT NULL AND EXISTS ( SELECT 1 FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(ep.frontmatter->'event'->'who') = 'array' THEN ep.frontmatter->'event'->'who' ELSE '[]'::jsonb END ) AS w(name) WHERE w.name = $2 OR w.name LIKE $3 )) ) ORDER BY COALESCE(ep.effective_date, te.date::timestamptz) DESC, te.id DESC LIMIT 1",- "textSha256": "1961a0d028029570230919d1a512f0f5438510500066b1d72a8335f91a5e313e"+ "sql": "SELECT te.date::text AS last_date, ep.slug AS last_event_slug FROM timeline_entries te JOIN pages p ON p.id = te.page_id AND p.deleted_at IS NULL LEFT JOIN pages ep ON ep.id = te.event_page_id WHERE (te.event_page_id IS NULL OR ep.deleted_at IS NULL) AND te.date <= current_date AND ( p.slug = $1 OR (ep.id IS NOT NULL AND EXISTS ( SELECT 1 FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(ep.frontmatter->'event'->'who') = 'array' THEN ep.frontmatter->'event'->'who' ELSE '[]'::jsonb END ) AS w(name) WHERE w.name = $2 OR w.name LIKE $3 ESCAPE '\\' OR w.name LIKE $4 ESCAPE '\\' )) ) ORDER BY te.date DESC, COALESCE(ep.effective_date, te.date::timestamptz) DESC, te.id DESC LIMIT 1",+ "textSha256": "9aa7d61f3255e394faf3f2e20f0015d3b94dc201c257a1808e61995478101de6"}]},diff --git a/test/helpers/evidence-delivery-fixture.ts b/test/helpers/evidence-delivery-fixture.tsnew file mode 100644index 0000000000..22636f8fd4--- /dev/null+++ b/test/helpers/evidence-delivery-fixture.ts@@ -0,0 +1,77 @@+/**+ * Shared fixture for the evidence-delivery off-path golden (PGLite unit arm+ * and Postgres e2e arm). The captured bytes were generated on the release+ * before evidence delivery; do not change the corpus or the captured calls.+ */+import type { BrainEngine } from '../../src/core/engine.ts';+import { operations, type OperationContext } from '../../src/core/operations.ts';+import { dispatchToolCall } from '../../src/mcp/dispatch.ts';+import { runThink } from '../../src/core/think/index.ts';+import { prepareMarkdownChunks } from '../../src/core/markdown-chunks.ts';+import { installFixtureChunks } from './page-projection.ts';++export const OFF_PATH_PAGES: Array<{ slug: string; body: string; timeline?: string; frontmatter?: Record<string, unknown> }> = [+ {+ slug: 'chat/session-a',+ body: Array.from({ length: 16 }, (_, i) => `**user:** turn ${i} about the ocelot renewal ${'and the roadmap '.repeat(10)}\n\n**assistant:** answer ${i} ${'owners and timelines '.repeat(10)}`).join('\n\n'),+ },+ {+ slug: 'notes/ocelot-handbook',+ body: `## Overview\n\nThe ocelot program. ${'Background prose for the handbook. '.repeat(30)}\n\n## Pricing\n\nOcelot pricing is tiered. ${'Pricing details repeat here. '.repeat(30)}`,+ timeline: '- 2026-02-01 ocelot pricing changed',+ },+ { slug: 'notes/ocelot-private', body: 'Private ocelot memo body.', frontmatter: { visibility: 'private' } },+ { slug: 'notes/short', body: 'A short ocelot note.' },+];++function ctxOf(engine: BrainEngine, meta: Record<string, unknown>[], overrides: Partial<OperationContext> = {}): OperationContext {+ return {+ engine: engine as never, config: {} as never, logger: console as never, dryRun: false, remote: false, sourceId: 'default',+ emitResponseMeta: (key: string, value: unknown) => { meta.push({ key, value }); },+ ...overrides,+ } as OperationContext;+}++export async function captureOffPath(engine: BrainEngine): Promise<Record<string, string>> {+ const out: Record<string, string> = {};+ const op = (name: string) => operations.find(o => o.name === name)!;+ const run = async (label: string, name: string, params: Record<string, unknown>, overrides: Partial<OperationContext> = {}) => {+ const meta: Record<string, unknown>[] = [];+ const result = await op(name).handler(ctxOf(engine, meta, overrides), params);+ out[label] = JSON.stringify({ result, meta });+ };+ for (const variant of [{}, { return_unit: 'chunk' }]) {+ const tag = Object.keys(variant).length ? ':chunk' : '';+ await run(`search${tag}`, 'search', { query: 'ocelot', ...variant });+ await run(`search-remote${tag}`, 'search', { query: 'ocelot pricing', ...variant }, { remote: true });+ await run(`search-subagent${tag}`, 'search', { query: 'ocelot', ...variant }, { viaSubagent: true } as Partial<OperationContext>);+ await run(`query${tag}`, 'query', { query: 'ocelot pricing', expand: false, ...variant });+ await run(`query-budget${tag}`, 'query', { query: 'ocelot', expand: false, token_budget: 300, ...variant });+ await run(`query-low${tag}`, 'query', { query: 'ocelot pricing', expand: false, detail: 'low', ...variant });+ await run(`recall${tag}`, 'recall', { query: 'ocelot', ...variant });+ await run(`recall-budget${tag}`, 'recall', { query: 'ocelot', budget_tokens: 1500, budget_policy: 'query_first', ...variant });+ }+ for (const name of ['search', 'query', 'recall']) {+ const res = await dispatchToolCall(engine, name, { query: 'ocelot', ...(name === 'query' ? { expand: false } : {}) },+ { remote: true, transport: 'stdio', sourceId: 'default' });+ out[`mcp-${name}`] = JSON.stringify(res);+ }+ const prompts: string[] = [];+ await runThink(engine, {+ question: 'ocelot pricing', remote: false,+ client: { create: async (params: { messages: unknown[] }) => {+ prompts.push(JSON.stringify(params.messages));+ return { content: [{ type: 'text', text: '{"answer":"ok","citations":[],"gaps":[]}' }], usage: { input_tokens: 1, output_tokens: 1 } };+ } } as never,+ });+ out['think-prompt'] = prompts[0];+ return out;+}++export async function seedOffPath(engine: BrainEngine): Promise<void> {+ for (const p of OFF_PATH_PAGES) {+ await engine.putPage(p.slug, { type: 'note', title: p.slug, compiled_truth: p.body, timeline: p.timeline ?? '', frontmatter: p.frontmatter ?? {} });+ await installFixtureChunks(engine, p.slug, await prepareMarkdownChunks({ compiled_truth: p.body, timeline: p.timeline ?? '' }));+ }+ await engine.setConfig('search.mcp_keyword_only', 'true');+}diff --git a/test/helpers/postgres-engine-sql-cases.ts b/test/helpers/postgres-engine-sql-cases.tsindex 18d9edb66f..ee095cc154 100644--- a/test/helpers/postgres-engine-sql-cases.ts+++ b/test/helpers/postgres-engine-sql-cases.ts@@ -101,7 +101,7 @@ export const DOMAIN_OF: Record<string, string> = {// files'upsertFile': 'files', 'getFile': 'files', 'listFilesForPage': 'files',// chunks- 'upsertChunks': 'chunks', 'getChunks': 'chunks', 'countStaleChunks': 'chunks', 'sumStaleChunkChars': 'chunks',+ 'upsertChunks': 'chunks', 'getChunks': 'chunks', 'getChunkWindows': 'chunks', 'countStaleChunks': 'chunks', 'sumStaleChunkChars': 'chunks','setPageEmbeddingSignature': 'chunks', 'invalidateStaleSignatureEmbeddings': 'chunks','invalidateContentDriftEmbeddings': 'chunks', 'listStaleChunks': 'chunks','countChunklessPagesWithContent': 'chunks', 'listChunklessPagesWithContent': 'chunks', 'deleteChunks': 'chunks',@@ -544,6 +544,10 @@ export const SQL_CASES: SqlCase[] = [['default', (e) => e.getEmbeddingsByChunkIds([1, 2])],['column', (e) => e.getEmbeddingsByChunkIds([1, 2], 'embedding_voyage')],]),+ ...variants('getChunkWindows', [+ ['default', (e) => e.getChunkWindows([{ page_id: 1, from_index: 0, to_index: 4, priority: 0 }], { chunkSources: ['compiled_truth', 'timeline'], maxRows: 16 })],+ ['scopedPrivateSafe', (e) => e.getChunkWindows([{ page_id: 1, from_index: 0, to_index: 4, priority: 0 }], { sourceIds: SRCS, excludePrivate: true, requireSafeChunks: true, chunkSources: ['compiled_truth'], maxRows: 16 })],+ ]),...variants('getChunksWithEmbeddings', [['default', (e) => e.getChunksWithEmbeddings(SLUG)],['sourceId+includeUnsealed', (e) => e.getChunksWithEmbeddings(SLUG, { sourceId: SRC, includeUnsealed: true })],diff --git a/test/ontology-backdated-same-value.test.ts b/test/ontology-backdated-same-value.test.tsnew file mode 100644index 0000000000..21965a174b--- /dev/null+++ b/test/ontology-backdated-same-value.test.ts@@ -0,0 +1,64 @@+/**+ * A backdated ontology observation whose value equals the current open value+ * is an earlier stint, not a corroboration of the current one. It must stay+ * live so as-of reads see it, exactly like a backdated observation of a+ * different value; a same-or-later observation of the current value still+ * corroborates. (gbrain-evals N3 temporal-asof, bug 1.)+ *+ * Synthetic data only.+ */+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { operations } from '../src/core/operations.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';++let engine: PGLiteEngine;+const E = 'people/alice-example';++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});++beforeEach(async () => {+ await resetPgliteState(engine);+});++afterAll(async () => {+ await engine.disconnect();+});++const op = (name: string, p: object) => {+ const ctx = { engine, config: { engine: 'pglite', database_path: ':memory:' }, logger: console, dryRun: false, remote: false, sourceId: 'default' } as any;+ return operations.find(o => o.name === name)!.handler(ctx, p as any);+};+const employerAt = async (asof: string) =>+ ((await op('ontology_get', { entity: E, asof })) as any[]).find(r => r.dimension === 'employer')?.value ?? null;++describe('mergeOntologyFact: backdated observation of the current value', () => {+ test('a late-learned first stint with the current value stays visible as of its window', async () => {+ await op('ontology_propose', { entity: E, dimension: 'employer', value: 'startup-1', valid_from: '2023-01-01', source: 'notes/b' });+ await op('ontology_propose', { entity: E, dimension: 'employer', value: 'startup-0', valid_from: '2024-01-01', source: 'notes/c' });+ const res = await op('ontology_propose', { entity: E, dimension: 'employer', value: 'startup-0', valid_from: '2022-01-01', source: 'notes/a' }) as any;+ expect(res.action).toBe('inserted');+ expect(await employerAt('2022-06-01')).toBe('startup-0');+ expect(await employerAt('2023-06-01')).toBe('startup-1');+ expect(await employerAt('2024-06-01')).toBe('startup-0');+ });++ test('a backdated same value with no intervening stint extends the as-of window back', async () => {+ await op('ontology_propose', { entity: E, dimension: 'employer', value: 'startup-0', valid_from: '2024-01-01', source: 'notes/c' });+ await op('ontology_propose', { entity: E, dimension: 'employer', value: 'startup-0', valid_from: '2022-01-01', source: 'notes/a' });+ expect(await employerAt('2023-01-01')).toBe('startup-0');+ expect(await employerAt('2021-06-01')).toBeNull();+ });++ test('a same-value observation at or after the current start still corroborates', async () => {+ await op('ontology_propose', { entity: E, dimension: 'employer', value: 'startup-0', valid_from: '2024-01-01', source: 'notes/c' });+ const later = await op('ontology_propose', { entity: E, dimension: 'employer', value: 'startup-0', valid_from: '2024-03-01', source: 'notes/d' }) as any;+ expect(later.action).toBe('corroborated');+ const undated = await op('ontology_propose', { entity: E, dimension: 'employer', value: 'startup-0', source: 'notes/e' }) as any;+ expect(undated.action).toBe('corroborated');+ });+});diff --git a/test/operations-coverage-ledger.test.ts b/test/operations-coverage-ledger.test.tsindex 5508effb3e..09bf74e7ea 100644--- a/test/operations-coverage-ledger.test.ts+++ b/test/operations-coverage-ledger.test.ts@@ -50,6 +50,7 @@ const LEDGER: Record<string, string> = {search_tune: 'test/search-introspection-ops.test.ts',cache_stats: 'test/quarantine-cache-ops.test.ts',search_by_image: 'test/search-by-image-op.test.ts',+ assemble_evidence: 'test/evidence-delivery.test.ts',add_tag: 'test/source-id-tx-regression.test.ts',remove_tag: 'test/e2e/mechanical.test.ts',get_tags: 'test/get-page-federated-scope.test.ts',diff --git a/test/operations-source-isolation-matrix.test.ts b/test/operations-source-isolation-matrix.test.tsindex aece05182f..0ff74a2645 100644--- a/test/operations-source-isolation-matrix.test.ts+++ b/test/operations-source-isolation-matrix.test.ts@@ -151,6 +151,7 @@ const MATRIX: Row[] = [{ name: 'list_pages', mode: 'isolated', args: { limit: 100 } },{ name: 'search', mode: 'isolated', args: { query: 'BETAMARKER', limit: 20 } },{ name: 'query', mode: 'isolated', args: { query: 'BETAMARKER', limit: 20 } },+ { name: 'assemble_evidence', mode: 'isolated', args: { hits: [{ source_id: 'srcbeta', slug: 'notes/beta-note', chunk_id: 0 }], return_unit: 'page' } },{ name: 'get_tags', mode: 'isolated', args: { slug: 'notes/beta-note' } },{ name: 'get_links', mode: 'isolated', args: { slug: 'notes/beta-note' } },{ name: 'get_backlinks', mode: 'isolated', args: { slug: 'people/beta-person' } },diff --git a/test/postgres-rls-scope-inventory.test.ts b/test/postgres-rls-scope-inventory.test.tsindex 854f4ceb30..fb32003e5d 100644--- a/test/postgres-rls-scope-inventory.test.ts+++ b/test/postgres-rls-scope-inventory.test.ts@@ -19,7 +19,8 @@** Reconciliation with the plan's "23 scoped sites": the source has 23 lines* naming `withScopedReadTransaction` = 1 definition + 22 call sites, in 21- * methods (searchVector has 2). The golden pins the exact numbers.+ * methods (searchVector has 2); evidence delivery's getChunkWindows adds one+ * (23 call sites, 22 methods). The golden pins the exact numbers.*/import { describe, expect, test } from 'bun:test';@@ -147,8 +148,8 @@ describe('EO4 RLS scope inventory (master)', () => {const scoping = astScoping(capture.ast);const callSites = Object.values(capture.ast).reduce((a, m) => a + m.directCallSites, 0);- expect(callSites).toBe(22);- expect(Object.values(capture.ast).filter((m) => m.directCallSites > 0).length).toBe(21);+ expect(callSites).toBe(23);+ expect(Object.values(capture.ast).filter((m) => m.directCallSites > 0).length).toBe(22);const byMethod = new Map<string, RuntimeObservation[]>();for (const [key, obs] of Object.entries(capture.runtime)) {diff --git a/test/public-exports.test.ts b/test/public-exports.test.tsindex 7c3c9c2ced..eeaccf767c 100644--- a/test/public-exports.test.ts+++ b/test/public-exports.test.ts@@ -49,6 +49,7 @@ const EXPECTED_EXPORTS: ExpectedExport[] = [{ subpath: 'gbrain/backoff', canary: [] },{ subpath: 'gbrain/search/hybrid', canary: ['hybridSearch', 'rrfFusion'] },{ subpath: 'gbrain/search/expansion', canary: ['expandQuery'] },+ { subpath: 'gbrain/search/evidence-delivery', canary: ['assembleEvidenceForHits', 'evidenceFingerprint', 'deliverEvidence'] },{ subpath: 'gbrain/eval/longmemeval/reader', canary: ['resolveReaderConfig', 'buildReaderRequest', 'readerConfigHash'] },{ subpath: 'gbrain/think', canary: ['runThink', 'stripGapsSection'] },{ subpath: 'gbrain/ai/gateway', canary: ['configureGateway', 'embed'] },@@ -78,7 +79,7 @@ describe('public exports — package.json exports map', () => {// Removing exports: see CLAUDE.md "Removing any of these is a// breaking change going forward" — bump minor and update this count.// 23→24 (2026-08 fix wave): ./core/skillopt (audit skillopt-cats-11).- expect(count).toBe(27);+ expect(count).toBe(28);});test('EXPECTED_EXPORTS list matches the exports map exactly (no drift)', () => {diff --git a/test/recall-federated-namesakes.test.ts b/test/recall-federated-namesakes.test.tsnew file mode 100644index 0000000000..238fa25478--- /dev/null+++ b/test/recall-federated-namesakes.test.ts@@ -0,0 +1,90 @@+/**+ * Federated recall({ entity }) keeps same-slug namesakes in different sources+ * apart. The identity key is (source_id, slug): two pages that share a slug in+ * two granted sources are different entities unless an entity-identity group+ * links them. Unlinked namesakes are refused (no facts, the candidates named+ * so the caller can pick a source); linked members merge; every fact row+ * carries its source_id. (gbrain-evals N4 entity-resolution, bug 2.)+ *+ * Synthetic data only.+ */+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { operations } from '../src/core/operations.ts';+import { linkEntityIdentity } from '../src/core/entity-identity.ts';++let engine: PGLiteEngine;+const recall = operations.find(o => o.name === 'recall')!;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await engine.executeRaw(`INSERT INTO sources (id, name, config) VALUES ('team', 'team', '{}')`);+ for (const source of ['default', 'team']) {+ // Two different people who share a name and slug, one per source.+ await importFromContent(engine, 'people/sam-example',+ `---\ntitle: Sam Example\ntype: person\n---\n\n# Sam Example\n\nThe ${source} Sam.\n`, { noEmbed: true, sourceId: source });+ await engine.insertFact({ fact: `fact about the ${source} Sam`, entity_slug: 'people/sam-example', source: 'note', visibility: 'world', embedding: null }, { source_id: source });+ // One person with a page in each source, linked by an identity group.+ await importFromContent(engine, 'people/theo-example',+ `---\ntitle: Theo Example\ntype: person\n---\n\n# Theo Example\n`, { noEmbed: true, sourceId: source });+ await engine.insertFact({ fact: `theo fact from ${source}`, entity_slug: 'people/theo-example', source: 'note', visibility: 'world', embedding: null }, { source_id: source });+ }+ await engine.insertFact({ fact: 'only-default fact', entity_slug: 'people/uma-example', source: 'note', visibility: 'world', embedding: null }, { source_id: 'default' });+ await linkEntityIdentity(engine, { entityId: 'theo', slug: 'people/theo-example', sourceId: 'default' });+ await linkEntityIdentity(engine, { entityId: 'theo', slug: 'people/theo-example', sourceId: 'team' });+});++afterAll(async () => {+ await engine.disconnect();+});++const federated = () => ({ engine, config: {}, logger: console, dryRun: false, remote: true, sourceId: 'default', auth: { allowedSources: ['default', 'team'] } }) as any;+const single = () => ({ engine, config: {}, logger: console, dryRun: false, remote: true, sourceId: 'default', auth: { allowedSources: ['default'] } }) as any;++describe('federated recall({ entity }) and same-slug namesakes', () => {+ for (const entity of ['Sam Example', 'people/sam-example']) {+ test(`unlinked namesakes are refused, not merged (${entity})`, async () => {+ const res = await recall.handler(federated(), { entity }) as any;+ expect(res.facts).toEqual([]);+ expect(res.total).toBe(0);+ expect(res.ambiguous_entity.candidates).toEqual([+ { source_id: 'default', entity_slug: 'people/sam-example' },+ { source_id: 'team', entity_slug: 'people/sam-example' },+ ]);+ });++ test(`the since arm refuses the same way (${entity})`, async () => {+ const res = await recall.handler(federated(), { entity, since: '3650d' }) as any;+ expect(res.facts).toEqual([]);+ expect(res.ambiguous_entity.candidates.map((c: any) => c.source_id)).toEqual(['default', 'team']);+ });+ }++ test('source_id narrows the read to one namesake, labelled', async () => {+ const res = await recall.handler(federated(), { entity: 'Sam Example', source_id: 'team' }) as any;+ expect(res.facts.map((f: any) => [f.fact, f.source_id])).toEqual([['fact about the team Sam', 'team']]);+ expect(res.ambiguous_entity).toBeUndefined();+ });++ test('identity-linked members merge, each row labelled with its source', async () => {+ const res = await recall.handler(federated(), { entity: 'Theo Example' }) as any;+ expect(res.ambiguous_entity).toBeUndefined();+ expect(res.facts.map((f: any) => [f.fact, f.source_id]).sort()).toEqual([+ ['theo fact from default', 'default'],+ ['theo fact from team', 'team'],+ ]);+ });++ test('an entity with facts in one granted source is unaffected, and labelled', async () => {+ const res = await recall.handler(federated(), { entity: 'people/uma-example' }) as any;+ expect(res.facts.map((f: any) => [f.fact, f.source_id])).toEqual([['only-default fact', 'default']]);+ });++ test('a single-source caller reads its own Sam, labelled', async () => {+ const res = await recall.handler(single(), { entity: 'Sam Example' }) as any;+ expect(res.facts.map((f: any) => [f.fact, f.source_id])).toEqual([['fact about the default Sam', 'default']]);+ });+});diff --git a/test/remote-privacy-sweep.test.ts b/test/remote-privacy-sweep.test.tsindex 56a7f43c11..06ddf5a27a 100644--- a/test/remote-privacy-sweep.test.ts+++ b/test/remote-privacy-sweep.test.ts@@ -159,6 +159,7 @@ const PARAM_FACTORY: Record<string, Record<string, unknown>> = {list_pages: {},search: { query: 'WORLDSWEEP' },query: { query: 'WORLDSWEEP' },+ assemble_evidence: { hits: [{ source_id: 'default', slug: WORLD_FENCE_SLUG, chunk_id: 0 }], return_unit: 'page' },recall: { entity: WORLD_PAGE_SLUG },entity: { name: WORLD_PAGE_SLUG },synthesize: { entity: WORLD_PAGE_SLUG },@@ -236,6 +237,7 @@ const EXPECTED_OUTCOME: Record<string, Outcome> = {list_pages: 'data',search: 'data',query: 'data',+ assemble_evidence: 'data',recall: 'data',entity: 'data',delta: 'data',diff --git a/test/search-date-bound-non-iso.test.ts b/test/search-date-bound-non-iso.test.tsnew file mode 100644index 0000000000..91d87cc3f8--- /dev/null+++ b/test/search-date-bound-non-iso.test.ts@@ -0,0 +1,86 @@+/**+ * Search date bounds accept only what the contract documents: YYYY-MM-DD, an+ * ISO-8601 timestamp, or a relative duration. JavaScript's Date.parse accepts+ * far more ("May 5" reads as 2001-05-05 in Bun), and such a string used to+ * pass validation, fail the database's timestamptz cast inside both lexical+ * arms, be swallowed as a degraded arm and come back as []. It is now+ * rejected up front, and a datetime cast error that still reaches an arm is+ * surfaced instead of swallowed. (gbrain-evals N3 temporal-asof, bug 4.)+ *+ * Synthetic data only.+ */+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { operations } from '../src/core/operations.ts';+import { hybridSearch, resolveDateBoundary } from '../src/core/search/hybrid.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import type { SearchResult } from '../src/core/types.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ const ctx = { engine, config: { engine: 'pglite', database_path: ':memory:' }, logger: console, dryRun: false, remote: false, sourceId: 'default' } as any;+ await operations.find(o => o.name === 'put_page')!.handler(ctx, { slug: 'notes/a', content: '---\ntype: note\ntitle: A\ndate: 2024-06-01\n---\nzebrafish note\n' });+});++afterAll(async () => {+ await engine.disconnect();+});++describe('resolveDateBoundary rejects non-ISO strings', () => {+ test.each(['May 5', 'June 2024', '5/5/2024', 'Sat May 05 2024', '2024-06-01T25:00:00Z', '2024-02-30T10:00:00Z', '20240601'])('%p is rejected', (raw) => {+ expect(() => resolveDateBoundary(raw, 'since')).toThrow(/Invalid since/);+ expect(() => resolveDateBoundary(raw, 'until')).toThrow(/Invalid until/);+ });++ test.each(['2024-06-01T10:00', '2024-06-01T10:00:00Z', '2024-06-01T10:00:00.123Z', '2024-06-01 10:00:00+02:00', '2024-06-01T10:00:00-0500'])('%p passes through', (raw) => {+ expect(resolveDateBoundary(raw, 'since')).toBe(raw);+ });+});++describe('query with a non-ISO date bound', () => {+ const query = (since: string) => {+ const ctx = { engine, config: { engine: 'pglite', database_path: ':memory:' }, logger: console, dryRun: false, remote: false, sourceId: 'default' } as any;+ return operations.find(o => o.name === 'query')!.handler(ctx, { query: 'zebrafish', since, expand: false }) as Promise<Array<{ slug: string }>>;+ };++ test('an ISO bound still filters normally', async () => {+ expect((await query('2024-01-01')).map(r => r.slug)).toEqual(['notes/a']);+ });++ test('"May 5" is rejected with a clear error, like "last week"', async () => {+ await expect(query('last week')).rejects.toThrow(/Invalid since value/);+ await expect(query('May 5')).rejects.toThrow(/Invalid since value "May 5"/);+ });+});++describe('a datetime cast error in a lexical arm is not swallowed', () => {+ const castError = () => Object.assign(new Error('invalid input syntax for type timestamp with time zone: "May 5"'), { code: '22007' });+ const fake = (arms: { searchKeyword: () => Promise<SearchResult[]>; searchTitles: () => Promise<SearchResult[]> }) => ({+ kind: 'pglite',+ getConfig: async () => null,+ executeRaw: async () => [],+ resolveAliases: async () => new Map(),+ getPage: async () => null,+ getContentFlagsByPageIds: async () => new Map(),+ getUnverifiedExtractionPageIds: async () => new Map(),+ relationalFanout: async () => [],+ searchVector: async () => [],+ ...arms,+ }) as unknown as BrainEngine;++ test('keyword arm cast error rethrows instead of returning []', async () => {+ const err = castError();+ await expect(hybridSearch(fake({ searchKeyword: () => Promise.reject(err), searchTitles: async () => [] }), 'orchard telemetry notes', { limit: 5 }))+ .rejects.toBe(err);+ });++ test('title arm cast error rethrows too', async () => {+ const err = castError();+ await expect(hybridSearch(fake({ searchKeyword: async () => [], searchTitles: () => Promise.reject(err) }), 'orchard telemetry notes', { limit: 5 }))+ .rejects.toBe(err);+ });+});