Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
v0.59.13.0 fix(search): page-grain fusion, reranker order through identity tiers, soft entity detail, newest-first trajectories, filter parity, LongMemEval gold-label leak (#5676)
Garry Tanb80cad61e472
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex d952fb4918..34996a6bd0 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.59.11.0",+ "version": "0.59.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 6b698ec59e..ddd0b74a35 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.59.11.0",+ "version": "0.59.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 cc4b5969d4..75ca095b49 100644--- a/BOOTSTRAP_FOR_AGENTS.md+++ b/BOOTSTRAP_FOR_AGENTS.md@@ -1,4 +1,4 @@-<!-- gbrain-runbook-stamp: 0.59.11.0 -->+<!-- gbrain-runbook-stamp: 0.59.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 54ed07c4fd..f4cadfdef1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,52 @@ 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.59.13.0] - 2026-09-28++**Search now credits a page when several retrieval methods agree on it, keeps the reranker's order, and stops hiding timeline evidence behind "who is" questions.**++GBrain finds candidates three ways: by words, by meaning and by title. Each method picks the best passage from a page, and they often pick different passages. Search used to count those as separate candidates, so a page that every method ranked first could lose to a page every method ranked second. Votes for a page now add up, whichever passage each method chose.++Several other ranking paths quietly undid good work. Name lookups re-sorted results after the reranker had ordered them. Questions phrased like "who is ..." or "tell me about ..." searched only page summaries, so an answer that lived in a dated timeline entry could not be found. A name mentioned inside a question never triggered the name-match boost. Those are fixed.++| Situation | Before | Now |+| --- | --- | --- |+| Page ranked first by two methods through different passages | Could lose to a page ranked second by both | Ranks first |+| Name lookup after reranking | Non-matching results fell back to pre-rerank order | Reranker order kept |+| "Who is the founder of X?" with the answer in a timeline entry | Answer invisible | Found; summaries get a mild preference |+| "Tell me about the widget tracker" (a declared alias) | No name boost | Named page boosted |+| Reranker times out or errors | Nothing on the wire said so | Response reports `rerank_failed` |+| Entity with more than 100 tracked values | "Latest" value was the 100th oldest | Latest value is the newest |++The LongMemEval harness also stopped leaking its answer key. Every correct conversation in that dataset has an id starting with `answer_`, and that id reached page names and the answer model's prompt. Sessions are now imported under opaque ids; scoring still uses the real ids privately.++Measured honestly: on a fixed 215-question LongMemEval slice with the reranker off, strict session recall at 5 moved from 203 to 202 (one question lost, none gained), with the same answer-bearing passages returned. The page-voting fix corrects ranking on pages with several matching passages; it is not a recall win on that benchmark.++### To take advantage of v0.59.13.0++Run `gbrain upgrade`. There is no migration. Ranking changes apply to the next search. `gbrain search "<query>" --explain` shows `exact_match_boost` when a name in your question matched a page, and a `degraded` line when the reranker failed. If you compare against older LongMemEval receipts, re-run both sides: session ids in new rows are opaque in slugs and prompts.++### Itemized changes++- Fusion votes per page: each retrieval list adds one vote per page at its best rank, and the page's lead passage carries the summed vote. The page's other passages keep their own votes, so they cannot push other pages out of a short result list (`src/core/search/rrf-page-fusion.ts`).+- The alias hop and the exact-lookup tier move identity results to the front without re-sorting everything else, so the reranker's order survives.+- An automatically detected "entity" question no longer restricts search to page summaries. It applies a 1.2x summary preference instead of 2x. An explicit `detail: low` keeps the strict filter.+- The name-match boost fires when a page title, slug or declared alias is mentioned inside the question, not only when the whole question equals it.+- A hard reranker failure (timeout, provider error, budget) stamps the `rerank_failed` degraded stage. The LongMemEval reranker gate treats it as un-reranked.+- Trajectory reads return the newest N facts, in chronological order, on both engines.+- Unified multimodal search re-scores against the multimodal embedding column, and cosine similarity returns 0 for vectors of different sizes instead of a wrong number.+- `hybridSearch` passes `exclude_slugs`, `exclude_slug_prefixes` and `include_slug_prefixes` to every retrieval method. The embedded engine's keyword search honors `exclude_slugs` and `type` like Postgres.+- The compiled-truth guarantee adds a summary passage instead of evicting a matching one, and results stay in score order.+- Backlink boosts count distinct linking pages, ignoring self-links and duplicate edges.+- `get_tags` returns nothing to remote callers for private or deleted pages.+- `gbrain eval --strategy vector` embeds queries the way search does, so vector baselines are not handicapped on providers with separate query and document modes.+- NamedThingBench counts a failed search as an error and a miss; any error fails the gate.+- README, capabilities and retrieval docs cite the September 9, 2026 BrainBench refresh (relationship questions: P@5 0.3421, R@5 0.9791) instead of the retired 49.1% / "+31.4 points" claim.++### For contributors++- New test files: `test/search/rrf-page-grain.test.ts`, `test/search/identity-tiers-keep-rerank-order.test.ts`, `test/search/auto-entity-detail-soft.test.ts`, `test/search/title-mention-boost.test.ts`, `test/search/exclude-filters-hybrid.test.ts`, `test/search/eval-vector-query-embed.test.ts`, `test/get-tags-remote-privacy.test.ts`, `test/longmemeval-gold-leak.slow.test.ts`; Postgres parity cases for keyword excludes, trajectory limits and tag visibility in `test/e2e/engine-parity.test.ts`.+## [0.59.11.0] - 2026-09-28**Your brain stops losing notes, stops linking people to the wrong person, and forgets links and dates you deleted.**diff --git a/README.md b/README.mdindex 3b6118dfa0..d9622db591 100644--- a/README.md+++ b/README.md@@ -23,7 +23,7 @@ I'm Garry Tan, President and CEO of Y Combinator. I built GBrain to run my own AAlongside keyword and semantic retrieval, GBrain offers two optional ways to use your stored knowledge:- **A synthesis layer that gives you the actual answer.** Synthesized, well-cited prose across people, companies, deals, and ideas. Not "here are 10 chunks that mention your query"; an actual answer with citations and an explicit note on what the brain doesn't know yet. The gap analysis is the part that changes how you use the brain.-- **A typed knowledge graph.** Trusted local page writes extract supported references without LLM calls when auto-linking is enabled. Remote `put_page` does not extract graph edges inline: stdio has best-effort startup/idle sweeps; HTTP needs explicit maintenance or authorized `add_link` calls. Ask "who works at acme-example?" to use stored relationships. A 240-page Opus-generated rich-prose BrainBench run reported **P@5 49.1%, R@5 97.9%**, with **+31.4 points P@5** over its graph-disabled variant. These are scoped benchmark results, not a guarantee for every corpus. Scorecards: [gbrain-evals](https://github.com/garrytan/gbrain-evals).+- **A typed knowledge graph.** Trusted local page writes extract supported references without LLM calls when auto-linking is enabled. Remote `put_page` does not extract graph edges inline: stdio has best-effort startup/idle sweeps; HTTP needs explicit maintenance or authorized `add_link` calls. Ask "who works at acme-example?" to use stored relationships. On BrainBench relationship questions a graph adapter scored **P@5 0.3421, R@5 0.9791** vs 0.1917 / 0.6874 plain hybrid ([2026-09-09 refresh](https://github.com/garrytan/gbrain-evals/blob/main/docs/benchmarks/2026-09-09-retrieval-refresh.md)): whole systems, not a graph-only lift or a general guarantee.The point of building a 150K-page brain is to use it as a strategic moat. To never lose context. To query what's in your own head without re-reading it. The brain layer is what makes the moat usable. The 24/7 dream cycle is what keeps it sharp. Both run on your hardware, your DB, your keys.diff --git a/VERSION b/VERSIONindex 373cda93c1..4d23a329fa 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-0.59.11.0+0.59.13.0diff --git a/docs/architecture/RETRIEVAL.md b/docs/architecture/RETRIEVAL.mdindex c91de6f74a..edcb194612 100644--- a/docs/architecture/RETRIEVAL.md+++ b/docs/architecture/RETRIEVAL.md@@ -6,7 +6,7 @@ Vector search alone underdelivers on real personal-knowledge queries. This doc e1. **Vector (HNSW on pgvector)** — semantic similarity. Catches "who works on retrieval quality at acme-example?" → pages mentioning "alice-example + retrieval" even when the user never typed "acme".2. **BM25 keyword** — lexical match. Catches names, exact phrases, code identifiers, anything where the user remembers the literal token. Survives the cases where vector search drifts into thematic neighbors.-3. **Reciprocal-rank fusion (RRF)** — merges vector + keyword rankings without weighting one over the other globally. Each strategy gets to vote.+3. **Reciprocal-rank fusion (RRF)** — merges vector + keyword rankings without weighting one over the other globally. Each strategy gets to vote, and the vote is for a PAGE: arms return each page's best chunk, often different chunks, so fusion sums a page's votes across arms onto the page's lead chunk (largest own vote, ties to the vector arm's chunk); the page's other chunks keep their own votes so they cannot crowd other pages out of a chunk-limited result.4. **Knowledge graph traversal** — follows recorded typed edges. It can answer relationship queries whose relevant endpoints are not close in embedding space; it depends on the edges being present and correct, and does not by itself establish causality.## Why each one alone fails@@ -23,17 +23,22 @@ Vector search alone underdelivers on real personal-knowledge queries. This doc eBrainBench (corpus + harness in the sibling [gbrain-evals](https://github.com/garrytan/gbrain-evals) repo) measures retrieval P@5, R@5, MRR, nDCG@5 on a 240-page Opus-generated rich-prose corpus. (This is the retrieval-ranking benchmark; the in-repo `gbrain eval brainbench` suite — [`docs/eval/BRAINBENCH.md`](../eval/BRAINBENCH.md) — gates the memory behaviors *above* retrieval: unprompted context push, write-back fidelity, cross-session continuity.)-| Strategy | P@5 | R@5 | Notes |-|---|---|---|---|-| ripgrep BM25 only | ~18 | ~75 | Lexical-only baseline |-| vector-only RAG | ~18 | ~80 | Standard RAG implementation |-| gbrain graph-disabled (hybrid + RRF, no graph traversal) | ~18 | ~85 | Hybrid alone |-| **gbrain default (full stack)** | **49.1** | **97.9** | Graph + extract-quality lift |+The [September 9, 2026 refresh](https://github.com/garrytan/gbrain-evals/blob/main/docs/benchmarks/2026-09-09-retrieval-refresh.md) (gbrain v0.48.4.0, three ingestion+orders, fixed-denominator P@5) measured the 145 relationship questions:-The recorded lift on that synthetic corpus was **+31 P@5 points** for graph-plus extraction-quality changes together. It does not isolate the graph's-contribution, establish universal superiority, or predict accuracy on a-different corpus. See the linked harness for the experiment's scope.+| Adapter | Mean P@5 | Mean R@5 |+|---|---:|---:|+| Specialized `gbrain` (recognizes four question templates, follows the fixture graph) | **0.3421** | **0.9791** |+| Reference hybrid | 0.1917 | 0.6874 |+| Keyword ranker | 0.1710 | 0.6244 |+| Vector only | 0.1076 | 0.4069 |++The specialized adapter is strong on the templates it understands, but this is a+comparison between whole systems. The refresh found that the older headline+(P@5 49.1%, "+31.4 points over graph-disabled") was not a graph-only effect and+used metric helpers since corrected; do not cite it. On the fuzzy and externally+authored families the keyword and vector paths win some comparisons. None of+this predicts accuracy on a different corpus.## Auto-link: why zero-LLM-call edge extraction works@@ -189,8 +194,9 @@ hybrid recall + fusion:├── relational (typed-edge recall arm — relational queries only)├── source-aware re-rank (CASE in SQL)├── role-tagged arms; variant/clause lists weighted by search.expansion_variant_budget INSIDE the fusion (fusion-lists.ts)- └── RRF fusion → cosine re-score → post-fusion boosts- (backlink / salience / recency / graph signals / exact-match;+ └── page-grain RRF fusion → cosine re-score → post-fusion boosts+ (backlink / salience / recency / graph signals / exact-match,+ which also fires when a title, slug or alias is named in the query;the metadata boosts are skipped when the vector arm was the onlyvoter — search.metadata_boost_gate=lexical, metadata-boost-gate.ts)│@@ -209,7 +215,8 @@ relational re-pin (relational-arm rows back above the reranked text rows, inreordered — src/core/search/relational-rerank-pin.ts)│▼-alias hop (exact alias match injects/boosts the canonical page)+alias hop (exact alias match injects/boosts the canonical page; like the+ exact-lookup tier below it never re-sorts, so the reranked order holds)│▼exact-lookup tier (lookup-shaped queries only: slug + exact-title probesdiff --git a/docs/architecture/key-files/commands-3.md b/docs/architecture/key-files/commands-3.mdindex 2a0fe705c5..567e9ad3f3 100644--- a/docs/architecture/key-files/commands-3.md+++ b/docs/architecture/key-files/commands-3.md@@ -19,7 +19,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/eval-suspected-contradictions.ts` + `src/core/eval-contradictions/{judge,runner,types,date-filter,cost-tracker,cache,severity-classify,cross-source,trends,calibration,judge-errors,auto-supersession,fixture-redact}.ts` — `gbrain eval suspected-contradictions [run|trend|review]`. Probe samples top-K retrieval pairs per query (cross-slug + intra-page chunk-vs-take), date pre-filters (3-rule layered — same-paragraph-dual-date overrides separation rule), LLM judge (query-conditioned; UTF-8-safe truncation; confidence-floor double-enforcement; resolution_kind output drives paste-ready commands), persistent cache keyed on `(chunk_a_hash, chunk_b_hash, model_id, prompt_version, truncation_policy)` (prompt edits cleanly invalidate prior verdicts), Wilson 95% CI calibration on the headline percentage with `small_sample_note` when n<30, judge_errors as first-class typed counters (parse_fail/refusal/timeout/http_5xx/unknown — avoids bias from silent skip), trend writes to `eval_contradictions_runs`, source-tier breakdown reuses `DEFAULT_SOURCE_BOOSTS` prefix logic, deterministic sampling (combined_score DESC + lex tiebreaker for stable cache hit-rate). Hermetic via `judgeFn` + `searchFn` DI in the runner; never touches the real gateway in tests. Engine surface: `BrainEngine.listActiveTakesForPages` (batched), `writeContradictionsRun` + `loadContradictionsTrend`, `getContradictionCacheEntry` + `putContradictionCacheEntry` + `sweepContradictionCache`. Schema migrations v51 + v52. MCP op `find_contradictions` (read scope, NOT localOnly, NOT in subagent allowlist — user-initiated only). Doctor check surfaces high-severity findings with paste-ready resolution commands; synthesize phase pre-fetches the latest probe's top-5-by-severity findings and threads them into `buildSynthesisPrompt` as an informational block. Architecture doc: `docs/contradictions.md`.-- `src/commands/eval-trajectory.ts` + `src/commands/founder-scorecard.ts` + `src/core/trajectory.ts` — temporal trajectory + founder scorecard. `gbrain eval trajectory <entity>` shows the chronological typed-claim history (mrr/arr/team_size/etc) with regressions auto-flagged inline; `gbrain founder scorecard <entity>` rolls up claim_accuracy / consistency / growth_trajectory / red_flags into one JSON. Pure-function math in `trajectory.ts`: `detectRegressions(points, threshold)` walks consecutive metric-value pairs per metric (10% drop default, env override `GBRAIN_TRAJECTORY_REGRESSION_THRESHOLD`); `computeDriftScore(points)` returns `1 - mean(cosine(emb[i], emb[i-1]))` over existing embeddings (null when <3 embedded points). Backed by `BrainEngine.findTrajectory(opts)` — both Postgres and PGLite, single SQL query, deterministic `ORDER BY valid_from ASC, id ASC`. Source-scoped via the `sourceId` scalar / `sourceIds` array dual pattern; visibility-filtered for remote callers. MCP op `find_trajectory` (read scope, NOT localOnly) registered after `find_experts`. Migration v67 adds optional typed-claim columns (`claim_metric`, `claim_value`, `claim_unit`, `claim_period`) + a partial index on `(entity_slug, claim_metric, valid_from) WHERE claim_metric IS NOT NULL`. Fence widens from 10 to 14 cells when any row has typed data; renderer stays at 10 cells when none do (no churn diff on existing fences). Metric labels normalize to lowercase snake_case via `normalizeMetricLabel` (15-entry seed map). The `consolidate` cycle phase does semantic upsert keyed on `(page_id, claim, since_date)` (so re-running the cycle after `extract_facts` clears `consolidated_at` cannot append duplicates via `MAX(row_num)+1`) and writes chronological `valid_until` on each cluster's older facts. The `extract_facts` cycle phase batch-embeds via `gateway.embed()` before insert AND threads `pages.effective_date` as the `pageEffectiveDate` fallback for `valid_from` (precedence: fence-row > pageEffectiveDate > now()). The contradiction probe MUST NOT write `valid_until` — grep guard at `test/eval-contradictions/no-valid-until-write.test.ts`. Haiku extraction lives in `src/core/facts/extract.ts` (not the `extract-facts.ts` cycle phase); its output cap is config `facts.extraction_max_tokens` (default 4000), a `stopReason: 'length'` response retries once at 2× the cap, and persistent truncation warns loudly on stderr instead of silently extracting zero facts. Mixed extractor arrays salvage valid candidates and warn with the dropped malformed count; all-malformed output still fails retryably, while an explicitly empty facts array remains a successful empty result. `pageEffectiveDate` is OPTIONAL because `fence-write.ts` callers have no Page object. Migration v89 adds a nullable `event_type TEXT` column on `facts` so the substrate carries event-shaped rows (`event_type='meeting'` / `'job_change'` / `'location_change'`) alongside metric rows. `TrajectoryPoint.event_type: string | null` projected by both engines. `TrajectoryOpts.kind?: 'metric' | 'event' | 'all'` filter (default `'all'`); `founder-scorecard` + `eval-trajectory` pass `kind: 'metric'` explicitly. Back-compat pinned by `test/regressions/v0_40_2_0-trajectory-backcompat.test.ts` (byte-identical `computeFounderScorecard` + `computeTrajectoryStats` with and without event rows); engine parity in `test/engine-parity-event-type.test.ts`.+- `src/commands/eval-trajectory.ts` + `src/commands/founder-scorecard.ts` + `src/core/trajectory.ts` — temporal trajectory + founder scorecard. `gbrain eval trajectory <entity>` shows the chronological typed-claim history (mrr/arr/team_size/etc) with regressions auto-flagged inline; `gbrain founder scorecard <entity>` rolls up claim_accuracy / consistency / growth_trajectory / red_flags into one JSON. Pure-function math in `trajectory.ts`: `detectRegressions(points, threshold)` walks consecutive metric-value pairs per metric (10% drop default, env override `GBRAIN_TRAJECTORY_REGRESSION_THRESHOLD`); `computeDriftScore(points)` returns `1 - mean(cosine(emb[i], emb[i-1]))` over existing embeddings (null when <3 embedded points). Backed by `BrainEngine.findTrajectory(opts)` — both Postgres and PGLite, single SQL query that selects the NEWEST `limit` points (`ORDER BY valid_from DESC, id DESC`) and returns them chronologically, so a capped series keeps its latest value. Source-scoped via the `sourceId` scalar / `sourceIds` array dual pattern; visibility-filtered for remote callers. MCP op `find_trajectory` (read scope, NOT localOnly) registered after `find_experts`. Migration v67 adds optional typed-claim columns (`claim_metric`, `claim_value`, `claim_unit`, `claim_period`) + a partial index on `(entity_slug, claim_metric, valid_from) WHERE claim_metric IS NOT NULL`. Fence widens from 10 to 14 cells when any row has typed data; renderer stays at 10 cells when none do (no churn diff on existing fences). Metric labels normalize to lowercase snake_case via `normalizeMetricLabel` (15-entry seed map). The `consolidate` cycle phase does semantic upsert keyed on `(page_id, claim, since_date)` (so re-running the cycle after `extract_facts` clears `consolidated_at` cannot append duplicates via `MAX(row_num)+1`) and writes chronological `valid_until` on each cluster's older facts. The `extract_facts` cycle phase batch-embeds via `gateway.embed()` before insert AND threads `pages.effective_date` as the `pageEffectiveDate` fallback for `valid_from` (precedence: fence-row > pageEffectiveDate > now()). The contradiction probe MUST NOT write `valid_until` — grep guard at `test/eval-contradictions/no-valid-until-write.test.ts`. Haiku extraction lives in `src/core/facts/extract.ts` (not the `extract-facts.ts` cycle phase); its output cap is config `facts.extraction_max_tokens` (default 4000), a `stopReason: 'length'` response retries once at 2× the cap, and persistent truncation warns loudly on stderr instead of silently extracting zero facts. Mixed extractor arrays salvage valid candidates and warn with the dropped malformed count; all-malformed output still fails retryably, while an explicitly empty facts array remains a successful empty result. `pageEffectiveDate` is OPTIONAL because `fence-write.ts` callers have no Page object. Migration v89 adds a nullable `event_type TEXT` column on `facts` so the substrate carries event-shaped rows (`event_type='meeting'` / `'job_change'` / `'location_change'`) alongside metric rows. `TrajectoryPoint.event_type: string | null` projected by both engines. `TrajectoryOpts.kind?: 'metric' | 'event' | 'all'` filter (default `'all'`); `founder-scorecard` + `eval-trajectory` pass `kind: 'metric'` explicitly. Back-compat pinned by `test/regressions/v0_40_2_0-trajectory-backcompat.test.ts` (byte-identical `computeFounderScorecard` + `computeTrajectoryStats` with and without event rows); engine parity in `test/engine-parity-event-type.test.ts`.- `src/commands/eval-whoknows.ts` — `gbrain eval whoknows <fixture.jsonl> [--json] [--skip-replay]`: two-layer eval gate. Layer 1 quality (hand-labeled fixture, top-3 hit rate ≥ 0.8). Layer 2 regression (`eval_candidates` replay set-Jaccard@3 ≥ 0.4). Sparseness fallback: < 20 replay-eligible rows → Layer 2 auto-skips with stderr warning. Stable JSON envelope with `schema_version: 1`; exit 0/1/2 for pass/fail/usage. `WhoknowsFn` callable abstraction makes the gates impl-agnostic; `runEvalWhoknows(engine: BrainEngine | null, args)` picks the impl at entry — thin-client mode (`isThinClient(cfg)`) routes per-query through `callRemoteTool(cfg, 'find_experts', {topic, limit})`, local mode calls `findExperts(engine, ...)` directly. cli.ts adds a thin-client bypass before `connectEngine` (dispatch shape under `src/commands/eval.ts`); the regression gate auto-skips in thin-client mode (no DB access to `eval_candidates`). Public exports `jaccardAtK`, `topKHit`, `readFixture`, `WhoknowsFn`, threshold constants pinned by `test/eval-whoknows.test.ts` (25 cases incl. null-engine signature contract).diff --git a/docs/architecture/key-files/core-search-1.md b/docs/architecture/key-files/core-search-1.mdindex 437ea7cd78..6720529b27 100644--- a/docs/architecture/key-files/core-search-1.md+++ b/docs/architecture/key-files/core-search-1.md@@ -15,11 +15,11 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/date-bounds.ts` — shared public since/until normalization for text and image query paths; hybrid.ts preserves both existing exports. Exact timestamps keep their precision, date-only upper bounds use exclusive next midnight, and invalid calendar dates fail before embedding. Direct legacy afterDate/beforeDate comparisons remain strict by default.-- `src/core/search/dedup.ts` — 4-layer result dedup + compiled-truth guarantee: (1) top 3 chunks per page by score, (2) drop chunks >0.85 Jaccard-similar to already-kept chunks of the SAME page (cross-page near-dups survive — two legitimately similar pages both return), (3) no page type exceeds 60% of results — applied only when the candidate set actually contains multiple page types; a homogeneous set passes through unchanged because dropping (for example) one of three distinct LongMemEval `note` sessions cannot introduce diversity and destroys multi-session recall (pinned by the homogeneous-set case in `test/dedup.test.ts`), (4) max 2 chunks per page (default; the two-pass structural expansion in `hybrid.ts` widens it), (5) ensure at least 1 compiled_truth chunk per page. Page identity is the composite `pageKey()` (source_id, slug) — the one canonical key helper every layer uses, so slug collisions across sources can't collapse recall.+- `src/core/search/dedup.ts` — 4-layer result dedup + compiled-truth guarantee: (1) top 3 chunks per page by score, (2) drop chunks >0.85 Jaccard-similar to already-kept chunks of the SAME page (cross-page near-dups survive — two legitimately similar pages both return), (3) no page type exceeds 60% of results — applied only when the candidate set actually contains multiple page types; a homogeneous set passes through unchanged because dropping (for example) one of three distinct LongMemEval `note` sessions cannot introduce diversity and destroys multi-session recall (pinned by the homogeneous-set case in `test/dedup.test.ts`), (4) max 2 chunks per page (default; the two-pass structural expansion in `hybrid.ts` widens it), (5) ensure at least 1 compiled_truth chunk per page — the page's best compiled_truth chunk is APPENDED (never swapped over a kept chunk, so matching evidence survives) and the final output is re-sorted by score, because slice / token budget / evidence consumers assume score order. Page identity is the composite `pageKey()` (source_id, slug) — the one canonical key helper every layer uses, so slug collisions across sources can't collapse recall.- `src/core/search/embedding-column.ts` — single source of truth for "which `content_chunks.*` column does this query rank against?" Pure functions, no engine I/O: `loadRegistry(cfg)` walks the `embedding_columns` config (DB plane, JSON map keyed by column name with `{provider, dimensions, type}` entries), seeds the OpenAI `embedding` builtin when unset, validates everything before it lands (column-name regex, type ∈ `vector | halfvec`, dims in [1, 8192], provider format) using `Object.create(null)` + `Object.hasOwn` so a key like `constructor` rejects instead of resolving to `Object.prototype.constructor`. `resolveColumn(registry, override?, cfg)` is the boundary call: returns a frozen `ResolvedColumn` descriptor (`{name, provider, dimensions, type}`) honoring per-call override → `search_embedding_column` config → `'embedding'` default; throws `UnknownEmbeddingColumnError` with the list of registered names on miss. `isCacheSafe(resolved, cfg)` compares the full embedding SPACE (provider + dimensions + name) against cfg's default so a repointed `embedding` builtin doesn't serve OpenAI-shaped cache rows. `validateResolvedColumn(descriptor)` re-validates hand-rolled descriptors that bypass the registry (internal-SDK passthrough) so the SQL-injection escape hatch through the descriptor field is closed. Consumed by `hybridSearch`, `gateway.embedQuery(text, {embeddingModel, dimensions})`, `cosineReScore`, and the `query` MCP op (per-call `embedding_column` param). Pinned by `test/search/embedding-column.test.ts` (prototype-pollution, descriptor passthrough, env-only Postgres install, empty-brain coverage gate, cache-space comparison). Write side: `resolveWriteColumnFromConfigRows({searchEmbeddingColumn, embeddingColumnsJson})` resolves upsertChunks's active write target from the raw DB-plane config rows through the same registry/validation chain (legacy `embedding` descriptor when neither row routes elsewhere; `embedding_image` falls back to the legacy text column since image vectors travel in their own INSERT column; malformed registry JSON is forgiven like loadConfigWithEngine; unregistered names throw the paste-ready error), and `vectorCastSuffix(resolved)` is the placeholder-free `'::vector' | '::halfvec(N)'` cast shared by the read fragment builder and the write path so the two casts can't drift. Pinned by `test/e2e/upsert-chunks-registry-column.test.ts`.-- `src/core/search/eval.ts` — Retrieval eval harness: P@k, R@k, MRR, nDCG@k metrics + runEval() orchestrator.+- `src/core/search/eval.ts` — Retrieval eval harness: P@k, R@k, MRR, nDCG@k metrics + runEval() orchestrator. The `vector` strategy runs the production query path: `embedQuery` (query-side `input_type` on asymmetric providers) in the resolved embedding column's model, searched on that column — `embed()` is the document side and would handicap the vector baseline.- `src/core/search/evidence.ts` — the agent-facing why-it-matched contract (so an agent never reads one blended score, decides "no strong match, safe to create", and writes a duplicate over a fully-developed page). `classifyEvidence(r, opts?)` names the strongest signal (precedence: `alias_hit` > `exact_title_match` > `high_vector_match` (real query↔chunk cosine `SearchResult.cosine` ≥ `DEFAULT_HIGH_COSINE_FLOOR=0.8`, overridable via `EvidenceOpts.cosineFloor` / config `search.evidence_cosine_floor` — never the blended score, so a keyword+boost pile-up can't earn the label; keyless/hermetic runs have no cosine and degrade to keyword-based labels; legacy `HIGH_MATCH_FLOOR=0.85` stays exported for back-compat only) > `keyword_exact` (base ≥ `SOLID_MATCH_FLOOR=0.6`) > `weak_semantic`). `createSafetyFor(evidence)` derives the don't-duplicate hint (`exists`/`probable`/`unknown`) the agent keys off INSTEAD of a raw threshold (a blended RRF/cosine score is not a calibrated probability). `stampEvidence(results, opts?)` stamps `evidence` + `create_safety` in place once at pipeline end (after the alias hop, before slice); idempotent.@@ -31,7 +31,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/graph-signals.ts` — per-query graph-signals helper. `applyGraphSignals(results, engine, opts)` runs as the 4th post-fusion stage (after backlink/salience/recency). Three boosts: `ADJACENCY_BOOST=1.05` (page linked from 2+ OTHER top-K results — local hub for THIS query), `CROSS_SOURCE_BOOST=1.10` (page linked from 2+ DIFFERENT sources — corroborated across team brains, dormant in single-source brains), `SESSION_DEMOTE=0.95` (3+ results from same chat session — keep the highest-scoring at full score, demote the rest). All three inherit the floor-ratio gate preventing weak pages from being boosted past strong ones via popularity. `computeScoreDistribution(results)` emits min/p25/p50/p75/p95/max + `reorder_band_width`. `sessionPrefix(slug)` extracts the chat-session anchor (`chat/2026-05-15-...`). Pure `pairedBootstrapPValue(deltas, resamples, rng)` exported for eval gates. Test seam via `adjacencyFn` DI. Fail-open: any error logs via `logGraphSignalsFailure` (JSONL audit via `audit-writer`) and returns the input array unchanged. Pinned by `test/search/graph-signals.test.ts` (incl. the IRON-RULE floor-gate guard). The atoms/ namespace is excluded from session diversification even when a later segment resembles a date or chat marker; daily, meeting and transcript siblings retain their existing demotion.-- `src/core/search/hybrid.ts` — `Promise<SearchResult[]>` return shape. `onMeta?: (m: HybridSearchMeta) => void` callback so op-layer capture records what hybridSearch actually did; callers that don't need it leave it undefined. `HybridSearchOpts.queryEmbedFn?: (text) => Float32Array | Promise<Float32Array>` is the hermetic eval seam: when set, the TEXT vector arm's query embedding comes from this function instead of the gateway's query-embed path AND the no-embedding-provider keyword-only short-circuit is bypassed, so deterministic eval canaries (`gbrain eval gate --embedder deterministic`, `scripts/run-eval-canary.ts`) run the vector arm with no provider key; never set on production paths — absent, the production path is untouched, and bare `hybridSearch` never touches the semantic query cache so the seam can't poison `query_cache`. `HybridSearchOpts.types?: PageType[]` (on `SearchOpts`) threads a multi-type filter into per-engine `searchKeyword` + `searchVector` + `searchKeywordChunks` as `AND p.type = ANY($N::text[])` (primary consumer `gbrain whoknows`, filters to `['person','company']`); AND-applies alongside the single-value `type` filter. `hybridSearch` resolves the embedding column at the boundary via `resolveColumn(loadRegistry(cfg), opts.embedding_column, cfg)` from `src/core/search/embedding-column.ts`, threads the `ResolvedColumn` descriptor (not a raw string) into per-engine `searchVector`, and uses `isCacheSafe(resolved, cfg)` for the cache-skip decision so a repointed `embedding` builtin doesn't leak across vector spaces. `cosineReScore` calls `engine.getEmbeddingsByChunkIds(ids, resolved.name)` so rerank uses vectors from the active column, not the hardcoded OpenAI `embedding`, and hydrates each result's raw query↔chunk `cosine` onto `SearchResult` (the calibrated signal evidence and `--explain` consume). `SearchOpts.onVectorPoolMeta` reports bounded candidate incompleteness after up to three pool escalations. SQL limits and offsets are independent of ef_search, filtered short pools need an exhaustion witness, and Postgres alone can use one exact fallback inside the remaining deadline. Hybrid and direct image query paths publish the scoped details and recall-affecting degraded stage; an exhausted genuine small corpus does not emit a false warning. The `query` MCP op accepts `embedding_column` for per-call A/B; `search` (keyword-only) rejects it. Two post-fusion stages + evidence stamp: `applyTitleBoost(results, query, titleBoost, floorThreshold)` multiplies a result's score by the resolved `title_boost` when `isTitlePhraseMatch` fires, stamps `title_match_boost`, inherits the floor-ratio gate so a title match can't shove a much-stronger page below it; `applyAliasHop(engine, results, query, opts)` normalizes the query, calls `engine.resolveAliases`, and on exact normalized-alias match surfaces that page at top-of-organic + epsilon with `alias_hit=true`; `stampEvidence(...)` runs LAST (after the alias hop, before slice) on every path — keyword-only, no-embed, and full hybrid — so MCP callers and `--explain` read the same `evidence` + `create_safety` contract. `title_boost` resolved from the mode bundle and threaded in. `runPostFusionStages` has a 4th stage (`graphSignalsEnabled`, `onGraphMeta`, `onScoreDistribution`). `base_score` stamped at function entry idempotently (captured ONCE before any boost stage mutates `score`). Each post-fusion stage stamps its multiplier: `applyBacklinkBoost`→`backlink_boost`, `applySalienceBoost`→`salience_boost`, `applyRecencyBoost`→`recency_boost`. `applyReranker` (earlier in the pipeline) stamps `reranker_delta` as a rank delta (positive = improved). `applyExactMatchBoost` in `src/core/search/intent-weights.ts` stamps `exact_match_boost` when fired. Per-stage attribution powers `gbrain search --explain` — every boost surface carries its own field so `formatResultsExplain` reads them all without coupling to internal stage ordering. with `src/core/search/sql-ranking.ts` + `src/core/operations.ts` + `src/core/types.ts`: agent-warning channel. `SearchResult.content_flag?: {reason, detail}` (optional field in `types.ts`) is stamped post-fusion by `stampContentFlags` (the `stampEvidence` precedent) in `hybridSearch` AND in the keyword-only `search` MCP op so both retrieval paths surface the marker. `get_page` returns a top-level `content_flag` parallel field via `getContentFlag(page.frontmatter)`. `buildVisibilityClause` (sql-ranking.ts) ANDs in `QUARANTINE_FILTER_FRAGMENT` so quarantined pages are excluded from all six search call sites (alongside soft-delete + archived-source filters). Pinned by `test/sql-ranking.test.ts` + `test/e2e/quarantine-search-exclusion.test.ts`. Cross-modal routing at the embed step: `effectiveModality` resolves per-call `opts.crossModal` (literal `'auto'` → undefined) → `suggestions.suggestedModality` → `'text'`. Image route: `embedQueryMultimodal` + `searchVector({embeddingColumn: 'embedding_image'})`, skipping expansion + keyword. `'both'` route: parallel text + image vector searches merged via `rrfFusionWeighted` with `effectiveRrfK(baseRrfK, weight)` from the configured cross-modal weights. Unified routing fires when `search.unified_multimodal` is true — bypasses dual-column branching, runs `embedQueryMultimodal` + `searchVector({embeddingColumn: 'embedding_multimodal'})`, fail-open on zero rows (non-strict falls through to dual-column). LLM modality escalation fires only when no explicit per-call opt is set AND the regex returned `'text'` AND `search.cross_modal.llm_intent` is on AND `isAmbiguousModalityQuery` fires; fail-open on every error. `compiledTruthBoost(result, applyBoost)` is exported for direct predicate tests: a synthetic chunkless title row (`chunk_id === 0` AND blank `chunk_text`) never receives the 2x compiled-truth boost (`test/search/compiled-truth-boost.test.ts`). The reranker pass-through callback is typed with `RerankPassThroughReason` imported from `rerank.ts` — one union, not a re-declaration. RRF inputs are assembled by ONE `composeFusionLists` call (next entry) over role-tagged `vectorArms` built with `pushVectorList` at every assembly site (unified, image-only, text/both, and the `allSettled` salvage path — where the `original` role additionally requires the original's `searchVector` to have succeeded); after `expandFn`, `queries[0]` is re-enforced to be the caller's query and repeats are deduped, so a variant can never take the anchor role. `HybridSearchOpts.onRerankPool` (eval-only, best-effort) fires immediately before `applyAutocut` with the exact pre-autocut `returnPool` — post alias-hop / exact-lookup / adaptive-return, unscored injected rows included, even when autocut is off — plus the deduped pre-rerank order, so an offline autocut replay is byte-faithful. Immediately after `applyReranker` — only when it actually reordered (`reranked !== deduped`) and never for image modality — `pinRelationalRows` (`relational-rerank-pin.ts`) re-pins the relational arm's rows above the reranked text rows bounded by `resolvedMode.relational_rerank_pin`, stamps `relational_pinned`, and emits `HybridSearchMeta.relational_rerank_pin`; `ensureRelationalEvidenceSlot` still runs after autocut (usually a no-op on relational queries now — it remains the page-1 guarantee for pin 0, reranker fail-open, and arm rows dropped before the pin).+- `src/core/search/hybrid.ts` — `Promise<SearchResult[]>` return shape. `onMeta?: (m: HybridSearchMeta) => void` callback so op-layer capture records what hybridSearch actually did; callers that don't need it leave it undefined. `HybridSearchOpts.queryEmbedFn?: (text) => Float32Array | Promise<Float32Array>` is the hermetic eval seam: when set, the TEXT vector arm's query embedding comes from this function instead of the gateway's query-embed path AND the no-embedding-provider keyword-only short-circuit is bypassed, so deterministic eval canaries (`gbrain eval gate --embedder deterministic`, `scripts/run-eval-canary.ts`) run the vector arm with no provider key; never set on production paths — absent, the production path is untouched, and bare `hybridSearch` never touches the semantic query cache so the seam can't poison `query_cache`. `HybridSearchOpts.types?: PageType[]` (on `SearchOpts`) threads a multi-type filter into per-engine `searchKeyword` + `searchVector` + `searchKeywordChunks` as `AND p.type = ANY($N::text[])` (primary consumer `gbrain whoknows`, filters to `['person','company']`); AND-applies alongside the single-value `type` filter. `hybridSearch` resolves the embedding column at the boundary via `resolveColumn(loadRegistry(cfg), opts.embedding_column, cfg)` from `src/core/search/embedding-column.ts`, threads the `ResolvedColumn` descriptor (not a raw string) into per-engine `searchVector`, and uses `isCacheSafe(resolved, cfg)` for the cache-skip decision so a repointed `embedding` builtin doesn't leak across vector spaces. `cosineReScore` calls `engine.getEmbeddingsByChunkIds(ids, resolved.name)` so rerank uses vectors from the active column, not the hardcoded OpenAI `embedding`, and hydrates each result's raw query↔chunk `cosine` onto `SearchResult` (the calibrated signal evidence and `--explain` consume). `SearchOpts.onVectorPoolMeta` reports bounded candidate incompleteness after up to three pool escalations. SQL limits and offsets are independent of ef_search, filtered short pools need an exhaustion witness, and Postgres alone can use one exact fallback inside the remaining deadline. Hybrid and direct image query paths publish the scoped details and recall-affecting degraded stage; an exhausted genuine small corpus does not emit a false warning. The `query` MCP op accepts `embedding_column` for per-call A/B; `search` (keyword-only) rejects it. Two post-fusion stages + evidence stamp: `applyTitleBoost(results, query, titleBoost, floorThreshold)` multiplies a result's score by the resolved `title_boost` when `isTitlePhraseMatch` fires, stamps `title_match_boost`, inherits the floor-ratio gate so a title match can't shove a much-stronger page below it; `applyAliasHop(engine, results, query, opts)` normalizes the query, calls `engine.resolveAliases`, and on exact normalized-alias match surfaces that page at top-of-organic + epsilon with `alias_hit=true` (skipping `exclude_slugs`). Both post-rerank identity tiers (alias hop, `applyExactLookupTier`) are ORDER-PRESERVING: identity rows move to the front and every other row keeps its input (reranked) order — never a global re-sort by `score`, which is still the fusion score after reranking; `stampEvidence(...)` runs LAST (after the alias hop, before slice) on every path — keyword-only, no-embed, and full hybrid — so MCP callers and `--explain` read the same `evidence` + `create_safety` contract. `title_boost` resolved from the mode bundle and threaded in. `runPostFusionStages` has a 4th stage (`graphSignalsEnabled`, `onGraphMeta`, `onScoreDistribution`). `base_score` stamped at function entry idempotently (captured ONCE before any boost stage mutates `score`). Each post-fusion stage stamps its multiplier: `applyBacklinkBoost`→`backlink_boost`, `applySalienceBoost`→`salience_boost`, `applyRecencyBoost`→`recency_boost`. `applyReranker` (earlier in the pipeline) stamps `reranker_delta` as a rank delta (positive = improved). `applyExactMatchBoost` in `src/core/search/intent-weights.ts` stamps `exact_match_boost` when fired — on an exact slug/title match OR a title / slug tail mentioned inside the query (`isTitleMentionedInQuery`), and `applyAliasMentionBoost` gives the same bounded boost to a present row whose declared alias occurs in the query (one batched `resolveAliases` over 1–5-token query n-grams, fail-open). **Fusion is page-grain:** `rrfFusion`/`rrfFusionWeighted` sum each list's vote per page `(source_id, slug)` (a list counts a page once, at its best rank) and the page's LEAD chunk (largest own vote; ties to the first list, a vector arm) carries the page's summed score while the page's other chunks keep their own votes — giving every chunk the page score let a page's second chunk crowd other pages out of chunk-limited results. Every arm is page-grain with its own representative chunk, so chunk-keyed fusion split a page's cross-arm agreement. **Detail:** only an EXPLICIT `detail: 'low'` hard-filters every arm to compiled truth (with the 2x boost and the zero-result escalation); an auto-detected `low` (entity intent) passes no SQL filter and applies `AUTO_LOW_COMPILED_TRUTH_TILT` (1.2x) via `compiledTruthFusionBoost`. The engine opts rebuild forwards `exclude_slugs`, `exclude_slug_prefixes` and `include_slug_prefixes` to every arm. Under unified multimodal routing the cosine rescore hydrates `embedding_multimodal` (the space the query was embedded in), and `cosineSimilarity` returns 0 for vectors of different lengths. Per-stage attribution powers `gbrain search --explain` — every boost surface carries its own field so `formatResultsExplain` reads them all without coupling to internal stage ordering. with `src/core/search/sql-ranking.ts` + `src/core/operations.ts` + `src/core/types.ts`: agent-warning channel. `SearchResult.content_flag?: {reason, detail}` (optional field in `types.ts`) is stamped post-fusion by `stampContentFlags` (the `stampEvidence` precedent) in `hybridSearch` AND in the keyword-only `search` MCP op so both retrieval paths surface the marker. `get_page` returns a top-level `content_flag` parallel field via `getContentFlag(page.frontmatter)`. `buildVisibilityClause` (sql-ranking.ts) ANDs in `QUARANTINE_FILTER_FRAGMENT` so quarantined pages are excluded from all six search call sites (alongside soft-delete + archived-source filters). Pinned by `test/sql-ranking.test.ts` + `test/e2e/quarantine-search-exclusion.test.ts`. Cross-modal routing at the embed step: `effectiveModality` resolves per-call `opts.crossModal` (literal `'auto'` → undefined) → `suggestions.suggestedModality` → `'text'`. Image route: `embedQueryMultimodal` + `searchVector({embeddingColumn: 'embedding_image'})`, skipping expansion + keyword. `'both'` route: parallel text + image vector searches merged via `rrfFusionWeighted` with `effectiveRrfK(baseRrfK, weight)` from the configured cross-modal weights. Unified routing fires when `search.unified_multimodal` is true — bypasses dual-column branching, runs `embedQueryMultimodal` + `searchVector({embeddingColumn: 'embedding_multimodal'})`, fail-open on zero rows (non-strict falls through to dual-column). LLM modality escalation fires only when no explicit per-call opt is set AND the regex returned `'text'` AND `search.cross_modal.llm_intent` is on AND `isAmbiguousModalityQuery` fires; fail-open on every error. `compiledTruthBoost(result, applyBoost)` is exported for direct predicate tests: a synthetic chunkless title row (`chunk_id === 0` AND blank `chunk_text`) never receives the 2x compiled-truth boost (`test/search/compiled-truth-boost.test.ts`). The reranker pass-through callback is typed with `RerankPassThroughReason` imported from `rerank.ts` — one union, not a re-declaration. RRF inputs are assembled by ONE `composeFusionLists` call (next entry) over role-tagged `vectorArms` built with `pushVectorList` at every assembly site (unified, image-only, text/both, and the `allSettled` salvage path — where the `original` role additionally requires the original's `searchVector` to have succeeded); after `expandFn`, `queries[0]` is re-enforced to be the caller's query and repeats are deduped, so a variant can never take the anchor role. `HybridSearchOpts.onRerankPool` (eval-only, best-effort) fires immediately before `applyAutocut` with the exact pre-autocut `returnPool` — post alias-hop / exact-lookup / adaptive-return, unscored injected rows included, even when autocut is off — plus the deduped pre-rerank order, so an offline autocut replay is byte-faithful. Immediately after `applyReranker` — only when it actually reordered (`reranked !== deduped`) and never for image modality — `pinRelationalRows` (`relational-rerank-pin.ts`) re-pins the relational arm's rows above the reranked text rows bounded by `resolvedMode.relational_rerank_pin`, stamps `relational_pinned`, and emits `HybridSearchMeta.relational_rerank_pin`; `ensureRelationalEvidenceSlot` still runs after autocut (usually a no-op on relational queries now — it remains the page-1 guarantee for pin 0, reranker fail-open, and arm rows dropped before the pin).`embedQueryBounded` preserves its own expired signal's timeout reason whenthe gateway wraps transport cancellation, keeping `embed_timeout` stable@@ -59,10 +59,12 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/query-intent.ts` — Deterministic query classifiers (pure, no LLM): `classifyQuery`/`classifyQueryIntent` (entity/temporal/event/concept/general → auto-selects detail level, salience/recency/modality axes; `concept` fires on definitional-paraphrase OR landscape/quantifier cues with a proper-noun name-guard — capitalized names, quoted phrases, slugs, and sub-3-word queries never trigger — and ranks vector-lean via the RRF-k tilt in `intent-weights.ts`), `isAmbiguousModalityQuery` (LLM-escalation gate), and the concept-shape pair — `looksConceptShaped` (fuzzy-quantifier/landscape cues minus exact-identifier anti-signals, tuned to favor false-negatives; cues owned by other routers like "who are the"/find_experts and bare "anything"/salience are deliberately excluded) + `conceptNudge` (full one-line CLI hint string steering a concept-shaped `search` toward `query`; consumed by `maybePrintConceptNudge` in `src/cli.ts` on BOTH the local-engine and thin-client result paths, stderr-only, `--quiet`-gated). Pinned by `test/query-intent-concept.test.ts` + `test/cli-concept-nudge.test.ts`.-- `src/core/search/read-enrichment.ts` — narrow query helpers shared by PGLite and Postgres. Recursive relational reads authorize seeds, hops and link origins before limits; seed identity constraints remain separate from caller grants. Batched IDs or `(source_id, slug)` pairs authorize backlinks, adjacency, dates, flags, extraction state and take-derived salience. Restricted holders use permitted active takes and zero stored emotional-weight contribution; required expert admission runs after optional enrichment, uses an authorized effective-date map and propagates query failures. Callers omit failed optional signals or apply their existing neutral defaults.+- `src/core/search/read-enrichment.ts` — narrow query helpers shared by PGLite and Postgres. Recursive relational reads authorize seeds, hops and link origins before limits; seed identity constraints remain separate from caller grants. Batched IDs or `(source_id, slug)` pairs authorize backlinks (counted as DISTINCT linking pages: no self-links, no duplicate edges, mentions excluded; a read policy also requires live, authorized contributors), adjacency, dates, flags, extraction state and take-derived salience. Restricted holders use permitted active takes and zero stored emotional-weight contribution; required expert admission runs after optional enrichment, uses an authorized effective-date map and propagates query failures. Callers omit failed optional signals or apply their existing neutral defaults.- `src/core/search/read-policy-sql.ts` — shared internal concrete-page SQL policy (`PageReadScope` in `types.ts`): nonempty federated grants precede scalar source; `excludePrivate` is resolved by `ops/context.ts:readPolicyOpts`, never an MCP override. Optional live-page filtering excludes deleted/quarantined pages and archived sources. Both engines apply policy inside content, version, timeline, graph and identity reads before limits. While page privacy is enforced, history requires both current-page and snapshot visibility. Links/timeline projections independently authorize originating pages.- `src/core/search/relational-rerank-pin.ts` — relational-arm rows bypass reranker DEMOTION (ranker wave, receipt R1 in `scripts/r1-namedthing-rerank-ab.ts`: on NamedThingBench's 39 graph-relationship questions the shipped `balanced` default lost hit@1 21/39 → 3/39 and hit@3 27/39 → 5/39 with the reranker on — 19 and 22 paired losses — because the cross-encoder scores chunk TEXT and an edge-derived answer's text need not mention the query's entity; with the pin at its default 3, measured with `--autocut on`, the shape that shipped before rule R2 turned autocut off, the same paired run shows 0 hit@1 / 0 hit@3 losses, 21/39 and 27/39, and the 11 non-relational core queries show 0 losses — one hard-negative gain, hit@1 10/11 → 11/11). `pinRelationalRows(reranked, relationalList, {max, fusedOrder?, onPin?})` is a pure PERMUTATION of the post-rerank pool: relational rows (page key `(source_id, slug)` in the arm's list; ONE row per page — its first, highest-ranked occurrence) claim `min(fused_rank, reranked_rank)` (fused rank = position among relational rows in `fusedOrder`, the pre-rerank `deduped` pool; arm order for rows absent from it), claims sort ascending with ties resolved to the FUSED order then the reranked position, the first `max` claimants form the top block in that order, every other row follows in reranked order (an unpinned row lands at its reranked position or up to `pinned.length` lower, never higher). Pinned rows are shallow copies stamped `relational_pinned: true`; no row is added or removed (re-injecting rows dropped upstream stays `ensureRelationalEvidenceSlot`'s job). Every no-op path (`max <= 0`, empty pool, empty arm, no relational page in the pool) returns the input array itself. `normalizeRelationalRerankPin` is the ONE range contract for the knob (non-negative integer `<= 10` or a string parsing to one → that integer; the literals `off` / `false` (any case) or boolean `false` → 0; anything else → `undefined` = fall through), shared by `mode.ts:loadOverridesFromConfig` and both per-call seams in `hybrid.ts`; `DEFAULT_RELATIONAL_RERANK_PIN` (3) and `RELATIONAL_RERANK_PIN_MAX` (10) are exported. `RelationalRerankPinDecision` (`{max, relational_in_pool, pinned:[{slug, source_id, from_rank, to_rank, fused_rank}], moved}`) is surfaced as `HybridSearchMeta.relational_rerank_pin` for `--explain`. Wired in `hybridSearch` immediately after `applyReranker` and before the alias hop, gated on the reranker having actually reordered (`reranked !== deduped` — `applyReranker` returns its input on every fail-open / skip / pass-through path, and the fused order already carries the arm) and on non-image modality; autocut's `scoreOf` ignores pinned rows and its preserve predicate keeps them, so text-row autocut is byte-identical to the pre-pin behavior. Known cost: a false-positive arm (relational shape parsed AND a real seed resolved, but wrong/stale edges) now puts up to `max` edge pages at ranks 1..max instead of one at `limit`; mitigations are the arm's `fallback_slugify` confidence gate, the tier-2 resolution-margin TODO, config `search.relational_rerank_pin off`, and per-call `SearchOpts.relationalRerankPin`. Pinned by `test/search/relational-rerank-pin.test.ts` (pure contract + tie policy) and `test/search/relational-rerank-pin-hybrid.serial.test.ts` (hermetic PGLite on the relational corpus through the REAL gateway rerank path behind `__setRerankTransportForTests` with an inverted-relevance stub: pin 0 reproduces the regression, pin 3 restores hit@1/hit@3 on all 8 who-invested questions, non-relational queries and reranker-off runs are byte-identical).-- `src/core/search/rerank.ts` — the call-site abstraction. `applyReranker(query, results, opts)` slots between `dedupResults()` and `enforceTokenBudget()` in `src/core/search/hybrid.ts`. Slices `opts.topNIn` (default 30) by current RRF order, caps each document via `capRerankDoc` (`RERANK_MAX_DOC_CHARS=6000` then a measured-ratio shrink to `RERANK_MAX_DOC_TOKENS=1400` — a 2048-ubatch llama-server minus query/template headroom minus a Qwen-tokenizer margin; every cut through `truncateUtf8` so no lone surrogate reaches the JSON body; docs under 1400 chars skip the tokenizer; applies to hosted providers too, so code/CJK chunks at the chunker ceiling lose part of their tail while prose is untouched), sends to `gateway.rerank()`, reorders by `relevanceScore` desc, appends the un-reranked tail unchanged (recall protection). Fail-open on every `RerankError.reason`: any error logs via `logRerankFailure` and returns the input array unchanged — except the SKIP class `no_key` (`RerankSkipReason`), which returns the input immediately WITHOUT a per-query audit row (the gateway already wrote the one per-process-per-model row) and fires `opts.onSkip(reason)`; `hybrid.ts` passes an `onSkip` that stamps `{stage: 'reranker_skipped', reason}` into `HybridSearchMeta.degraded` (closed vocabulary in `types.ts`), which `--explain` renders as `degraded: reranker_skipped (no_key)` via `formatDegradedSummary` — the only place a silently skipped reranker is visible from the CLI. `types.ts` classifies the stage as ranking-only: `RANKING_ONLY_DEGRADED_STAGES` (= `{reranker_skipped}`) + `affectsRecall(entry)` — consumers that ask "was recall impaired?" filter through it (the CLI `No results.` line in `cli.ts:describeEmptyRetrieval` and the MCP empty-result block in `dispatch.ts:buildEmptyRetrievalBlock` keep saying "clean miss"; the degraded cache-TTL rule below uses the same predicate), while consumers that report what did not run (`--explain`, telemetry, eval rows) keep it; pinned by `test/degraded-stages-recall.test.ts`. `hybridSearchCached` excludes `reranker_skipped` from the short degraded-TTL rule (it is a config state, not a transient limp: a keyless balanced brain keeps the full `cache.ttl_seconds`, and the stored meta still carries the stamp). Stamps `rerank_score` onto reordered items so downstream telemetry sees the new ordering signal. `topNOut: null` is the explicit "don't truncate" signal — semantically distinct from `undefined` ("fall through to mode bundle"). Test seam: `opts.rerankerFn` stubs `gateway.rerank` without the network. Document cap pinned by `test/rerank-doc-cap.test.ts`.+- `src/core/search/rerank.ts` — the call-site abstraction. `applyReranker(query, results, opts)` slots between `dedupResults()` and `enforceTokenBudget()` in `src/core/search/hybrid.ts`. Slices `opts.topNIn` (default 30) by current RRF order, caps each document via `capRerankDoc` (`RERANK_MAX_DOC_CHARS=6000` then a measured-ratio shrink to `RERANK_MAX_DOC_TOKENS=1400` — a 2048-ubatch llama-server minus query/template headroom minus a Qwen-tokenizer margin; every cut through `truncateUtf8` so no lone surrogate reaches the JSON body; docs under 1400 chars skip the tokenizer; applies to hosted providers too, so code/CJK chunks at the chunker ceiling lose part of their tail while prose is untouched), sends to `gateway.rerank()`, reorders by `relevanceScore` desc, appends the un-reranked tail unchanged (recall protection). Fail-open on every `RerankError.reason`: any error logs via `logRerankFailure` and returns the input array unchanged — except the SKIP class `no_key` (`RerankSkipReason`), which returns the input immediately WITHOUT a per-query audit row (the gateway already wrote the one per-process-per-model row) and fires `opts.onSkip(reason)`; every OTHER thrown failure (HTTP error, network, timeout, budget) is audited and fires `opts.onFailure(reason)` with `RerankFailedReason` `timeout | budget | provider_error`, which `hybrid.ts` stamps as `{stage: 'rerank_failed', reason}` (recall-affecting, like `rerank_passthrough`; the LongMemEval reranker gate and the R1 script count it as un-reranked); `hybrid.ts` passes an `onSkip` that stamps `{stage: 'reranker_skipped', reason}` into `HybridSearchMeta.degraded` (closed vocabulary in `types.ts`), which `--explain` renders as `degraded: reranker_skipped (no_key)` via `formatDegradedSummary` — the only place a silently skipped reranker is visible from the CLI. `types.ts` classifies the stage as ranking-only: `RANKING_ONLY_DEGRADED_STAGES` (= `{reranker_skipped}`) + `affectsRecall(entry)` — consumers that ask "was recall impaired?" filter through it (the CLI `No results.` line in `cli.ts:describeEmptyRetrieval` and the MCP empty-result block in `dispatch.ts:buildEmptyRetrievalBlock` keep saying "clean miss"; the degraded cache-TTL rule below uses the same predicate), while consumers that report what did not run (`--explain`, telemetry, eval rows) keep it; pinned by `test/degraded-stages-recall.test.ts`. `hybridSearchCached` excludes `reranker_skipped` from the short degraded-TTL rule (it is a config state, not a transient limp: a keyless balanced brain keeps the full `cache.ttl_seconds`, and the stored meta still carries the stamp). Stamps `rerank_score` onto reordered items so downstream telemetry sees the new ordering signal. `topNOut: null` is the explicit "don't truncate" signal — semantically distinct from `undefined` ("fall through to mode bundle"). Test seam: `opts.rerankerFn` stubs `gateway.rerank` without the network. Document cap pinned by `test/rerank-doc-cap.test.ts`.++- `src/core/search/rrf-page-fusion.ts` — `accumulateRrf(lists)`, the one accumulation step behind `rrfFusion` / `rrfFusionWeighted` in `hybrid.ts`. Votes are keyed on the PAGE `(source_id, slug)`: each list adds `weight / (k + rank)` to a page once, at its best rank, chunks stay distinct rows keyed `(source_id, slug, chunk_id)` with their own vote (`own`) and an OR-propagated `keyword_hit`, and each page's lead chunk (largest `own`, first-seen on ties — a vector arm in `composeFusionLists` order) scores the page's summed vote while its other chunks score their own vote. Pure. Pinned by `test/search/rrf-page-grain.test.ts`.diff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.mdindex 41ab679235..d284a624e8 100644--- a/docs/architecture/key-files/core-search-2.md+++ b/docs/architecture/key-files/core-search-2.md@@ -13,7 +13,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/sql-ranking.ts` — Pure SQL string builders. `buildSourceFactorCase(slugColumn, boostMap, detail)` emits a CASE with longest-prefix-match wins (returns literal `'1.0'` when `detail === 'high'` for temporal-bypass parity with COMPILED_TRUTH_BOOST). `buildHardExcludeClause(slugColumn, prefixes)` emits `NOT (col LIKE 'p1%' OR col LIKE 'p2%')` — OR-chain wrapped in NOT, NOT `NOT LIKE ALL/ANY` (those quantifiers don't express set-exclusion). LIKE meta-character escape covers all three of `%`, `_`, AND `\` (backslash is Postgres LIKE's default escape char). Single-quote doubling on SQL string literals so injection-style inputs are inert text. `buildBestPerPagePoolCte(...)` is the shared per-page max-pool CTE both engines' `searchVector` inject — instead of returning the single best chunk per page from an inner `ORDER BY embedding <=> vec LIMIT N` (which lets a page lose to a neighbor on ONE weak chunk while its strong chunk sits just below the inner cut), the CTE pools the BEST chunk score per `(source_id, slug)` composite key so a page surfaces on its strongest evidence; composite key (not bare slug) keeps multi-source brains correct; single source of truth so the two engines can't drift.-- `src/core/search/title-match.ts` — pure, zero-I/O title-phrase matcher shared by the production title boost AND NamedThingBench (no drift). `isTitlePhraseMatch(query, title)` returns true when the normalized query is a contiguous token run inside the title with `>= MIN_CONTENT_TOKENS=2` non-stopword tokens, OR an exact full-title match (covers deliberate 1-word chosen names like "Helios"). Token-boundary matching (never raw substring, so "art" doesn't match "Bartholomew"); small conservative English stopword set excluded from the content-token floor (guards against promoting generic pages on stopword-y queries); NFKC normalize so CJK / width variants converge. Exports `tokenizeTitle` + `__test__` internals.+- `src/core/search/title-match.ts` — pure, zero-I/O title-phrase matcher shared by the production title boost AND NamedThingBench (no drift). `isTitlePhraseMatch(query, title)` returns true when the normalized query is a contiguous token run inside the title with `>= MIN_CONTENT_TOKENS=2` non-stopword tokens, OR an exact full-title match (covers deliberate 1-word chosen names like "Helios"). Token-boundary matching (never raw substring, so "art" doesn't match "Bartholomew"); small conservative English stopword set excluded from the content-token floor (guards against promoting generic pages on stopword-y queries); NFKC normalize so CJK / width variants converge. `isTitleMentionedInQuery(query, title)` is the reverse direction the intent exact-match boost uses: the title appears as a contiguous token run INSIDE the query ("who is Alice Example" → "Alice Example"), guarded to titles with ≥2 content tokens or one content token of ≥4 characters. Exports `tokenizeTitle` + `__test__` internals.- `src/core/search/tune-recommendations.ts` — tuning recommendations never propose enabling or tuning unavailable semantic result caching. Mode-reduction suggestions describe payload size, not expansion savings: shipped commands pin expansion independently of the bundle.diff --git a/docs/architecture/key-files/core-utilities-1.md b/docs/architecture/key-files/core-utilities-1.mdindex 2302a149b6..78803135ea 100644--- a/docs/architecture/key-files/core-utilities-1.md+++ b/docs/architecture/key-files/core-utilities-1.md@@ -51,7 +51,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/operations-descriptions.ts` — Constants module for tool descriptions. Pinned via `test/operations-descriptions.test.ts`. Houses `GET_RECENT_SALIENCE_DESCRIPTION`, `FIND_ANOMALIES_DESCRIPTION`, `GET_RECENT_TRANSCRIPTS_DESCRIPTION` plus `LIST_PAGES_DESCRIPTION`, `QUERY_DESCRIPTION`, `SEARCH_DESCRIPTION`. Stable surface for the Tier-2 LLM routing eval — keeping them here keeps the test from binding to whatever is in `operations.ts` at test-run time.-- `src/core/operations.ts` — Contract-first operation contract, served through a ~300-line assembly façade: the op definitions live in the domain modules under `src/core/ops/` (next entry) and are spread into the single exported `operations` array here; the shared contract types (`src/core/ops/contract.ts`) and the security/scope layer (`src/core/ops/context.ts`) are re-exported through this file, so every import path below resolves through the façade unchanged. The rest of this entry describes the surface as consumers see it. Fresh same-source graph mutations (`add_link`, `add_timeline_entry`) preflight each endpoint against the scalar write source via `requireWritablePage` (`ops/context.ts`); `add_timeline_entry` resolves an authorized stored request before that fresh-write preflight so exact replay retains its outcome after page purge or recreation: a page readable only from another granted source returns endpoint-specific `permission_denied` naming the boundary, pages outside the caller's `get_page` visibility scope stay `page_not_found` (a soft-deleted foreign page is indistinguishable from absence), and a mutation-time engine miss — the typed `PageMissingError` from `src/core/engine-errors.ts`, thrown by both engines' single-statement endpoint resolution — is reclassified into the same envelope by `instanceof`, never message matching. Exports upload validators `validateUploadPath`, `validatePageSlug`, `validateFilename`, plus `matchesSlugAllowList(slug, prefixes)` (glob matcher: `<prefix>/*` matches recursive children; bare `<prefix>` matches exact only). `OperationContext.remote` is a REQUIRED field flagging untrusted callers; `OperationContext.allowedSlugPrefixes` is the trusted-workspace allow-list set by the dream cycle; `OperationContext.auth?: AuthInfo` is threaded through HTTP dispatch for scope enforcement in `serve-http.ts` before the op runs. OAuth `whoami` exposes the authenticated `AuthInfo.sourceId` and `AuthInfo.allowedSources` grants as `source_id` and `federated_read`; absent grants serialize fail-closed as `null` and `[]`, while local, legacy, and stdio response shapes stay unchanged. `enforceSubagentSlugFence(ctx, slug, opName)` is the shared fail-closed subagent write fence: when `viaSubagent` and `allowedSlugPrefixes` is set, the slug must match the allow-list; else the legacy `wiki/agents/<id>/...` namespace check applies. Both `put_page` and `add_timeline_entry` (subagent-allowlisted) route through it. Auto-link/timeline hooks are skipped for remote-owned subagents even with explicit prefixes; only local subagents qualify as trusted workspaces. `enforceClientSlugFence(ctx, slug, opName)` is the OAuth-client write fence: when `ctx.auth.boundSlugPrefixes` is present (threaded from `oauth_clients.bound_slug_prefixes` at token-verification time), every direct slug-mutating write op — `put_page`, `delete_page`, `restore_page`, `add_tag`, `remove_tag`, `add_link`/`remove_link` (`from` endpoint only; linking TO a readable page is a reference), `add_timeline_entry`, `revert_version`, `put_raw_data` — rejects out-of-prefix slugs with `permission_denied`, BEFORE each op's dry-run short-circuit. Direct writes use the shared boundary-aware prefix rules; empty-array binding is deny-all (fail-closed); no auth / no binding = no fence. The match rule itself lives in the exported `slugUnderBoundPrefixes(prefixes, slug)` so non-op write surfaces reuse it verbatim. It is BOUNDARY-AWARE (a prefix matches whole segments, so `emp-alice` does not admit `emp-alice-2/…`), lowercases both sides (stored slugs are lowercased by `validateSlug`, so comparing the caller's raw string would let a mixed-case slug commit and only then trip the resolved-slug re-check), accepts BOTH the trailing-slash and the `<prefix>/*` glob spelling via `normalizeSlugPrefix` (direct and delegated fences share normalization while storing independently reviewed spans), and ignores empty-string prefixes. `assertValidSlugPrefixes` (`oauth-provider.ts`) rejects empty, whitespace-bearing, non-lowercase, and boundary-less entries at registration and rescope. `submit_agent` validates tools and namespaces against the independently stored `bound_tools`, `delegated_slug_prefixes`, and `delegated_namespace` grants. It normalizes accepted prefixes for `matchesSlugAllowList` and rejects explicit empty remote tool or prefix overrides. Workers interpret explicit empty tool lists as no tools, with defaults reserved for absent trusted-local bindings. `put_page` deduplication may resolve another slug by content hash or `frontmatter.id`, but returns an authorized read-only `duplicate` outcome. The original target's revision never authorizes publication to that other page. Preparation and guarded validation recheck the duplicate's current authority, readability, concrete page identity and revision; neither its canonical fields nor its file are written. OAuth and delegated subagent fences still apply, and denials do not name an inaccessible duplicate. Pinned by `test/put-page-dedup-fence.test.ts`. `CLIENT_FENCED_WRITE_OPS` + `enforceBoundClientOpAllowList(auth, op)` are the fail-closed companion, applied once in `src/mcp/dispatch.ts` (the choke point both MCP transports share): a slug-bound client calling ANY `write`/`admin` op not on the allow-list gets `permission_denied`. This covers the ops that write by a key other than a slug and therefore cannot be fenced — `extract_entities`/`extract_facts` (mutate `people/*`, `companies/*`), `forget_fact` (numeric fact id, crosses sources), `ontology_propose` — and makes a write op added later denied-by-default instead of silently unfenced. `think` is on the allow-list because remote callers cannot persist from it. Pinned by `test/client-slug-fence.test.ts` and over-the-wire by `test/e2e/qm-provisioning.test.ts`. Every `Operation` carries `scope?: 'read' | 'write' | 'admin'` + `localOnly?: boolean`; `think` is read-scoped for OAuth/MCP because remote callers have `save`/`take` forced off before persistence, while local CLI can still persist via `remote:false`; `sync_brain`, `file_upload`, `file_list`, `file_url` are `admin + localOnly` (rejected over HTTP). Four trust-boundary call sites (`put_page` allowlist, file_upload trust-narrowing, submit_job protected-name guard, auto-link skip) use FAIL-CLOSED semantics: `ctx.remote === false` for trusted-only sites, `ctx.remote !== false` for "untrust unless explicit-false" — anything not strictly `false` is treated as remote (so a read+write OAuth token over HTTP MCP cannot submit `shell` jobs). `sourceScopeOpts(ctx)` encodes the source-scoped read precedence ladder — federated array (`ctx.auth.allowedSources`) wins over scalar (`ctx.sourceId`/`ctx.auth.sourceId`) over nothing; every read-side op handler routes through it so a source-bound OAuth client can't see neighboring sources via `search`/`query`/`list_pages`/`get_page`/`find_experts`/query's image path, plus the by-slug reads `get_tags`/`get_links`/`get_backlinks`/`get_timeline`/`get_chunks` (chunks follow the same ladder as `get_page`, so a federated grant that can open a page can read its chunks — and the chunk payload never carries embedding vectors) (and `get_page`'s tag fetch, which resolves against the concrete page's own `source_id`). `assertExplicitSourceLive(ctx, sourceIdParam)` is the async companion for the ops that accept a per-call `source_id` (`get_page`, `list_pages`, `search`, `query`): called right after `federatedSearchScope` (so the grant check has already run and it can only name a granted source), an explicit id with no live unarchived `sources` row throws `unknown_source` instead of silently scoping the read to an empty source — the CLI's `--source` existence rule applied to the op path; `__all__` and an omitted param skip it. `linkReadScopeOpts(ctx)` is the link-read sibling for `get_links`/`get_backlinks`: a link row references three pages (from/to/origin), and the engine's federated (`sourceIds[]`) branch scopes ALL THREE while its scalar (`sourceId`) branch scopes only the near endpoint (by design — trusted internal callers like `reconcileLinks` and back-link validators call the engine with a scalar scope and need the cross-source view). For an UNTRUSTED remote caller (`ctx.remote !== false`) carrying only a scalar scope it promotes that scope to a single-element `sourceIds:[id]`, routing them through the all-endpoint branch so a far/origin slug from outside the grant isn't disclosed; a federated array passes through unchanged and trusted local CLI (`ctx.remote === false`) keeps the scalar cross-source view. `thinkSourceScopeOpts(ctx)` maps the same precedence ladder onto `runThink`'s public options (`allowedSources`/`sourceId`) so the `think` op's gather and trajectory stages inherit the caller's source grant. `put_page` submits through `submitPageMutation` to the durable journal. Existing-page replacements require `expected_revision` or explicit `force`; omission is create-only. The designated owner publishes under native root and database guards, with recoverable file replacement and a terminal receipt committed with canonical state. Accepted contention returns `write_pending` after the synchronous wait; admission failure does not fabricate a queued receipt. Git and embeddings report separate effect outcomes. Trusted-local `delete_page` with `purge: true` uses the same journal, revision and recovery protocol: artifact-removal failure preserves the prior row, and exact replay retains the original terminal outcome after deletion. Link provenance surface: `add_link` (`gbrain link`/`link-add`) + `remove_link` (`gbrain unlink`/`link-rm`) expose `link_source`/`link_type`; `add_link` rejects the reconciliation-managed built-ins via `MANAGED_LINK_SOURCES` (`markdown`/`frontmatter`/`mentions`/`wikilink-resolved`) and defaults omitted provenance to `'manual'` (the engine's own default stays `'markdown'` for internal callers); `list_link_sources` (`gbrain link-sources`, read) lists provenances via `sourceScopeOpts`. CLI aliases register through `cliHints.aliases` (collision-guarded in `src/cli.ts`).+- `src/core/operations.ts` — Contract-first operation contract, served through a ~300-line assembly façade: the op definitions live in the domain modules under `src/core/ops/` (next entry) and are spread into the single exported `operations` array here; the shared contract types (`src/core/ops/contract.ts`) and the security/scope layer (`src/core/ops/context.ts`) are re-exported through this file, so every import path below resolves through the façade unchanged. The rest of this entry describes the surface as consumers see it. Fresh same-source graph mutations (`add_link`, `add_timeline_entry`) preflight each endpoint against the scalar write source via `requireWritablePage` (`ops/context.ts`); `add_timeline_entry` resolves an authorized stored request before that fresh-write preflight so exact replay retains its outcome after page purge or recreation: a page readable only from another granted source returns endpoint-specific `permission_denied` naming the boundary, pages outside the caller's `get_page` visibility scope stay `page_not_found` (a soft-deleted foreign page is indistinguishable from absence), and a mutation-time engine miss — the typed `PageMissingError` from `src/core/engine-errors.ts`, thrown by both engines' single-statement endpoint resolution — is reclassified into the same envelope by `instanceof`, never message matching. Exports upload validators `validateUploadPath`, `validatePageSlug`, `validateFilename`, plus `matchesSlugAllowList(slug, prefixes)` (glob matcher: `<prefix>/*` matches recursive children; bare `<prefix>` matches exact only). `OperationContext.remote` is a REQUIRED field flagging untrusted callers; `OperationContext.allowedSlugPrefixes` is the trusted-workspace allow-list set by the dream cycle; `OperationContext.auth?: AuthInfo` is threaded through HTTP dispatch for scope enforcement in `serve-http.ts` before the op runs. OAuth `whoami` exposes the authenticated `AuthInfo.sourceId` and `AuthInfo.allowedSources` grants as `source_id` and `federated_read`; absent grants serialize fail-closed as `null` and `[]`, while local, legacy, and stdio response shapes stay unchanged. `enforceSubagentSlugFence(ctx, slug, opName)` is the shared fail-closed subagent write fence: when `viaSubagent` and `allowedSlugPrefixes` is set, the slug must match the allow-list; else the legacy `wiki/agents/<id>/...` namespace check applies. Both `put_page` and `add_timeline_entry` (subagent-allowlisted) route through it. Auto-link/timeline hooks are skipped for remote-owned subagents even with explicit prefixes; only local subagents qualify as trusted workspaces. `enforceClientSlugFence(ctx, slug, opName)` is the OAuth-client write fence: when `ctx.auth.boundSlugPrefixes` is present (threaded from `oauth_clients.bound_slug_prefixes` at token-verification time), every direct slug-mutating write op — `put_page`, `delete_page`, `restore_page`, `add_tag`, `remove_tag`, `add_link`/`remove_link` (`from` endpoint only; linking TO a readable page is a reference), `add_timeline_entry`, `revert_version`, `put_raw_data` — rejects out-of-prefix slugs with `permission_denied`, BEFORE each op's dry-run short-circuit. Direct writes use the shared boundary-aware prefix rules; empty-array binding is deny-all (fail-closed); no auth / no binding = no fence. The match rule itself lives in the exported `slugUnderBoundPrefixes(prefixes, slug)` so non-op write surfaces reuse it verbatim. It is BOUNDARY-AWARE (a prefix matches whole segments, so `emp-alice` does not admit `emp-alice-2/…`), lowercases both sides (stored slugs are lowercased by `validateSlug`, so comparing the caller's raw string would let a mixed-case slug commit and only then trip the resolved-slug re-check), accepts BOTH the trailing-slash and the `<prefix>/*` glob spelling via `normalizeSlugPrefix` (direct and delegated fences share normalization while storing independently reviewed spans), and ignores empty-string prefixes. `assertValidSlugPrefixes` (`oauth-provider.ts`) rejects empty, whitespace-bearing, non-lowercase, and boundary-less entries at registration and rescope. `submit_agent` validates tools and namespaces against the independently stored `bound_tools`, `delegated_slug_prefixes`, and `delegated_namespace` grants. It normalizes accepted prefixes for `matchesSlugAllowList` and rejects explicit empty remote tool or prefix overrides. Workers interpret explicit empty tool lists as no tools, with defaults reserved for absent trusted-local bindings. `put_page` deduplication may resolve another slug by content hash or `frontmatter.id`, but returns an authorized read-only `duplicate` outcome. The original target's revision never authorizes publication to that other page. Preparation and guarded validation recheck the duplicate's current authority, readability, concrete page identity and revision; neither its canonical fields nor its file are written. OAuth and delegated subagent fences still apply, and denials do not name an inaccessible duplicate. Pinned by `test/put-page-dedup-fence.test.ts`. `CLIENT_FENCED_WRITE_OPS` + `enforceBoundClientOpAllowList(auth, op)` are the fail-closed companion, applied once in `src/mcp/dispatch.ts` (the choke point both MCP transports share): a slug-bound client calling ANY `write`/`admin` op not on the allow-list gets `permission_denied`. This covers the ops that write by a key other than a slug and therefore cannot be fenced — `extract_entities`/`extract_facts` (mutate `people/*`, `companies/*`), `forget_fact` (numeric fact id, crosses sources), `ontology_propose` — and makes a write op added later denied-by-default instead of silently unfenced. `think` is on the allow-list because remote callers cannot persist from it. Pinned by `test/client-slug-fence.test.ts` and over-the-wire by `test/e2e/qm-provisioning.test.ts`. Every `Operation` carries `scope?: 'read' | 'write' | 'admin'` + `localOnly?: boolean`; `think` is read-scoped for OAuth/MCP because remote callers have `save`/`take` forced off before persistence, while local CLI can still persist via `remote:false`; `sync_brain`, `file_upload`, `file_list`, `file_url` are `admin + localOnly` (rejected over HTTP). Four trust-boundary call sites (`put_page` allowlist, file_upload trust-narrowing, submit_job protected-name guard, auto-link skip) use FAIL-CLOSED semantics: `ctx.remote === false` for trusted-only sites, `ctx.remote !== false` for "untrust unless explicit-false" — anything not strictly `false` is treated as remote (so a read+write OAuth token over HTTP MCP cannot submit `shell` jobs). `sourceScopeOpts(ctx)` encodes the source-scoped read precedence ladder — federated array (`ctx.auth.allowedSources`) wins over scalar (`ctx.sourceId`/`ctx.auth.sourceId`) over nothing; every read-side op handler routes through it so a source-bound OAuth client can't see neighboring sources via `search`/`query`/`list_pages`/`get_page`/`find_experts`/query's image path, plus the by-slug reads `get_tags`/`get_links`/`get_backlinks`/`get_timeline`/`get_chunks` (chunks follow the same ladder as `get_page`, so a federated grant that can open a page can read its chunks — and the chunk payload never carries embedding vectors) (and `get_page`'s tag fetch, which resolves against the concrete page's own `source_id`). `get_tags` resolves `readPolicyOpts`, so an untrusted caller gets no tags for a `visibility: private` page (unless the operator's private-pages opt-out is on) or a soft-deleted page. `assertExplicitSourceLive(ctx, sourceIdParam)` is the async companion for the ops that accept a per-call `source_id` (`get_page`, `list_pages`, `search`, `query`): called right after `federatedSearchScope` (so the grant check has already run and it can only name a granted source), an explicit id with no live unarchived `sources` row throws `unknown_source` instead of silently scoping the read to an empty source — the CLI's `--source` existence rule applied to the op path; `__all__` and an omitted param skip it. `linkReadScopeOpts(ctx)` is the link-read sibling for `get_links`/`get_backlinks`: a link row references three pages (from/to/origin), and the engine's federated (`sourceIds[]`) branch scopes ALL THREE while its scalar (`sourceId`) branch scopes only the near endpoint (by design — trusted internal callers like `reconcileLinks` and back-link validators call the engine with a scalar scope and need the cross-source view). For an UNTRUSTED remote caller (`ctx.remote !== false`) carrying only a scalar scope it promotes that scope to a single-element `sourceIds:[id]`, routing them through the all-endpoint branch so a far/origin slug from outside the grant isn't disclosed; a federated array passes through unchanged and trusted local CLI (`ctx.remote === false`) keeps the scalar cross-source view. `thinkSourceScopeOpts(ctx)` maps the same precedence ladder onto `runThink`'s public options (`allowedSources`/`sourceId`) so the `think` op's gather and trajectory stages inherit the caller's source grant. `put_page` submits through `submitPageMutation` to the durable journal. Existing-page replacements require `expected_revision` or explicit `force`; omission is create-only. The designated owner publishes under native root and database guards, with recoverable file replacement and a terminal receipt committed with canonical state. Accepted contention returns `write_pending` after the synchronous wait; admission failure does not fabricate a queued receipt. Git and embeddings report separate effect outcomes. Trusted-local `delete_page` with `purge: true` uses the same journal, revision and recovery protocol: artifact-removal failure preserves the prior row, and exact replay retains the original terminal outcome after deletion. Link provenance surface: `add_link` (`gbrain link`/`link-add`) + `remove_link` (`gbrain unlink`/`link-rm`) expose `link_source`/`link_type`; `add_link` rejects the reconciliation-managed built-ins via `MANAGED_LINK_SOURCES` (`markdown`/`frontmatter`/`mentions`/`wikilink-resolved`) and defaults omitted provenance to `'manual'` (the engine's own default stays `'markdown'` for internal callers); `list_link_sources` (`gbrain link-sources`, read) lists provenances via `sourceScopeOpts`. CLI aliases register through `cliHints.aliases` (collision-guarded in `src/cli.ts`).- `src/core/pg-access-classify.ts` — Postgres ACCESS-error classifier, the reason/remediation layer of the db-availability loop (detect → `GBRAIN_DB_ACCESS` marker → skills/db-repair → `gbrain db-repair`). Two entry points, one diagnosis type: `classifyPgAccessError(err, ctx?)` for thrown errors (data-driven ordered `REASON_ROWS` table, first match wins — specific rows before general ones) and `diagnoseDbConfig(ctx)` for errorless config-plane reasons (`no_url`, `env_shadowed` — there is no error object at connectEngine's no-config exit or under an env shadow; never fake one). The `PgAccessReason` union (16 reasons) is APPEND-ONLY — a compatibility surface once the bundled skills are in the wild, like progress phase names; consumers switch exhaustively with a `never` sentinel. Invariants: `message`/`remediation` are ALWAYS pre-redacted (safe for transcripts/receipts/issues); every `fix` descriptor is hardcoded or derived from the CURRENT config URL (`deriveSessionPoolerUrl`/`deriveDirectUrl`), never from anything parsed out of error text, and `run_command` argv[0] is always `gbrain`; **remediation copy has exactly ONE home: this module** — db-repair, doctor, and MCP dispatch all render `diagnosis.remediation`, skills reference the command and never duplicate recipe text. TWO-AXIS design note (mirrored in `retry-matcher.ts`'s header — do not "fix" one side to match the other): retry-matcher answers "should I retry?" and deliberately treats `password authentication failed` as retryable (auth race during DNS failover); this module answers "what went wrong?" and reports the same error `auth_failed` + `transient: false` — both correct on their own axis; unknown reasons defer `transient` to `isRetryableConnError`. Also exports `DB_ACCESS_MARKER_PREFIX`/`formatDbAccessMarker` (the single source of the marker literal that skills/db-repair pins in both `description:` and `triggers:`; the action a reader takes is ALWAYS the hardcoded `gbrain db-repair`, never a command parsed from the marker), `isDbAccessFailure` (the ACCESS-class subset fail-open recall arms use to tell "one arm degraded" from "the DB is down"), and Supabase enrichment `{pooler, projectRef, pausedSuspect}` (paused projects aren't a distinct wire error — modeled as a suspicion flag on dns/timeout/tenant reasons). Pinned by `test/pg-access-classify.test.ts`.diff --git a/docs/architecture/key-files/evaluation.md b/docs/architecture/key-files/evaluation.mdindex 68ae47f286..3940c5ca8e 100644--- a/docs/architecture/key-files/evaluation.md+++ b/docs/architecture/key-files/evaluation.md@@ -35,13 +35,13 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/eval/longmemeval/judge.ts` + `judge-lane.ts` + `qa-accuracy.ts` — the LongMemEval LLM-as-judge lane behind `gbrain eval longmemeval --judge`. **judge.ts** is a faithful port of the official `evaluate_qa.py::get_anscheck_prompt`: the per-type instruction (standard for `single-session-user` / `single-session-assistant` / `multi-session`; temporal-reasoning adds the off-by-one-days clause; knowledge-update; the single-session-preference rubric) and the abstention instruction for `_abs` ids (the id suffix beats the type; an unknown type falls back to standard), ONE user message per question, `DEFAULT_JUDGE_MODEL` `openai:gpt-4o`, `JUDGE_TEMPERATURE` 0, `JUDGE_MAX_TOKENS` 16 (the OpenAI API's minimum; the official 10 is rejected, and a one-token yes/no verdict is unaffected), and the official verdict rule (`parseJudgeVerdict`: `'yes'` substring of the lowercased completion). Disclosed deviations, carried verbatim in `JUDGE_METHODOLOGY_NOTE` on every summary: (1) the question / reference / response sit inside `<judge_input>` data-boundary framing under `JUDGE_DATA_BOUNDARY_INSTRUCTION` (#4338) — `escapeJudgeData` neutralises tag closures inside the data and the response text is otherwise unaltered, so the judge grades what the reader actually said; (2) the `judge_error` class — `classifyJudgeResponse` returns null for a completion that is neither a yes nor a standalone no (`malformed`, re-judged) instead of a silent `no`; (3) abstention detected by the `_abs` suffix; (4) the unknown-type fallback. `JUDGE_PROMPT_VERSION` bumps whenever any instruction text, framing or field label changes. `judgeConfigHash` = sha256 over the stable JSON of `{judge_model, prompt_version, max_tokens, temperature, reader_model, reader_prompt_sha, context: {k, max_tokens}}`. `judgeRow` judges one row from its stored hypothesis: budget-skips on the PROJECTED cost (`estimateJudgeCallUsd`) BEFORE spending, records actual cost after, never throws on a transport failure, and `stripJudgeFields` removes every prior `judge_*` key first so a re-judge leaves no stale field. **judge-lane.ts** is the harness-side orchestration, pure except `runJudgeBackfill` (whose only effects are the injected client and in-place row updates; no engine, no file I/O): `parseMaxUsd` (`N`, or `off` / `none` / `unlimited` → no cap), `makeJudgeConfigHasher` (per-row hasher — a prior row's recorded reader pins win over this run's; k is the run's `--top-k`, already gated by `retrieval_config_hash`), `hasJudgeAttempt` / `hasSettledVerdict`, `selectBackfillRows` (candidates = rows with a hypothesis and no settled verdict; counts `settled`, `mismatched` + the foreign hashes, `retrievalOnly`, `missingFromDataset`), `judgePreflight` (availability → pricing → estimate → cap: exit 1 no provider, exit 2 unpriced-with-budget or over-cap without `--yes`) and `runJudgeBackfill` (`runWithLimit` at `--judge-concurrency`; the dataset's answer is the reference, the row's own `answer` the fallback). **qa-accuracy.ts** builds the `qa_accuracy` block from ALL rows (pure; last row per `question_id` wins): `accuracy_headline` (alias `accuracy`) = correct / `total_questions` over EVERY question including `_abs` — a `judge_error`, a budget-skipped row, a reader-error row and a never-judged row all score INCORRECT, so it is never more lenient than the official scorer; `accuracy_excluding_errors` = correct / judged (secondary); `accuracy_470` = the headline rule over the non-`_abs` questions (the retrieval-metric denominator); `by_type` and an `abstention` sub-block; `judge_error_classes`; `ci95_bootstrap` (percentile bootstrap over the headline 0/1 vector, `label: 'question-sampling only'`); `complete` (no error, no skip, no unjudged row — the publishability bit the run-end gate reads); `mixed_judge_config`; `est_cost_usd`, `actual_cost_usd` (summed over the rows' own `judge_cost_usd` across resumes), `run_cost_usd` (this run's ledger); `methodology_note`. Pinned by `test/longmemeval-judge.test.ts` and `test/eval-longmemeval-judge.slow.test.ts`.-- `src/eval/longmemeval/metrics.ts` — LongMemEval strict-recall metrics: the raw-id join, `recall_all@k` / `recall_any@k`, per-type buckets, the schema-v2 `by_type_summary`, and the per-question row assembler. PURE: no engine, no I/O, no LLM, so the harness and the tests score the same bytes. The join is on RAW session ids: `haystackToPages` lowercases and hyphenates ids to build slugs, so a slug tail compared against `answer_session_ids` never matches on the public `_s` split; `buildSlugToRawMap` inverts the slug construction per question, `distinctRetrievedSessions` joins through it, `detectSlugCollisions` / `collisionsTouchingGold` name the ambiguous slugs (a gold-touching collision makes the harness emit an error row), `goldMissingFromHaystack` counts dataset defects, and `normalizeSessionId` exists only for slug construction — never for the gold compare. k semantics: `recall_*@k` is scored over the DISTINCT sessions among the top-k CHUNK rows returned at `limit: k` (the caller slices first; `scoreRecall` treats k as a guard); empty gold scores both hits false, not vacuously true, and such rows stay out of the denominator. `addRowToBucket` folds a v2 row into `total`/`all_hit`/`any_hit`; a row carrying only the deprecated any-only `recall_hit` counts toward `total` + `any_hit` and bumps `legacy_rows` (its `all_rate` is therefore a lower bound); `buildByTypeSummaryV2` emits sorted type keys, `null` rates on empty buckets, `mean_distinct_sessions`, and the caller's `run_config`. `buildRow` assembles the JSONL row — scored fields over `results.slice(0, k)`, `retrieved[]` + `retrieved_session_ids` over EVERY returned row so replay can re-score at any smaller k — and harness passthrough `extra` keys never override the scored fields. Pinned by `test/longmemeval-metrics.test.ts`.+- `src/eval/longmemeval/metrics.ts` — LongMemEval strict-recall metrics: the raw-id join, `recall_all@k` / `recall_any@k`, per-type buckets, the schema-v2 `by_type_summary`, and the per-question row assembler. PURE: no engine, no I/O, no LLM, so the harness and the tests score the same bytes. The join is on RAW session ids: `haystackToPages` imports every session under an OPAQUE per-question id (`sessionSlug` → `chat/s-` + first 10 hex of sha256(`question_id:normalized session id`), the same id in frontmatter and in the reader's `<chat_session id>`), because every public gold id starts with `answer_` and no distractor does — a raw id in a slug, title, chunk or reader prompt is a gold label (pinned by `test/longmemeval-gold-leak.slow.test.ts`); `buildSlugToRawMap` is the private per-question inverse used only for scoring, `distinctRetrievedSessions` joins through it, `detectSlugCollisions` / `collisionsTouchingGold` name the ambiguous slugs (a gold-touching collision makes the harness emit an error row), `goldMissingFromHaystack` counts dataset defects, and `normalizeSessionId` exists only for the opaque-id hash input and legacy-row rawification — never for the gold compare. k semantics: `recall_*@k` is scored over the DISTINCT sessions among the top-k CHUNK rows returned at `limit: k` (the caller slices first; `scoreRecall` treats k as a guard); empty gold scores both hits false, not vacuously true, and such rows stay out of the denominator. `addRowToBucket` folds a v2 row into `total`/`all_hit`/`any_hit`; a row carrying only the deprecated any-only `recall_hit` counts toward `total` + `any_hit` and bumps `legacy_rows` (its `all_rate` is therefore a lower bound); `buildByTypeSummaryV2` emits sorted type keys, `null` rates on empty buckets, `mean_distinct_sessions`, and the caller's `run_config`. `buildRow` assembles the JSONL row — scored fields over `results.slice(0, k)`, `retrieved[]` + `retrieved_session_ids` over EVERY returned row so replay can re-score at any smaller k — and harness passthrough `extra` keys never override the scored fields. Pinned by `test/longmemeval-metrics.test.ts`.- `src/eval/longmemeval/resume.ts` — reading a prior run's JSONL back: row scanning, the mixed-run check, expansion-variant replay maps, and per-type bucket re-seeding. INVARIANT: recall is RECOMPUTED, never trusted — `seedBucketsFromRows` re-derives both metrics for every prior row from `retrievedIdsAtK` (prefers `retrieved[]` sliced to k; falls back to the older `retrieved_session_ids` shape) joined against the dataset's gold, so a file written before the raw-id join simply scores false instead of poisoning the summary, and there is no legacy any-only counter. `readJsonlRows` skips corrupt lines (a SIGKILL tail); `isScoredQuestionRow` excludes summaries and hypothesis-less error rows (those are retried); `checkResumeConfigHash` reports rows stamped with a foreign `retrieval_config_hash` (refused by the harness unless `--allow-mixed-run-config`) and tolerates unstamped rows; `loadExpansionReplay` maps `question_id` → recorded `expansion_variants`. Pure given its inputs (file reads are the only I/O).- `src/eval/longmemeval/run-config.ts` — the resolved retrieval pins, `retrieval_config_hash`, the `run_config` receipt block, secret redaction, and the `--question-ids` loader. Pure given its inputs (the harness resolves the mode bundle and the embedder string and passes them in). `RetrievalPins` = `{mode, keyword_only, reranker: {enabled, model}, autocut, expansion, expansion_variant_budget, embedder (model@dims or 'unconfigured'), top_k, trajectory}`; `retrievalConfigHash(pins, {knobs_hash, knobs_hash_version})` is sha256 over `stableStringify` (sorted keys at every level) of the pins PLUS the resolved `knobsHash`, so two runs hash equal regardless of flag order, dataset, output path or clock, and a resume file written under a config snapshot that differs in ANY result-shaping knob — not just a pin — is a different run. `redactSecrets` (URL userinfo, bearer tokens, secret-looking `key=value` pairs, provider key prefixes, `?password=`) is applied to every error string BEFORE it lands in a receipt row or the eval ledger. `loadQuestionIds` reads one id per line with `#` comments, dedupes, and throws on a missing or empty file. `buildRunConfig` stamps the summary's `run_config` (pins, `expansion_replay`, dataset sha256 + count, `question_ids_file`, both hashes, the `CacheReceipt` `{path, hits, misses, bypassed, infra_faults, canonical_sha256, sha256}` or `cache: null` + `cache_skipped` reason, and the counters `reranker_skipped_rows`, `vector_degraded_rows`, `expansion_failed_rows`, `expansion_replay_miss`, `gold_missing_from_haystack`, `slug_collisions`, `excluded_abstention`, `errors`).-- `src/eval/retrieval-quality/harness.ts` + `src/commands/eval-retrieval-quality.ts` + `test/fixtures/retrieval-quality/namedthing.jsonl` + `test/fixtures/retrieval-quality/namedthing/corpus.ts` — NamedThingBench, the retrieval-quality eval that pins the named-thing-miss failure class. Seven query families, each a distinct failure class: `title-substring` (the named-thing miss itself), `generic-to-named` (tourist label → named thing), `alias-synonym` (declared alias / romanization → canonical), `multi-chunk-dilution` (one strong chunk among many weak — stresses max-pool), `short-vs-rich`, `graph-relationship` (guardrail), `hard-negative` (precision guard, must NOT return a page). `gbrain eval retrieval-quality <fixture.jsonl>` runs it with hard gates (e.g. title-substring Hit@1 ≥ 0.95, alias Hit@1 ≥ 0.98, multi-chunk-dilution Hit@3 = 1.0). Pure: caller injects a `SearchFn` (CLI uses `hybridSearch`, tests stub) so it's engine-agnostic. Metric glossary entries (`hit@1`/`hit@3`) added to `src/core/eval/metric-glossary.ts`. Pinned by `test/eval-retrieval-quality.test.ts` + `test/retrieval-quality-harness.test.ts`. The seed corpus (`NAMEDTHING_CORPUS`, `seedNamedThingCorpus(engine, { embed? })`, `loadNamedThingQuestions()`) lives in `test/fixtures/retrieval-quality/namedthing/corpus.ts` — the ONE brain the fixture is written against (sibling of `relational/corpus.ts`), seeded without vectors by the hermetic gate and with real vectors by the R1 A/B script, so a paid receipt and the CI gate describe the same pages. The committed fixture is 12 queries — 11 non-relational core queries plus one `graph-relationship` query, which R1 scores together with `relational/corpus.ts`'s 38 `RELATIONAL_QUESTIONS` as the 39 relational questions. `seedNamedThingCorpus` seeds exactly what the gate always seeded (`putPage` with `compiled_truth` = the chunks joined, one `upsertChunks` row per chunk with `token_count: 10`, lower-cased `setPageAliases` when declared) and, when `embed` is supplied, embeds every chunk text in ONE batch and stores the vectors (a count mismatch throws); the result reports `pages`, `chunks`, `embedded`, `embedded_chars` for spend accounting. Change pages, chunk boundaries or aliases only together with the fixture and its gate expectations.+- `src/eval/retrieval-quality/harness.ts` + `src/commands/eval-retrieval-quality.ts` + `test/fixtures/retrieval-quality/namedthing.jsonl` + `test/fixtures/retrieval-quality/namedthing/corpus.ts` — NamedThingBench, the retrieval-quality eval that pins the named-thing-miss failure class. Seven query families, each a distinct failure class: `title-substring` (the named-thing miss itself), `generic-to-named` (tourist label → named thing), `alias-synonym` (declared alias / romanization → canonical), `multi-chunk-dilution` (one strong chunk among many weak — stresses max-pool), `short-vs-rich`, `graph-relationship` (guardrail), `hard-negative` (precision guard, must NOT return a page). `gbrain eval retrieval-quality <fixture.jsonl>` runs it with hard gates (e.g. title-substring Hit@1 ≥ 0.95, alias Hit@1 ≥ 0.98, multi-chunk-dilution Hit@3 = 1.0). Pure: caller injects a `SearchFn` (CLI uses `hybridSearch`, tests stub) so it's engine-agnostic. A search call that throws is stamped `errored: true` and scored as a miss in every family (never a clean hard-negative); `report.errored` / per-family `errored` count them and any errored question fails the gate. Metric glossary entries (`hit@1`/`hit@3`) added to `src/core/eval/metric-glossary.ts`. Pinned by `test/eval-retrieval-quality.test.ts` + `test/retrieval-quality-harness.test.ts`. The seed corpus (`NAMEDTHING_CORPUS`, `seedNamedThingCorpus(engine, { embed? })`, `loadNamedThingQuestions()`) lives in `test/fixtures/retrieval-quality/namedthing/corpus.ts` — the ONE brain the fixture is written against (sibling of `relational/corpus.ts`), seeded without vectors by the hermetic gate and with real vectors by the R1 A/B script, so a paid receipt and the CI gate describe the same pages. The committed fixture is 12 queries — 11 non-relational core queries plus one `graph-relationship` query, which R1 scores together with `relational/corpus.ts`'s 38 `RELATIONAL_QUESTIONS` as the 39 relational questions. `seedNamedThingCorpus` seeds exactly what the gate always seeded (`putPage` with `compiled_truth` = the chunks joined, one `upsertChunks` row per chunk with `token_count: 10`, lower-cased `setPageAliases` when declared) and, when `embed` is supplied, embeds every chunk text in ONE batch and stores the vectors (a count mismatch throws); the result reports `pages`, `chunks`, `embedded`, `embedded_chars` for spend accounting. Change pages, chunk boundaries or aliases only together with the fixture and its gate expectations.- `src/eval/shared/autocut-replay.ts` + `scripts/replay-autocut-floor.ts` — pure replay of the autocut weak-top-floor sweep over captured rerank pools, and its CLI. INVARIANT: the replay uses the SAME `applyAutocut` the live path uses, over the SAME pre-autocut reranked pool (`gbrain eval longmemeval --capture-pool` → `rerank_pool`, unscored alias/exact-lookup rows included — dropping them would change `decision.total`), with the SAME preserve predicate (`alias_hit === true || exact_lookup === true`), and slices to k AFTER autocut exactly like hybrid.ts, so `validateLive(rows, floor)` can demand byte-for-byte agreement with the recorded live decision (`search_meta.autocut`, plus `autocut_kept_keys` when present) before any other floor cell is trusted. Every cell — including floor `off` — comes from ONE capture; no second reranker call. Metric semantics mirror the harness (`distinct` sessions among the first k kept chunk rows; `recall_all` = gold ⊆ distinct; `recall_any` = non-empty intersection), with the benefit metrics `mean_returned_results` / `mean_returned_est_tokens` (why autocut exists) and recall as the guardrail; `pairedDelta` gives wins/losses/net per type vs the first floor, `splitHalf(rows, seed)` gives a seeded half-A/half-B selection/confirmation split, `topScoreHistogram` publishes the reranker's top-score distribution. `normalizePoolRow` throws on a row without `slug`/`session_id` (a silently dropped row shifts every cliff). The script owns argv (`<capture.ndjson> --floors off,0.10,… [--k 5] [--validate-live F] [--split-half SEED] [--jump 0.2] [--min-keep 1] [--json]`; `--validate-live` takes exactly one floor), file I/O and printing; every metric it prints routes through `src/core/eval/metric-glossary.ts` (`REPLAY_GLOSSARY_KEYS`); exit 0 ok · 1 validate-live mismatch or bad input · 2 usage. Pinned by `test/replay-autocut-floor.test.ts`.diff --git a/docs/eval/FIX_WAVE_BASELINES.md b/docs/eval/FIX_WAVE_BASELINES.mdindex b24df50c3d..bf1b1bf364 100644--- a/docs/eval/FIX_WAVE_BASELINES.md+++ b/docs/eval/FIX_WAVE_BASELINES.md@@ -23,6 +23,47 @@ touch `~/.gbrain` per the eval discipline — results land in`<repo>/.gbrain-evals/eval-results.jsonl`). Record the gate verdict + headlinemetrics here per run.+## Read-path wave (2026-09-28, v0.59.13.0)++Page-grain fusion, identity tiers that keep the reranker order, soft auto+entity detail, title/alias-mention boost, and the LongMemEval opaque session+ids. Three arms on the measured base `6bb88d1`, all with the opaque-id scorer so+the leak fix does not confound them: A = unchanged ranking, B = A + page-grain+fusion only, C = the whole wave. Same data, one embedding cache+(`openai:text-embedding-3-large@1536`; B and C ran with 0 cache misses against+A's vectors), `limit 5`, reranker off, autocut off, expansion off, trajectory+off. Question set: the committed `halfA430` split in+`evals/longmemeval/splits-seed42.json` (215 scored questions).++```bash+gbrain eval longmemeval longmemeval_s_cleaned.json --retrieval-only --top-k 5 \+ --by-type --no-trajectory --mode balanced --reranker off --autocut off \+ --question-ids halfA430.txt --embed-cache embed.sqlite --output armX.ndjson+```++| Arm | `recall_all@5` | `recall_any@5` | Mean distinct sessions in top 5 | Paired vs A |+|---|---|---|---|---|+| A unchanged ranking | 203/215 (94.42%) | 211/215 | 4.912 | |+| B page-grain fusion, every chunk carries the page score (rejected) | 201/215 (93.49%) | 211/215 | 4.879 | +0 / −2 |+| B page-grain fusion, lead chunk only (shipped) | 202/215 (93.95%) | 211/215 | 4.907 | +0 / −1 |+| C whole wave (lead-chunk fusion) | 202/215 (93.95%) | 211/215 | 4.907 | +0 / −1 |++- The first fusion design let a page's second chunk inherit the page score and+ crowd other sessions out of the five-chunk window (both losses were+ multi-session questions whose distinct-session count dropped). Only the+ page's lead chunk now carries the summed vote.+- The remaining loss, `gpt4_ab202e7f`, needs all five of its gold sessions in+ five chunks; a distractor that two retrieval arms agreed on took one slot.+- Evidence-span check (a returned chunk contains a window of an answer-bearing+ turn, from the dataset's `has_answer` labels): identical across A, B and C,+ 93/215 all-evidence and 163/215 any-evidence.+- B and C differ in no top-5 chunk on this corpus: the other ranking fixes+ target timelines, aliases, rerank order and identity lookups, which these+ chat sessions do not exercise.+- Verdict: flat on LongMemEval recall (−1, no gains; exact McNemar p = 1.0).+ The fusion change is kept because it corrects a reproduced ranking defect+ (`test/search/rrf-page-grain.test.ts`), not because it moved this benchmark.+## Ranker wave (2026-09-06, branch stuttgart, v0.48.4.0)The read-path wave whose receipt producer is the in-repo harnessdiff --git a/docs/guides/capabilities.md b/docs/guides/capabilities.mdindex fbab61ce3c..2450639907 100644--- a/docs/guides/capabilities.md+++ b/docs/guides/capabilities.md@@ -2,7 +2,7 @@**Hybrid search.** Vector (HNSW on pgvector) + BM25 keyword + reciprocal-rank fusion + source-tier boost + intent-aware query rewriting. Three named search modes (`conservative`, `balanced`, `tokenmax`) bundle the cost/quality knobs into a single config key. Live cost/recall comparisons in [`docs/eval/SEARCH_MODE_METHODOLOGY.md`](../eval/SEARCH_MODE_METHODOLOGY.md). The install picker default-applies `tokenmax` (it recommends `conservative` for Haiku-class subagent tiers or keyless setups); a brain with `search.mode` unset resolves to `balanced` at query time. The cross-encoder reranker is on in `balanced` and `tokenmax`, off in `conservative` — the default is Voyage `rerank-2.5` on `VOYAGE_API_KEY`; without the key search fails open in fusion order and `gbrain search modes` / `gbrain doctor` say so (ask your agent *"check whether my brain's reranker is actually running"*). Per-query graph signals notice when a top result is a hub for THAT query (adjacency boost), is corroborated across team brains (cross-source boost), or is being crowded out by weak chunks from a chatty session (session demote). Run `gbrain search "<query>" --explain` to see per-stage attribution: base score, every boost that fired, what it multiplied. `gbrain doctor` ships a `graph_signals_coverage` check; `gbrain search stats` shows fire counts and failure breakdowns. Vector retrieval pools the best chunk per page, so a page surfaces on its strongest evidence instead of losing to a neighbor on one weak chunk. Queries that match a page's title phrase or a declared free-text alias (`gbrain reindex --aliases` backfills existing pages) get boosted to the page they name. Every result carries an `evidence` tag (why it matched) and a `create_safety` hint (`exists` / `probable` / `unknown`) so an agent decides whether a page already exists instead of guessing from a raw score. `gbrain search diagnose "<query>" --target <slug>` traces which retrieval layer surfaces (or misses) a page. **Say to your agent:** *"Tune my retrieval"* — *"What search mode am I running?"* — *"Why did this page rank first?"* (your agent runs `gbrain search --explain`).-**Self-wiring knowledge graph.** Trusted local `put_page` extracts supported references without LLM calls when auto-linking is enabled. Remote MCP writes save references as text without inline graph extraction; stdio has best-effort startup/idle sweeps, while HTTP requires explicit host maintenance or authorized `add_link`. See [memory boundaries](memory-boundaries.md#page-writes-and-the-graph-are-separate-outcomes). Typed edges (`attended`, `works_at`, `invested_in`, `founded`, `advises`, `mentions`, …). Multi-hop traversal via `gbrain graph-query`. The README reports a +31.4-point P@5 lift over the graph-disabled variant on one synthetic BrainBench corpus; this is not a universal retrieval guarantee. **Say to your agent:** *"Who works at acme-example?"* — *"What's the relationship between fund-a and widget-co?"* — *"What connections does alice-example have?"* **Obsidian-style vaults:** bare `[[note-name]]` wikilinks that point across folders — you wrote `[[struktura]]` but the page lives at `projects/struktura.md` — resolve by basename once you opt in with `gbrain config set link_resolution.global_basename true`. Off by default; `gbrain doctor` tells you how many edges you'd gain before you flip it. See [migrating an Obsidian vault](../../INSTALL_FOR_AGENTS.md#step-45-wire-the-knowledge-graph).+**Self-wiring knowledge graph.** Trusted local `put_page` extracts supported references without LLM calls when auto-linking is enabled. Remote MCP writes save references as text without inline graph extraction; stdio has best-effort startup/idle sweeps, while HTTP requires explicit host maintenance or authorized `add_link`. See [memory boundaries](memory-boundaries.md#page-writes-and-the-graph-are-separate-outcomes). Typed edges (`attended`, `works_at`, `invested_in`, `founded`, `advises`, `mentions`, …). Multi-hop traversal via `gbrain graph-query`. On the synthetic BrainBench relationship questions the specialized graph adapter measured mean P@5 0.3421 / R@5 0.9791 versus 0.1917 / 0.6874 for the reference hybrid ([September 9, 2026 refresh](https://github.com/garrytan/gbrain-evals/blob/main/docs/benchmarks/2026-09-09-retrieval-refresh.md)); that compares whole systems on four templates and is not a graph-only lift or a universal retrieval guarantee. **Say to your agent:** *"Who works at acme-example?"* — *"What's the relationship between fund-a and widget-co?"* — *"What connections does alice-example have?"* **Obsidian-style vaults:** bare `[[note-name]]` wikilinks that point across folders — you wrote `[[struktura]]` but the page lives at `projects/struktura.md` — resolve by basename once you opt in with `gbrain config set link_resolution.global_basename true`. Off by default; `gbrain doctor` tells you how many edges you'd gain before you flip it. See [migrating an Obsidian vault](../../INSTALL_FOR_AGENTS.md#step-45-wire-the-knowledge-graph).**Job queue (Minions).** BullMQ-shaped, Postgres-native job queue. Durable subagents (LLM tool loops that survive crashes via two-phase pending→done persistence), shell jobs with audit, child jobs with cascading timeouts, rate leases for outbound providers, attachments via S3/Supabase storage. Opt-in per-job process isolation (`gbrain jobs work --job-isolation process`) runs each claimed job in its own SIGKILL-able child process, so a stuck handler dies for real and a crash takes one job instead of the whole worker; when the worker's DB health probe fails, it names the failing layer (`pool_starved` vs `server_unreachable`) instead of a blanket "DB unreachable". Sizing and rollout guidance in [`docs/guides/minions-deployment.md`](minions-deployment.md); probe-verdict triage in [`docs/guides/queue-operations-runbook.md`](queue-operations-runbook.md). Replaces "spawn subagent as fire-and-forget Promise" with durable job state and explicit recovery paths. **Say to your agent:** *"Run this as a background task and tell me when it's done"* — *"Submit a gbrain job for the backfill"* — *"What's running in the background?"*diff --git a/llms-full.txt b/llms-full.txtindex baa3111cb6..46bac6b30c 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -3200,7 +3200,7 @@ I'm Garry Tan, President and CEO of Y Combinator. I built GBrain to run my own AAlongside keyword and semantic retrieval, GBrain offers two optional ways to use your stored knowledge:- **A synthesis layer that gives you the actual answer.** Synthesized, well-cited prose across people, companies, deals, and ideas. Not "here are 10 chunks that mention your query"; an actual answer with citations and an explicit note on what the brain doesn't know yet. The gap analysis is the part that changes how you use the brain.-- **A typed knowledge graph.** Trusted local page writes extract supported references without LLM calls when auto-linking is enabled. Remote `put_page` does not extract graph edges inline: stdio has best-effort startup/idle sweeps; HTTP needs explicit maintenance or authorized `add_link` calls. Ask "who works at acme-example?" to use stored relationships. A 240-page Opus-generated rich-prose BrainBench run reported **P@5 49.1%, R@5 97.9%**, with **+31.4 points P@5** over its graph-disabled variant. These are scoped benchmark results, not a guarantee for every corpus. Scorecards: [gbrain-evals](https://github.com/garrytan/gbrain-evals).+- **A typed knowledge graph.** Trusted local page writes extract supported references without LLM calls when auto-linking is enabled. Remote `put_page` does not extract graph edges inline: stdio has best-effort startup/idle sweeps; HTTP needs explicit maintenance or authorized `add_link` calls. Ask "who works at acme-example?" to use stored relationships. On BrainBench relationship questions a graph adapter scored **P@5 0.3421, R@5 0.9791** vs 0.1917 / 0.6874 plain hybrid ([2026-09-09 refresh](https://github.com/garrytan/gbrain-evals/blob/main/docs/benchmarks/2026-09-09-retrieval-refresh.md)): whole systems, not a graph-only lift or a general guarantee.The point of building a 150K-page brain is to use it as a strategic moat. To never lose context. To query what's in your own head without re-reading it. The brain layer is what makes the moat usable. The 24/7 dream cycle is what keeps it sharp. Both run on your hardware, your DB, your keys.diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex 0c3645c2bd..04e7786bc1 100644--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@ -1,7 +1,7 @@{"id": "gbrain-context-engine","name": "gbrain",- "version": "0.59.11.0",+ "version": "0.59.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 5d153ab2ed..a5d2b1069a 100644--- a/package.json+++ b/package.json@@ -190,7 +190,7 @@"bun": ">=1.3.11"},"license": "MIT",- "version": "0.59.11.0",+ "version": "0.59.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 2d14389cf6..8597965b06 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.59.11.0",+ "version": "0.59.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 9f0a053a4d..ef77b98563 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.59.11.0",+ "version": "0.59.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 5662f026c4..6c378d7830 100644--- a/plugin-variants/gbrain-coding/README.md+++ b/plugin-variants/gbrain-coding/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.59.11.0 -->+<!-- gbrain-plugin-tree-stamp: 0.59.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-daily/.claude-plugin/plugin.json b/plugin-variants/gbrain-daily/.claude-plugin/plugin.jsonindex 4f144e1d06..a570ca0c9e 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.59.11.0",+ "version": "0.59.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 78a5f87df8..382a966343 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.59.11.0",+ "version": "0.59.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 ebd759de46..ae60d4d907 100644--- a/plugin-variants/gbrain-daily/README.md+++ b/plugin-variants/gbrain-daily/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.59.11.0 -->+<!-- gbrain-plugin-tree-stamp: 0.59.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/README.md b/plugin/README.mdindex 14ca9883c3..f944fa828b 100644--- a/plugin/README.md+++ b/plugin/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.59.11.0 -->+<!-- gbrain-plugin-tree-stamp: 0.59.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/scripts/eval-answer-packet.ts b/scripts/eval-answer-packet.tsindex e06a1818e1..52b8d6d161 100644--- a/scripts/eval-answer-packet.ts+++ b/scripts/eval-answer-packet.ts@@ -4,7 +4,7 @@ import { chat, configureGateway, type ChatOpts, type ChatResult } from '../src/cimport { withAIInvocationGuard, type AIInvocationUsage } from '../src/core/ai/invocation-guard.ts';import { BudgetTracker } from '../src/core/budget/budget-tracker.ts';import { canonicalLookup } from '../src/core/model-pricing.ts';-import { normalizeSessions, haystackToPages, type LongMemEvalQuestion } from '../src/eval/longmemeval/adapter.ts';+import { normalizeSessions, haystackToPages, opaqueSessionId, type LongMemEvalQuestion } from '../src/eval/longmemeval/adapter.ts';import { buildEvidencePacket, renderFullSessions, type EvidenceSession } from '../src/eval/longmemeval/evidence-packet.ts';import { buildReaderUserText, READER_SYSTEM_TEXT, READER_MAX_TOKENS, READER_MAX_SESSION_CHARS } from '../src/eval/longmemeval/reader.ts';import { sanitizeChatContent } from '../src/eval/longmemeval/sanitize.ts';@@ -52,7 +52,8 @@ export function freezeEvidence(q: Question, row: Receipt): EvidenceSession[] {const i = sessions.findIndex(s => s.session_id === id);if (i < 0) throw new Error(`Missing saved session: ${id}`);if (sessions.filter(s => s.session_id === id).length !== 1 || pages.filter(p => p.slug === pages[i].slug).length !== 1) throw new Error('Missing or ambiguous saved session');- return { source_id: 'longmemeval-public', session_id: id, date: q.haystack_dates?.[i], body: pages[i].content, turns: sessions[i].turns.map(t => ({ role: t.role, content: t.content })) };+ // Reader-visible id is opaque (gold ids start with `answer_`); scoring uses the receipt's raw ids.+ return { source_id: 'longmemeval-public', session_id: opaqueSessionId(q.question_id, id), date: q.haystack_dates?.[i], body: pages[i].content, turns: sessions[i].turns.map(t => ({ role: t.role, content: t.content })) };});}@@ -342,7 +343,7 @@ async function main(args: string[]) {outcomes[`${arm}_correct`] = judge.verdict === 'correct';}const row = { phase, variant, question_id: id, category: q.question_type, abstention: id.endsWith('_abs'),- retrieval_complete: q.answer_session_ids.length > 0 && q.answer_session_ids.every(id => sources.some(s => s.session_id === id)),+ retrieval_complete: q.answer_session_ids.length > 0 && q.answer_session_ids.every(gold => receipts.find(r => r.question_id === id)!.retrieved_session_ids.includes(gold)),...outcomes, arm_order: order, budget_fallback: packet.budget_fallback, provider_count_fallback: providerCountFallback,baseline_input_count: countBaseline, candidate_input_count: countCandidate };appendRecord(pairsPath, row);diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex d29eef1380..32f44b2abe 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -20,10 +20,10 @@ src/core/engine.ts 2665 ratchet grown v0.46.26.0 megawave: relational/visibilitysrc/core/import-file.ts 2236 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 anchorsrc/core/migrate.ts 722 region-exempt append-only MIGRATIONS array grows freely; runner logic is ratcheted — grown v0.46.26.0: repair-handler hooks (#3957 pages-upsert-arbiter); wave-k v142 takes-embedding resize is in-region (renumbered from v141; master consumed v141 for #4482); master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: projection migration helper; #5105: lease schema helper; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +1 import for focused topology migration module; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: static projection statistics import; DDL remains region-exempt; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestionsrc/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 6133 ratchet +6 #4881: ontology provenance-page visibility gate (getOntology/findOntologyConflicts); grown v0.46.26.0 megawave parity twins + master v0.46.26.0 private-queue columns; +#3754 traverseGraph soft-delete filters; grown wave-g (#4524 #4527): canonical islanded orphans + timestamp-preserving migrate; wave-k: +1 semantic takes retrieval delegate (#3776), +5 NUL-sanitize shared chunk_text local (#3998), +7 getAllConfig bulk read (#3980); +22: pre-close WAL CHECKPOINT in disconnect (#3893); +10: #4109 atomic link/timeline mutation + typed per-endpoint miss (parity); +1: getBacklinkCounts page-id keying comment (#4380); +14: dream-verdict TTL expiry predicate + sweep (#4069); +7 test-gap-wave merge true-up; +23: softDeletePages batch soft-delete primitive (#4587, parity twin); +51: #4592 source-scoped getStats/getHealth (bound $1 scope, both-endpoint link rule); +5 file-bytes snapshot hash (coverage-immune — CI shards were silently cold-initting); +7 2026-09 fix wave (#3617 follow-up): OR-fallback rows tagged keyword_relaxed in searchKeyword + title arm (fusion demotion reads it); cold-initting); +11: #4280 orphan/health served-memory denominators (quarantine + leaf-type metadata); composition true-up (fix-wave multi-train); +14: traversePathsDetailed row cap (LIMIT + truncated probe, parity twin); +7: resolveSlugWithAliasDetailed (owning source_id, parity twin) | merged v0.48.1.0 true-up; corrective release: shared batched enrichment peel; concrete content and Chronicle authorization; +2: #4681 listPages projects updated_at_iso (microsecond keyset cursor); master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: grant and authority schema bootstrap parity; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; upstream integration: preserve independently reviewed master additions with branch facade extraction; +1 v0.50.5.0 security merge (upstream delta; coordinated facade retained); +7 ceiling: bounded in-memory create retry with attached-database exclusion and second-failure diagnostics; #5252 bounded candidate recovery and statistics snapshot dependency; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared-skills integration on company-ingestion base; shared skills: include explicit access DDL in snapshot invalidation; archived eligibility: source-locked drift and raw signature mutations; +6 write-path wave: updateSlug records its rename alias in one transaction+src/core/pglite-engine.ts 6144 ratchet +6 #4881: ontology provenance-page visibility gate (getOntology/findOntologyConflicts); grown v0.46.26.0 megawave parity twins + master v0.46.26.0 private-queue columns; +#3754 traverseGraph soft-delete filters; grown wave-g (#4524 #4527): canonical islanded orphans + timestamp-preserving migrate; wave-k: +1 semantic takes retrieval delegate (#3776), +5 NUL-sanitize shared chunk_text local (#3998), +7 getAllConfig bulk read (#3980); +22: pre-close WAL CHECKPOINT in disconnect (#3893); +10: #4109 atomic link/timeline mutation + typed per-endpoint miss (parity); +1: getBacklinkCounts page-id keying comment (#4380); +14: dream-verdict TTL expiry predicate + sweep (#4069); +7 test-gap-wave merge true-up; +23: softDeletePages batch soft-delete primitive (#4587, parity twin); +51: #4592 source-scoped getStats/getHealth (bound $1 scope, both-endpoint link rule); +5 file-bytes snapshot hash (coverage-immune — CI shards were silently cold-initting); +7 2026-09 fix wave (#3617 follow-up): OR-fallback rows tagged keyword_relaxed in searchKeyword + title arm (fusion demotion reads it); cold-initting); +11: #4280 orphan/health served-memory denominators (quarantine + leaf-type metadata); composition true-up (fix-wave multi-train); +14: traversePathsDetailed row cap (LIMIT + truncated probe, parity twin); +7: resolveSlugWithAliasDetailed (owning source_id, parity twin) | merged v0.48.1.0 true-up; corrective release: shared batched enrichment peel; concrete content and Chronicle authorization; +2: #4681 listPages projects updated_at_iso (microsecond keyset cursor); master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: grant and authority schema bootstrap parity; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; upstream integration: preserve independently reviewed master additions with branch facade extraction; +1 v0.50.5.0 security merge (upstream delta; coordinated facade retained); +7 ceiling: bounded in-memory create retry with attached-database exclusion and second-failure diagnostics; #5252 bounded candidate recovery and statistics snapshot dependency; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared-skills integration on company-ingestion base; shared skills: include explicit access DDL in snapshot invalidation; archived eligibility: source-locked drift and raw signature mutations; +6 write-path wave: updateSlug records its rename alias in one transaction; +11 read-path wave: searchKeyword type/exclude_slugs Postgres parity + getTags private/deleted filterssrc/core/postgres-engine.ts 5577 ratchet +6 #4881: ontology provenance-page visibility gate (parity twin); lowered wave-g: #4477 bootstrap peel to src/core/postgres-engine/ modules (ratchet holds the win); +2 on wave-g-prs merge true-up; wave-k: +2 semantic takes retrieval (#3776), +5 NUL-sanitize shared chunk_text local (#3998), +11 getAllConfig bulk read (#3980); +13: #4109 atomic FOR KEY SHARE link/timeline mutation + typed per-endpoint miss; +2: getBacklinkCounts page-id keying comment (#4380); +12: dream-verdict TTL expiry predicate + sweep (#4069); +23: softDeletePages batch soft-delete primitive (#4587, parity twin); +61: #4592 source-scoped getStats/getHealth (scope predicate, both-endpoint link rule); +11 2026-09 fix wave (#3617 follow-up): OR-fallback rows tagged keyword_relaxed in searchKeyword + title arm (fusion demotion reads it); rule); +12: #4280 orphan/health served-memory denominators (quarantine + leaf-type metadata, parity twin); composition true-up (fix-wave multi-train); +14: traversePathsDetailed row cap (LIMIT + truncated probe, parity twin); +7: resolveSlugWithAliasDetailed (owning source_id, parity twin) | merged v0.48.1.0 true-up; corrective release: shared batched enrichment peel; concrete content and Chronicle authorization; +3: #4681 listPages projects updated_at_iso (microsecond keyset cursor, parity twin); #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop barrier and direct transaction route; upstream integration: preserve independently reviewed master additions with branch facade extraction; +1 v0.50.5.0 security merge (upstream delta; coordinated facade retained)src/core/search/hybrid.ts 3215 ratchet +2: preserve local query-deadline classification through gateway error wrapping; grown v0.46.26.0 megawave: CRAG escalation seam, degradation visibility, excludePrivate knobs-fold v23 (#1663 #3873 #4352); grown #4356: semantic-cache-hit slice honors resolved mode searchLimit (double-resolution caveat); grown #4414: offset!==0 cache-skip widening + knobs-hash v24; grown #4487: chunkless rows join the cosine blend (no raw-score head start); grown wave-g (#4480 #4415): shared salience/recency resolution + pattern-aware cache keying; grown db-availability loop: all-lexical-arms-dead access-error rethrow (a dead DB must never return an empty success) — refined to both-arms-FAILED (a succeeded-but-empty arm proves the DB is alive); grown v0.46.26.0 megawave: CRAG escalation seam, degradation visibility, excludePrivate knobs-fold v23 (#1663 #3873 #4352); grown #4356: semantic-cache-hit slice honors resolved mode searchLimit (double-resolution caveat); grown #4414: offset!==0 cache-skip widening + knobs-hash v24; grown #4487: chunkless rows join the cosine blend (no raw-score head start); grown wave-g (#4480 #4415): shared salience/recency resolution + pattern-aware cache keying; +2: backlink-boost counts page-id keying doc (#4380); +59 2026-09 adversarial batch 2: both-mode text-only demotion gate (textVectorArmNonEmpty) + relaxed_dropped meta + keyword_relaxed_carried degraded stamp + intent-skew caveat docs; +35 #3617 follow-up: relaxed-row fusion demotion (vectorArmNonEmpty gate + keywordFusionList/titleFusionList) with the LongMemEval 51.3%-vs-93.8% receipt comment; +24 2026-08 eval fix wave (E5b/D8): adaptive-return knobs-hash v27 fold (resolved gate + intent class threaded to the cache key), adaptive-on skipCache removal, dedupOpts cache-skip honesty, explicit-maxPerPage min() precedence under walk widening; (#4380); +20 wave #4256: compiledTruthBoost helper — synthetic chunkless title rows (chunk_id 0 + empty chunk_text) never gain the 2x compiled-truth boost (#3695); composition true-up (fix-wave multi-train) | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: read-policy propagation and semantic result-cache containment; ranker wave v0.48.4.0: role-tagged fusion arms, relational rerank pin, metadata boost gate, per-call knob seams, onRerankPool hook (+150) merged over master's read-policy plumbing (+31); +11 #4359 (#4972): thread the loaded search-mode config snapshot from hybridSearchCached into the inner hybridSearch call (INTERNAL _searchModeInput opt) so both resolve from the same one DB-plane config read instead of two independent ones — closes the cache-key/result desync window and removes the second config-table round trip on every hybridSearchCached call; #5252 wave: inclusive date bounds and public vector incompleteness; shared date-bounds peel retains exports; merged company ingestion/schema routing changes; retired provider integration removed-src/core/types.ts 2073 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+src/core/types.ts 2076 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 notesrc/core/minions/queue.ts 2513 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 releasesrc/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)diff --git a/scripts/r1-namedthing-rerank-ab.ts b/scripts/r1-namedthing-rerank-ab.tsindex 7135004925..5308ebd49c 100644--- a/scripts/r1-namedthing-rerank-ab.ts+++ b/scripts/r1-namedthing-rerank-ab.ts@@ -325,7 +325,7 @@ export function r1Verdict(rows: readonly VerdictRow[]): R1Verdict {// ── Integrity (fail loudly, never fail open) ─────────────────────────────────-const RERANK_STAGES = new Set<string>(['reranker_skipped', 'rerank_passthrough']);+const RERANK_STAGES = new Set<string>(['reranker_skipped', 'rerank_passthrough', 'rerank_failed']);const EMBED_STAGES = new Set<string>(['embed_unavailable', 'embed_timeout', 'vector_arm_failed']);/**diff --git a/src/commands/eval-longmemeval.ts b/src/commands/eval-longmemeval.tsindex b2945ff701..e1815b6db4 100644--- a/src/commands/eval-longmemeval.ts+++ b/src/commands/eval-longmemeval.ts@@ -829,7 +829,7 @@ export async function runEvalLongMemEval(args: string[], runOpts: RunOpts = {}):// Gate on the RESOLVED reranker pin (flag, --search-pin, snapshot or bundle),// not the flag alone: a configured-but-silently-skipped reranker never exits 0.if (pins.reranker.enabled && st.rerankerSkippedRows > 0) {- process.stderr.write(`[longmemeval] FAIL reranker on (resolved pin): ${st.rerankerSkippedRows} row(s) fell through un-reranked (reranker_skipped / rerank_passthrough) — pass --reranker off or set the reranker provider key (e.g. VOYAGE_API_KEY)\n`);+ process.stderr.write(`[longmemeval] FAIL reranker on (resolved pin): ${st.rerankerSkippedRows} row(s) fell through un-reranked (reranker_skipped / rerank_passthrough / rerank_failed) — pass --reranker off or set the reranker provider key (e.g. VOYAGE_API_KEY)\n`);exitCode = 1;}// Every question of this run errored AND the output holds no scored rowdiff --git a/src/commands/eval-retrieval-quality.ts b/src/commands/eval-retrieval-quality.tsindex 7d48dc10f6..40ee2bf880 100644--- a/src/commands/eval-retrieval-quality.ts+++ b/src/commands/eval-retrieval-quality.ts@@ -101,11 +101,12 @@ export async function runEvalRetrievalQuality(engine: BrainEngine, args: string[console.log(` ${f.family.padEnd(22)} n=${f.n} Hit@1=${(f.hit_at_1 * 100).toFixed(0)}% Hit@3=${(f.hit_at_3 * 100).toFixed(0)}% MRR=${f.mrr.toFixed(3)}`);}console.log('');- if (gate.breaches.length) {+ if (!gate.pass) {console.log('GATE: FAIL');for (const b of gate.breaches) {console.log(` ✗ ${b.family} ${b.metric}=${(b.got * 100).toFixed(0)}% < floor ${(b.floor * 100).toFixed(0)}%`);}+ if (gate.errored > 0) console.log(` ✗ ${gate.errored} question(s) errored in search (scored as misses)`);} else {console.log('GATE: PASS');}diff --git a/src/core/engine.ts b/src/core/engine.tsindex aad719c94c..58834b13e2 100644--- a/src/core/engine.ts+++ b/src/core/engine.ts@@ -694,7 +694,7 @@ export interface TrajectoryOpts {since?: string | Date;/** Upper bound on valid_from (inclusive). YYYY-MM-DD or full ISO. */until?: string | Date;- /** Cap on points returned. Default 100, max 500. */+ /** Cap on points returned (the newest N, in chronological order). Default 100, max 500. */limit?: number;}@@ -1701,7 +1701,7 @@ export interface BrainEngine {* via `page_id IN (…) … DISTINCT`. The write-side addTag/removeTag deliberately* stay scalar-only — `allowedSources` is a read grant; writes route to one source.*/- getTags(slug: string, opts?: { sourceId?: string; sourceIds?: string[] }): Promise<string[]>;+ getTags(slug: string, opts?: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean; liveOnly?: boolean }): Promise<string[]>;// Timeline/**diff --git a/src/core/ops/tags.ts b/src/core/ops/tags.tsindex 3f690bf6de..01e2c24ff6 100644--- a/src/core/ops/tags.ts+++ b/src/core/ops/tags.ts@@ -6,7 +6,7 @@*/import type { Operation } from './contract.ts';-import { enforceClientSlugFence, sourceScopeOpts } from './context.ts';+import { enforceClientSlugFence, readPolicyOpts } from './context.ts';import { submitPageMutation } from '../persistence/page-mutations.ts';import { WRITE_REQUEST_PARAM } from '../persistence/params.ts';@@ -56,12 +56,19 @@ const get_tags: Operation = {slug: { type: 'string', required: true, description: 'Slug of the page whose tags to list.' },},handler: async (ctx, p) => {- // #2200: route through sourceScopeOpts so a federated read grant+ // #2200: route through the source scope (via readPolicyOpts) so a federated read grant// (ctx.auth.allowedSources) reaches the engine, not just scalar ctx.sourceId.// Was `ctx.sourceId ? {sourceId} : {}` — a federated client got '{}' →// engine fell back to 'default' (functionality gap + cross-source leak).- const sourceOpts = sourceScopeOpts(ctx);- return ctx.engine.getTags(p.slug as string, sourceOpts);+ // Untrusted callers never learn a private or soft-deleted page's tags+ // (readPolicyOpts resolves the operator's private-pages posture).+ const policy = await readPolicyOpts(ctx);+ return ctx.engine.getTags(p.slug as string, {+ sourceId: policy.sourceId,+ sourceIds: policy.sourceIds,+ excludePrivate: policy.excludePrivate,+ liveOnly: ctx.remote !== false,+ });},scope: 'read',cliHints: { name: 'tags', positional: ['slug'] },diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.tsindex b4190a9b0e..09d7c120af 100644--- a/src/core/pglite-engine.ts+++ b/src/core/pglite-engine.ts@@ -2487,6 +2487,15 @@ export class PGLiteEngine implements BrainEngine {params.push(opts.types);extraFilter += ` AND p.type = ANY($${params.length}::text[])`;}+ // Postgres parity: single-type filter and exact-slug excludes.+ if (opts?.type) {+ params.push(opts.type);+ extraFilter += ` AND p.type = $${params.length}`;+ }+ if (opts?.exclude_slugs?.length) {+ params.push(opts.exclude_slugs);+ extraFilter += ` AND p.slug != ALL($${params.length}::text[])`;+ }// v0.29.1 — since/until date filter (Postgres parity, codex pass-1 #10).// Reads against COALESCE(effective_date, updated_at) so date filtering// matches user intent (a meeting was on its event_date, not when it@@ -4547,7 +4556,7 @@ export class PGLiteEngine implements BrainEngine {return mutatePageTag(this, { sourceId: opts?.sourceId ?? 'default', slug }, tag, false);}- async getTags(slug: string, opts?: { sourceId?: string; sourceIds?: string[] }): Promise<string[]> {+ async getTags(slug: string, opts?: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean; liveOnly?: boolean }): Promise<string[]> {// #2200: federated grant (sourceIds[]) wins over scalar. `page_id IN (..)`// (not `= (..)`) so a slug present in >1 allowed source doesn't blow up;// DISTINCT unions tags across the matched pages. Scalar/unscoped keeps the@@ -4556,9 +4565,11 @@ export class PGLiteEngine implements BrainEngine {opts?.sourceIds && opts.sourceIds.length > 0? { sql: 'source_id = ANY($2::text[])', param: opts.sourceIds }: { sql: 'source_id = $2', param: opts?.sourceId ?? 'default' };+ const privacy = opts?.excludePrivate ? `AND ${privatePagesFilterFragment('pages')}` : '';+ const live = opts?.liveOnly ? 'AND deleted_at IS NULL' : '';const { rows } = await this.db.query(`SELECT DISTINCT tag FROM tags- WHERE page_id IN (SELECT id FROM pages WHERE slug = $1 AND ${scope.sql})+ WHERE page_id IN (SELECT id FROM pages WHERE slug = $1 AND ${scope.sql} ${privacy} ${live})ORDER BY tag`,[slug, scope.param]);diff --git a/src/core/pglite-engine/facts.ts b/src/core/pglite-engine/facts.tsindex ac9e268ca5..6b75ec0171 100644--- a/src/core/pglite-engine/facts.ts+++ b/src/core/pglite-engine/facts.ts@@ -495,7 +495,8 @@ export async function findTrajectory(deps: PgliteFactsDeps, opts: import('../eng// Build SQL dynamically. PGLite uses $N positional params; we// assemble the WHERE clauses + params array in tandem to keep them- // aligned. Final shape is single SELECT, ORDER BY (valid_from, id) ASC.+ // aligned. Selects the NEWEST `limit` points (ORDER BY … DESC) and+ // returns them chronologically, so a capped series keeps its latest value.const where: string[] = [useArray ? `source_id = ANY($1::text[])` : `source_id = $1`,`entity_slug = $2`,@@ -540,7 +541,7 @@ export async function findTrajectory(deps: PgliteFactsDeps, opts: import('../engAND embedded_text_hash=md5(fact) THEN embedding END AS embeddingFROM factsWHERE ${where.join(' AND ')}- ORDER BY valid_from ASC, id ASC+ ORDER BY valid_from DESC, id DESCLIMIT $${limitPlaceholder}`;const result = await deps.db.query<{@@ -557,7 +558,7 @@ export async function findTrajectory(deps: PgliteFactsDeps, opts: import('../engembedding: string | number[] | Float32Array | null;}>(sqlText, params);- return result.rows.map(r => {+ return result.rows.reverse().map(r => {// Inline embedding parser — mirrors rowToFact() at line 3911.let embedding: Float32Array | null = null;if (r.embedding != null) {diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex 0bc1bdcb6a..af13c271ed 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -3754,7 +3754,7 @@ export class PostgresEngine implements BrainEngine {return mutatePageTag(this, { sourceId: opts?.sourceId ?? 'default', slug }, tag, false);}- async getTags(slug: string, opts?: { sourceId?: string; sourceIds?: string[] }): Promise<string[]> {+ async getTags(slug: string, opts?: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean; liveOnly?: boolean }): Promise<string[]> {const sql = this.sql;// #2200: federated grant (sourceIds[]) wins over scalar sourceId. Use// `page_id IN (subquery)` — NOT `= (subquery)` — because a federated read of@@ -3765,9 +3765,11 @@ export class PostgresEngine implements BrainEngine {opts?.sourceIds && opts.sourceIds.length > 0? sql`source_id = ANY(${opts.sourceIds}::text[])`: sql`source_id = ${opts?.sourceId ?? 'default'}`;+ const privacy = opts?.excludePrivate ? sql.unsafe(`AND ${privatePagesFilterFragment('pages')}`) : sql``;+ const live = opts?.liveOnly ? sql`AND deleted_at IS NULL` : sql``;const rows = await sql`SELECT DISTINCT tag FROM tags- WHERE page_id IN (SELECT id FROM pages WHERE slug = ${slug} AND ${scope})+ WHERE page_id IN (SELECT id FROM pages WHERE slug = ${slug} AND ${scope} ${privacy} ${live})ORDER BY tag`;return rows.map((r) => r.tag as string);diff --git a/src/core/postgres-engine/facts.ts b/src/core/postgres-engine/facts.tsindex 6abab591b5..bb00628f62 100644--- a/src/core/postgres-engine/facts.ts+++ b/src/core/postgres-engine/facts.ts@@ -519,8 +519,9 @@ export async function findTrajectory(deps: PgFactsDeps, opts: import('../engine.const remoteFilter = opts.remote !== false;// Source-scope predicate: array path (federated) wins over scalar.- // Engine.ts contract: returns chronological points; regressions +- // drift_score are computed by the caller (src/core/trajectory.ts).+ // Engine.ts contract: returns chronological points (the NEWEST `limit`,+ // so a capped series keeps its latest value); regressions + drift_score+ // are computed by the caller (src/core/trajectory.ts).// v0.40.2.0 — kind filter ('all'|'metric'|'event'); event_type column.const rows = await sql<Array<{id: number;@@ -551,11 +552,11 @@ export async function findTrajectory(deps: PgFactsDeps, opts: import('../engine.${kind === 'event' ? sql`AND event_type IS NOT NULL` : sql``}${sinceDate ? sql`AND valid_from >= ${sinceDate}` : sql``}${untilDate ? sql`AND valid_from <= ${untilDate}` : sql``}- ORDER BY valid_from ASC, id ASC+ ORDER BY valid_from DESC, id DESCLIMIT ${limit}`;- return rows.map(r => ({+ return [...rows].reverse().map(r => ({fact_id: Number(r.id),valid_from: r.valid_from,metric: r.claim_metric,diff --git a/src/core/search/dedup.ts b/src/core/search/dedup.tsindex 8886bc023c..fd16a5d655 100644--- a/src/core/search/dedup.ts+++ b/src/core/search/dedup.ts@@ -7,6 +7,7 @@* 3. By type: no page type exceeds 60% of results* 4. By page: max N chunks per page (default 2)* 5. Compiled truth guarantee: ensure at least 1 compiled_truth chunk per page+ * (appended, never evicting a kept chunk; the output is re-sorted by score)** v0.18.0: every page key is composite (source_id, slug). Pre-v0.17 this* was slug alone — under multi-source uniqueness that would collapse two@@ -63,10 +64,11 @@ export function dedupResults(// Layer 4: Cap chunks per pagededuped = capPerPage(deduped, maxPerPage);- // Final pass: guarantee compiled_truth representation+ // Final pass: guarantee compiled_truth representation, then restore score+ // order (downstream slice / token budget / evidence assume it).deduped = guaranteeCompiledTruth(deduped, preDedup);- return deduped;+ return deduped.sort((a, b) => b.score - a.score);}/**@@ -180,7 +182,9 @@ function capPerPage(results: SearchResult[], maxPerPage: number): SearchResult[]/*** Final pass: for each page in results that has no compiled_truth chunk,- * swap in the best compiled_truth chunk from the pre-dedup set (if one exists).+ * add the best compiled_truth chunk from the pre-dedup set (if one exists).+ * It is appended, not swapped in: evicting the page's lowest kept chunk threw+ * away matching evidence (a 0.90 hit replaced by a 0.10 summary chunk).*/function guaranteeCompiledTruth(results: SearchResult[], preDedup: SearchResult[]): SearchResult[] {// Group results by composite page key (source_id, slug).@@ -208,17 +212,7 @@ function guaranteeCompiledTruth(results: SearchResult[], preDedup: SearchResult[if (!candidate) continue;- // Swap: replace the lowest-scored chunk from this page (same- // composite key match).- const lowestIdx = output.reduce((minIdx, r, idx) => {- if (pageKey(r) !== key) return minIdx;- if (minIdx === -1) return idx;- return r.score < output[minIdx].score ? idx : minIdx;- }, -1);-- if (lowestIdx !== -1) {- output[lowestIdx] = candidate;- }+ output.push(candidate);}return output;diff --git a/src/core/search/eval.ts b/src/core/search/eval.tsindex 3367eb0a41..1ef0cb99cc 100644--- a/src/core/search/eval.ts+++ b/src/core/search/eval.ts@@ -10,7 +10,9 @@*/import type { BrainEngine } from '../engine.ts';-import { embed } from '../embedding.ts';+import { embedQuery } from '../embedding.ts';+import { loadConfig, loadConfigWithEngine } from '../config.ts';+import { resolveEmbeddingColumn } from './embedding-column.ts';import { hybridSearch } from './hybrid.ts';import type { HybridSearchOpts } from './hybrid.ts';import { dedupeRankedKeys } from '../eval/ranked-docs.ts';@@ -238,8 +240,16 @@ async function runQuery(}if (strategy === 'vector') {- const embedding = await embed(query);- const results = await engine.searchVector(embedding, { limit });+ // Same query path production hybrid runs: the query-side embedding+ // (`input_type: query` on asymmetric providers) in the resolved column's+ // model, searched on that column. `embed()` is the DOCUMENT side and+ // handicapped the vector baseline on Voyage-class providers.+ const cfg = (await loadConfigWithEngine(engine).catch(() => null)) ?? loadConfig();+ const column = resolveEmbeddingColumn(undefined, cfg ?? { engine: 'pglite' });+ const embedding = await embedQuery(query, column.embeddingModel+ ? { embeddingModel: column.embeddingModel, dimensions: column.dimensions }+ : undefined);+ const results = await engine.searchVector(embedding, { limit, embeddingColumn: column });return results.map(r => r.slug);}diff --git a/src/core/search/exact-lookup.ts b/src/core/search/exact-lookup.tsindex 0a68f7712c..fabb7bd16e 100644--- a/src/core/search/exact-lookup.ts+++ b/src/core/search/exact-lookup.ts@@ -172,8 +172,10 @@ export async function structuralExactLookup(* Promote/inject structural exact-lookup hits into a ranked result set.* Mirrors applyAliasHop's contract: hits already present are promoted to the* top (score = current-top + epsilon) and stamped; absent hits inject with- * the same top-of-organic + epsilon score shape. Returns a NEW sorted array;- * fail-open returns `results` unchanged.+ * the same top-of-organic + epsilon score shape. Identity rows move to the+ * front; every other row keeps its input order (never re-sorted by `score`,+ * which would discard a reranked order). Returns a NEW array; fail-open+ * returns `results` unchanged.*/export async function applyExactLookupTier(engine: BrainEngine,@@ -218,14 +220,13 @@ export async function applyExactLookupTier(if (hit.title_match_boost) {promoted.title_match_boost = Math.max(promoted.title_match_boost ?? 1.0, hit.title_match_boost);}- // Splice highest-index-first so earlier removals don't shift later ones.- for (let k = matchingIndexes.length - 1; k >= 0; k--) {- if (matchingIndexes[k] !== idx) out.splice(matchingIndexes[k], 1);- }+ // Remove every chunk of the page, then put the promoted one first. No+ // global re-sort: the rest keep their input (reranked) order.+ for (let k = matchingIndexes.length - 1; k >= 0; k--) out.splice(matchingIndexes[k], 1);+ out.unshift(promoted);continue;}- out.push({ ...hit, score: injectScore, base_score: injectScore });+ out.unshift({ ...hit, score: injectScore, base_score: injectScore });}- out.sort((a, b) => b.score - a.score);return out;}diff --git a/src/core/search/hybrid.ts b/src/core/search/hybrid.tsindex 6eb83d83d1..d42a099698 100644--- a/src/core/search/hybrid.ts+++ b/src/core/search/hybrid.ts@@ -48,7 +48,8 @@ import {} from './relational-recall.ts';import { loadConfigWithEngine } from '../config.ts';import { dedupResults } from './dedup.ts';-import { applyReranker, type RerankPassThroughReason, type RerankSkipReason } from './rerank.ts';+import { accumulateRrf } from './rrf-page-fusion.ts';+import { applyReranker, type RerankFailedReason, type RerankPassThroughReason, type RerankSkipReason } from './rerank.ts';import {classifyQuery,classifyQueryWithBrainPatterns,@@ -80,6 +81,7 @@ import {weightsForIntent,effectiveRrfK,applyExactMatchBoost,+ applyAliasMentionBoost,} from './intent-weights.ts';import {SemanticQueryCache,@@ -125,6 +127,26 @@ export function shouldBoostCompiledTruth(detail: string | null | undefined): booreturn detail === 'low';}+/**+ * Compiled-truth tilt for an AUTO-detected `low` (entity intent, never an+ * explicit `detail: 'low'`). Auto intent is a guess from framing words ("who+ * is", "tell me about"), so it must not hide timeline evidence: no SQL+ * filter, and a soft preference instead of the categorical 2x boost.+ */+export const AUTO_LOW_COMPILED_TRUTH_TILT = 1.2;++/**+ * The fusion-boost argument for `rrfFusionWeighted`: `true` (full 2x) only for+ * an explicit `low`, the soft tilt for an auto-detected `low`, `false` otherwise.+ */+export function compiledTruthFusionBoost(+ detail: string | null | undefined,+ explicitDetail: string | null | undefined,+): boolean | number {+ if (!shouldBoostCompiledTruth(detail)) return false;+ return explicitDetail === 'low' ? true : AUTO_LOW_COMPILED_TRUTH_TILT;+}+/*** #3695 — the boost multiplier for one fused row. The title arm COALESCEs a* page with no text chunk into a synthetic row (chunk_id 0 + empty chunk_text,@@ -134,13 +156,13 @@ export function shouldBoostCompiledTruth(detail: string | null | undefined): boo* cosineReScore never runs. Unverified auto-extracted stubs stay excluded* (issue #160, stamped pre-fusion by stampUnverifiedExtractions).*/-export function compiledTruthBoost(result: SearchResult, applyBoost: boolean): number {+export function compiledTruthBoost(result: SearchResult, applyBoost: boolean, boost: number = COMPILED_TRUTH_BOOST): number {const syntheticTitleRow = result.chunk_id === 0 && (result.chunk_text ?? '').trim().length === 0;return applyBoost &&result.chunk_source === 'compiled_truth' &&result.unverified !== true &&!syntheticTitleRow- ? COMPILED_TRUTH_BOOST+ ? boost: 1.0;}const pendingCacheWrites = new Set<Promise<unknown>>();@@ -888,6 +910,9 @@ const MAX_ALIAS_INJECT = 3; // cap injected pages per query (collision* - skip queries longer than MAX_ALIAS_QUERY_TOKENS (clearly prose, not a name).* - bounded: present-boost is 1.10x; inject score is top-of-organic + ε,* never an absolute 1.0 (D3 — aliases are not a ranking sledgehammer).+ * - order-preserving: injected rows go to the front and a boosted row only+ * climbs past lower-scored rows directly above it; every other row keeps+ * its input (reranked) order.* - collisions (two pages claim one alias): deterministic alpha order, capped.** Fail-open: pre-v110 brains (no page_aliases table) and any lookup error@@ -897,7 +922,7 @@ export async function applyAliasHop(engine: import('../engine.ts').BrainEngine,results: SearchResult[],query: string,- opts: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean; requireSafeChunks?: boolean },+ opts: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean; requireSafeChunks?: boolean; excludeSlugs?: string[] },): Promise<SearchResult[]> {if (!query) return results;const qNorm = normalizeAlias(query);@@ -916,6 +941,7 @@ export async function applyAliasHop(// pair so a federated caller boosts/injects the RIGHT source's page, never// collapsing or cross-injecting (P0 source-isolation contract).const ordered = [...refs]+ .filter(ref => !opts.excludeSlugs?.includes(ref.slug)).sort((a, b) => (a.source_id === b.source_id ? a.slug.localeCompare(b.slug) : a.source_id.localeCompare(b.source_id))).slice(0, MAX_ALIAS_INJECT);const out = [...results];@@ -923,10 +949,19 @@ export async function applyAliasHop(let injectScore = topScore > 0 ? topScore : 1.0;for (const ref of ordered) {- const idx = out.findIndex(r => r.slug === ref.slug && (r.source_id ?? 'default') === ref.source_id);+ let idx = out.findIndex(r => r.slug === ref.slug && (r.source_id ?? 'default') === ref.source_id);if (idx >= 0) {- if (Number.isFinite(out[idx].score)) out[idx].score *= ALIAS_HOP_PRESENT_BOOST;- out[idx].alias_hit = true;+ const hit = out[idx];+ if (Number.isFinite(hit.score)) hit.score *= ALIAS_HOP_PRESENT_BOOST;+ hit.alias_hit = true;+ // Bubble the boosted row past lower-scored rows directly above it; never+ // re-sort the list, which would discard a reranked order (post-rerank+ // `score` is still the fusion score, not the rerank order).+ while (idx > 0 && out[idx - 1].score < hit.score) {+ out[idx] = out[idx - 1];+ idx--;+ }+ out[idx] = hit;continue;}// Absent canonical: fetch (in its OWN source) + inject at top-of-organic + epsilon.@@ -945,7 +980,7 @@ export async function applyAliasHop(((page.frontmatter as Record<string, unknown> | null | undefined)?.visibility === 'private')) continue;injectScore += 1e-6;- out.push({+ out.unshift({// #2339-sibling: include page_id. The `as SearchResult` cast hid its// absence, so any consumer reading page_id off an alias-injected result got// undefined — e.g. listActiveTakesForPages bound undefined/NaN into@@ -963,7 +998,6 @@ export async function applyAliasHop(alias_hit: true,} as SearchResult);}- out.sort((a, b) => b.score - a.score);return out;}@@ -1297,9 +1331,12 @@ export async function hybridSearch(// on the first query of a fresh process before the config was applied.const detail = opts?.detail ?? suggestions.suggestedDetail;const detailResolved: 'low' | 'medium' | 'high' | null = detail ?? null;+ const ctBoost = compiledTruthFusionBoost(detail, opts?.detail);const searchOpts: SearchOpts = {limit: innerLimit,- detail,+ // Only an EXPLICIT `low` hard-filters to compiled truth in SQL; an+ // auto-detected one is the soft tilt in `ctBoost`.+ detail: detail === 'low' && opts?.detail !== 'low' ? undefined : detail,// v0.20.0 Cathedral II Layer 10 — thread language + symbolKind through so// per-engine searchKeyword / searchVector apply the filters at SQL level.language: opts?.language,@@ -1308,6 +1345,12 @@ export async function hybridSearch(// type filter to SQL level so the limit budget goes to candidate-typed// pages instead of being eaten by note/transcript/article pages.types: opts?.types,+ // Exact-slug and prefix exclusions are caller contract too (grade-takes+ // passes exclude_slugs; SDK callers pass prefix excludes); dropping them+ // here silently ignored them on every arm.+ exclude_slugs: opts?.exclude_slugs,+ exclude_slug_prefixes: opts?.exclude_slug_prefixes,+ include_slug_prefixes: opts?.include_slug_prefixes,// v0.29.1: since/until take precedence over deprecated afterDate/beforeDate.// The engine still consumes the legacy field names; this aliasing keeps// PR #618 callers compiling while the new names are the public surface.@@ -1568,7 +1611,7 @@ export async function hybridSearch(const noEmbedLists = [{ list: keywordResults, k: fk }];if (titleResults.length > 0) noEmbedLists.push({ list: titleResults, k: fk });if (relationalList.length > 0) noEmbedLists.push({ list: relationalList, k: fk });- noEmbedResults = rrfFusionWeighted(noEmbedLists, shouldBoostCompiledTruth(detailResolved));+ noEmbedResults = rrfFusionWeighted(noEmbedLists, ctBoost);}if (noEmbedResults.length > 0) {await runPostFusionStages(engine, noEmbedResults, postFusionOpts);@@ -1965,7 +2008,7 @@ export async function hybridSearch(const fallbackLists = [{ list: keywordResults, k: fk }];if (titleResults.length > 0) fallbackLists.push({ list: titleResults, k: fk });if (relationalList.length > 0) fallbackLists.push({ list: relationalList, k: fk });- fallbackResults = rrfFusionWeighted(fallbackLists, shouldBoostCompiledTruth(detail));+ fallbackResults = rrfFusionWeighted(fallbackLists, ctBoost);}if (fallbackResults.length > 0) {await runPostFusionStages(engine, fallbackResults, postFusionOpts);@@ -2114,14 +2157,16 @@ export async function hybridSearch(// arms BEFORE fusion so the compiled-truth authority boost skips them.await stampUnverifiedExtractions(engine, allLists.flatMap((l) => l.list), opts);- let fused = rrfFusionWeighted(allLists, shouldBoostCompiledTruth(detail));+ let fused = rrfFusionWeighted(allLists, ctBoost);// Cosine re-scoring before dedup so semantically better chunks survive.// v0.36 (D9): hydrate from the active embedding column so rescore happens// in the same vector space the HNSW just ranked in. Pre-v0.36 this// always pulled from `embedding` and silently corrupted alt-column ranks.if (queryEmbedding) {- fused = await cosineReScore(engine, fused, queryEmbedding, resolvedCol.name);+ // Unified routing embedded the query with the multimodal model, so the+ // rescore must hydrate the multimodal column, not the text column.+ fused = await cosineReScore(engine, fused, queryEmbedding, unifiedDone ? 'embedding_multimodal' : resolvedCol.name);}// Phase E3 (Cat 13): metadata boost gate — decided from the SAME lexical@@ -2146,6 +2191,9 @@ export async function hybridSearch(// No-op when boost factor is 1.0 (general intent or weighting disabled).if (intentWeights.exactMatchBoost !== 1.0) {applyExactMatchBoost(fused, query, intentWeights);+ await applyAliasMentionBoost(fused, query, intentWeights, (aliases) => engine.resolveAliases(aliases, {+ sourceId: opts?.sourceId, sourceIds: opts?.sourceIds, excludePrivate: opts?.excludePrivate,+ }));}fused.sort((a, b) => b.score - a.score);}@@ -2244,6 +2292,7 @@ export async function hybridSearch(? await applyReranker(query, deduped, {...(rerankerOpts as any),onSkip: (reason: RerankSkipReason) => pushDegraded(degraded, 'reranker_skipped', reason),+ onFailure: (reason: RerankFailedReason) => pushDegraded(degraded, 'rerank_failed', reason),onPassThrough: (reason: RerankPassThroughReason) => {pushDegraded(degraded, 'rerank_passthrough', reason);// Chain a per-call callback if the caller supplied one.@@ -2271,6 +2320,7 @@ export async function hybridSearch(sourceIds: opts?.sourceIds,excludePrivate: opts?.excludePrivate,requireSafeChunks: opts?.requireSafeChunks,+ excludeSlugs: opts?.exclude_slugs,});// #1663 — structural exact-lookup tier: a query that IS a page identity@@ -2941,21 +2991,6 @@ export function textVectorArmNonEmpty(arms: readonly VectorArm[]): boolean {return textArmsNonEmpty(arms);}-/**- * RRF/dedup identity for a result row, at chunk granularity.- *- * Includes `source_id` so two same-slug pages in different federated sources- * don't collapse into one fusion entry (the same composite-key discipline- * `dedup.ts:pageKey` already uses at page granularity). Pre-fix the key was- * `slug:chunk_id`, which silently merged cross-source rows and let a- * synthetic chunkless row (chunk_id null) key on a text prefix; the- * `(source_id, slug, chunk_id)` shape is collision-safe for both.- */-function rrfKey(r: SearchResult): string {- const source = r.source_id ?? 'default';- return `${source}:${r.slug}:${r.chunk_id ?? r.chunk_text.slice(0, 50)}`;-}-/*** Canonical query-cache scope key.*@@ -3027,31 +3062,9 @@ export function filterResultsByCallerScope(*/export function rrfFusionWeighted(lists: FusionListEntry[],- applyBoost = true,+ applyBoost: boolean | number = true,): SearchResult[] {- const scores = new Map<string, { result: SearchResult; score: number; keywordHit: boolean }>();-- for (const { list, k, weight } of lists) {- const w = weight ?? 1;- for (let rank = 0; rank < list.length; rank++) {- const r = list[rank];- const key = rrfKey(r);- const existing = scores.get(key);- const rrfScore = w / (k + rank);-- if (existing) {- existing.score += rrfScore;- // #3783 — OR-propagate lexical-arm membership: a row that fusion- // first saw via a vector list must still read keyword_hit when the- // keyword arm ALSO surfaced it.- if (r.keyword_hit === true) existing.keywordHit = true;- } else {- scores.set(key, { result: r, score: rrfScore, keywordHit: r.keyword_hit === true });- }- }- }-- const entries = Array.from(scores.values());+ const entries = accumulateRrf(lists);if (entries.length === 0) return [];const maxScore = Math.max(...entries.map(e => e.score));@@ -3059,14 +3072,16 @@ export function rrfFusionWeighted(for (const e of entries) {e.score = e.score / maxScore;// issue #160 + #3695: unverified stubs and synthetic chunkless title- // rows never get the compiled-truth authority boost.- const boost = compiledTruthBoost(e.result, applyBoost);+ // rows never get the compiled-truth authority boost. Numeric = factor.+ const boost = typeof applyBoost === 'number'+ ? compiledTruthBoost(e.result, true, applyBoost)+ : compiledTruthBoost(e.result, applyBoost);e.score *= boost;}}return entries- .sort((a, b) => b.score - a.score)+ .sort((a, b) => b.score - a.score || b.own - a.own).map(({ result, score, keywordHit }) =>keywordHit && result.keyword_hit !== true? { ...result, score, keyword_hit: true }@@ -3075,7 +3090,8 @@ export function rrfFusionWeighted(/*** Reciprocal Rank Fusion: merge multiple ranked lists.- * Each result gets score = sum(1 / (K + rank)) across all lists it appears in.+ * Each PAGE gets score = sum(1 / (K + rank)) across the lists it appears in+ * (its best rank per list), carried by the page's lead chunk; other chunks keep their own vote.* After accumulation: normalize to 0-1, then boost compiled_truth chunks.*//**@@ -3091,26 +3107,7 @@ export function resolveWalkDedupCap(explicitCap: number | undefined, capFromWalk}export function rrfFusion(lists: SearchResult[][], k: number, applyBoost = true): SearchResult[] {- const scores = new Map<string, { result: SearchResult; score: number; keywordHit: boolean }>();-- for (const list of lists) {- for (let rank = 0; rank < list.length; rank++) {- const r = list[rank];- const key = rrfKey(r);- const existing = scores.get(key);- const rrfScore = 1 / (k + rank);-- if (existing) {- existing.score += rrfScore;- // #3783 — OR-propagate lexical-arm membership across merge order.- if (r.keyword_hit === true) existing.keywordHit = true;- } else {- scores.set(key, { result: r, score: rrfScore, keywordHit: r.keyword_hit === true });- }- }- }-- const entries = Array.from(scores.values());+ const entries = accumulateRrf(lists.map(list => ({ list, k })));if (entries.length === 0) return [];// Normalize to 0-1 by dividing by observed max@@ -3132,9 +3129,9 @@ export function rrfFusion(lists: SearchResult[][], k: number, applyBoost = true)}}- // Sort by boosted score descending+ // Sort by boosted score descending; a page's own-vote leader breaks tiesreturn entries- .sort((a, b) => b.score - a.score)+ .sort((a, b) => b.score - a.score || b.own - a.own).map(({ result, score, keywordHit }) =>keywordHit && result.keyword_hit !== true? { ...result, score, keyword_hit: true }@@ -3204,6 +3201,9 @@ export async function cosineReScore(}export function cosineSimilarity(a: Float32Array, b: Float32Array): number {+ // Vectors from different embedding spaces are incomparable: a length+ // mismatch used to yield a truncated dot product or NaN.+ if (a.length !== b.length) return 0;let dot = 0, magA = 0, magB = 0;for (let i = 0; i < a.length; i++) {dot += a[i] * b[i];diff --git a/src/core/search/intent-weights.ts b/src/core/search/intent-weights.tsindex 4944168fad..2da11aba54 100644--- a/src/core/search/intent-weights.ts+++ b/src/core/search/intent-weights.ts@@ -25,12 +25,14 @@* Intent weighting is the new DEFAULT, and replaces the expansion call* for the common case (simple queries, no API key, fast loop).*- * Pure module. No DB, no LLM, no async. Tested in+ * Pure module. No DB, no LLM. The one async helper (`applyAliasMentionBoost`)+ * takes its alias resolver as a parameter. Tested in* test/intent-weights.test.ts.*/import type { QueryIntent } from './query-intent.ts';import type { SearchResult } from '../types.ts';+import { isTitleMentionedInQuery, tokenizeTitle } from './title-match.ts';/*** Weight adjustments to apply for a classified intent. All factors are@@ -125,8 +127,11 @@ export function effectiveRrfK(baseK: number, weight: number): number {/*** Apply exact-match boost in place. Mutates each result's score by* `weights.exactMatchBoost` when the result's slug or title (lowercased,- * trimmed) matches the lowercased query exactly. No-op when the boost- * is 1.0. Caller re-sorts after.+ * trimmed) matches the lowercased query exactly, OR when the title or the+ * slug's last segment is mentioned inside the query as a token run+ * (`isTitleMentionedInQuery`: "who is Alice Example" → "Alice Example").+ * Entity intent is defined by framing words, so without the mention form the+ * boost could never fire. No-op when the boost is 1.0. Caller re-sorts after.** Normalization: slug is matched as-is (slugs are already canonicalized* lowercase-kebab); title is lowercased + trimmed. The query is@@ -145,7 +150,9 @@ export function applyExactMatchBoost(for (const r of results) {const slug = (r.slug ?? '').toLowerCase();const title = (r.title ?? '').toLowerCase().trim();- if (slug === q || slug === qKebab || slug.endsWith(`/${qKebab}`) || title === q) {+ const exact = slug === q || slug === qKebab || slug.endsWith(`/${qKebab}`) || title === q;+ const mentioned = isTitleMentionedInQuery(q, title) || isTitleMentionedInQuery(q, slug.slice(slug.lastIndexOf('/') + 1));+ if (exact || mentioned) {r.score *= weights.exactMatchBoost;// v0.40.4 attribution stamp (D12=A) — formatter reads this for// --explain output. Only stamped when boost actually fires.@@ -153,3 +160,55 @@ export function applyExactMatchBoost(}}}++/** Longest alias n-gram looked up for a query mention (tokens). */+const MAX_ALIAS_MENTION_TOKENS = 5;++/**+ * Query n-grams (1..MAX_ALIAS_MENTION_TOKENS tokens, normalized like+ * `page_aliases` rows) that could be a declared alias mentioned in the query.+ * Single tokens need at least 4 characters so "who"/"is" never probe.+ */+export function aliasMentionCandidates(query: string): string[] {+ const tokens = tokenizeTitle(query);+ const out = new Set<string>();+ for (let n = 1; n <= MAX_ALIAS_MENTION_TOKENS; n++) {+ for (let i = 0; i + n <= tokens.length; i++) {+ if (n === 1 && tokens[i].length < 4) continue;+ out.add(tokens.slice(i, i + n).join(' '));+ }+ }+ return [...out];+}++/**+ * Alias half of the mention boost: a result whose page declares an alias that+ * occurs inside the query gets the same `exactMatchBoost` (once — a row the+ * title/slug path already boosted is skipped). Present rows only; injection+ * stays the alias hop's job. Fail-open: a resolver error changes nothing.+ */+export async function applyAliasMentionBoost(+ results: SearchResult[],+ query: string,+ weights: IntentWeights,+ resolveAliases: (aliasNorms: string[]) => Promise<Map<string, Array<{ slug: string; source_id: string }>>>,+): Promise<void> {+ if (weights.exactMatchBoost === 1.0 || results.length === 0) return;+ const candidates = aliasMentionCandidates(query);+ if (candidates.length === 0) return;+ let refs: Map<string, Array<{ slug: string; source_id: string }>>;+ try {+ refs = await resolveAliases(candidates);+ } catch {+ return;+ }+ const pages = new Set<string>();+ for (const list of refs.values()) for (const ref of list) pages.add(`${ref.source_id}:${ref.slug}`);+ if (pages.size === 0) return;+ for (const r of results) {+ if (r.exact_match_boost !== undefined) continue;+ if (!pages.has(`${r.source_id ?? 'default'}:${r.slug}`)) continue;+ r.score *= weights.exactMatchBoost;+ r.exact_match_boost = weights.exactMatchBoost;+ }+}diff --git a/src/core/search/read-enrichment.ts b/src/core/search/read-enrichment.tsindex 2ab2812937..7c21bdf0d9 100644--- a/src/core/search/read-enrichment.ts+++ b/src/core/search/read-enrichment.ts@@ -81,9 +81,14 @@ export async function readBacklinkCounts(query: ReadQuery, ids: number[], scope?const target = pageReadFilter('p', scope, params, !!scope);const contributor = pageReadFilter('contributor', scope, params, true);const origin = originFilter(scope, params);+ // Distinct linking pages, not link rows: duplicate edges (several link+ // types between one pair) and self-links would inflate the boost+ // (adjacency's COUNT(DISTINCT) shape). A policy additionally requires live,+ // authorized contributors; the trusted unscoped call counts every page.const rows = await query<{ page_id: number; cnt: number }>(`- SELECT p.id AS page_id, COUNT(l.id)::int AS cnt+ SELECT p.id AS page_id, COUNT(DISTINCT l.from_page_id)::int AS cntFROM pages p LEFT JOIN links l ON l.to_page_id = p.id+ AND l.from_page_id <> p.idAND l.link_source IS DISTINCT FROM 'mentions'${scope ? `AND EXISTS (SELECT 1 FROM pages contributor WHERE contributor.id = l.from_page_id AND ${contributor}) AND ${origin}` : ''}WHERE p.id = ANY($1::int[]) AND ${target} GROUP BY p.id`, params);diff --git a/src/core/search/rerank.ts b/src/core/search/rerank.tsindex 0d78848e0b..f53a1e7959 100644--- a/src/core/search/rerank.ts+++ b/src/core/search/rerank.ts@@ -36,11 +36,20 @@ export interface RerankerOpts {rerankerFn?: (input: RerankInput) => Promise<RerankResult[]>;onSkip?: (reason: RerankSkipReason) => void;+ /**+ * Fired when the reranker call failed hard (HTTP error, timeout, budget,+ * network, …) and the results passed through in RRF order. hybridSearch+ * stamps it as the `rerank_failed` degraded stage. Best-effort.+ */+ onFailure?: (reason: RerankFailedReason) => void;}/** The two skip classes (no HTTP call, no per-query audit row). */export type RerankSkipReason = 'no_key';+/** A reranker call that threw (anything but a missing key), as stamped on the wire. */+export type RerankFailedReason = 'timeout' | 'budget' | 'provider_error';+/** SHA-256 prefix (8 chars) of the query text for privacy-preserving audit. */function hashQuery(query: string): string {return createHash('sha256').update(query, 'utf8').digest('hex').slice(0, 8);@@ -149,6 +158,8 @@ export async function applyReranker(} catch {// Audit logging must never break search.}+ const failed: RerankFailedReason = reason === 'timeout' || reason === 'budget' ? reason : 'provider_error';+ try { opts.onFailure?.(failed); } catch { /* caller hook must never break search */ }return results;}diff --git a/src/core/search/rrf-page-fusion.ts b/src/core/search/rrf-page-fusion.tsnew file mode 100644index 0000000000..b004ea0733--- /dev/null+++ b/src/core/search/rrf-page-fusion.ts@@ -0,0 +1,85 @@+/**+ * Page-grain RRF accumulation shared by `rrfFusion` and `rrfFusionWeighted`+ * (hybrid.ts). Pure: no engine, no I/O.+ */++import type { SearchResult } from '../types.ts';++/**+ * RRF/dedup identity for a result row, at chunk granularity.+ *+ * Includes `source_id` so two same-slug pages in different federated sources+ * don't collapse into one fusion entry (the same composite-key discipline+ * `dedup.ts:pageKey` already uses at page granularity). Pre-fix the key was+ * `slug:chunk_id`, which silently merged cross-source rows and let a+ * synthetic chunkless row (chunk_id null) key on a text prefix; the+ * `(source_id, slug, chunk_id)` shape is collision-safe for both.+ */+function rrfKey(r: SearchResult): string {+ const source = r.source_id ?? 'default';+ return `${source}:${r.slug}:${r.chunk_id ?? r.chunk_text.slice(0, 50)}`;+}++/**+ * RRF vote identity: the page, `(source_id, slug)`. Every arm is page-grain+ * (best chunk per page) but each arm picks its OWN representative chunk, so+ * voting on the chunk key split one page's cross-arm agreement across+ * several fusion entries (a page ranked #1 by keyword and by vector lost to+ * a page ranked #2 by both). Votes sum per page — each list counts a page+ * once, at its best rank — and the page's LEAD chunk (largest own vote; ties+ * go to the first list that surfaced it, which is a vector arm in+ * `composeFusionLists` order, i.e. the page's best-cosine chunk) carries the+ * page's summed score. The page's other chunks keep their own votes, so a+ * page's second chunk never crowds out another page's lead in a chunk-limited+ * result (giving every chunk the page score cost multi-session recall).+ */+function rrfPageKey(r: SearchResult): string {+ return `${r.source_id ?? 'default'}:${r.slug}`;+}++export type RrfEntry = { result: SearchResult; score: number; own: number; keywordHit: boolean };++/**+ * Shared accumulation for both RRF fusers: chunk entries (identity and+ * keyword-hit OR-propagation) plus page vote totals. Returns chunk entries in+ * first-seen order; each page's lead scores the page total, the rest their+ * own vote.+ */+export function accumulateRrf(lists: ReadonlyArray<{ list: SearchResult[]; k: number; weight?: number }>): RrfEntry[] {+ const chunks = new Map<string, RrfEntry>();+ const pages = new Map<string, number>();+ for (const { list, k, weight } of lists) {+ const w = weight ?? 1;+ const votedPages = new Set<string>();+ for (let rank = 0; rank < list.length; rank++) {+ const r = list[rank];+ const rrfScore = w / (k + rank);+ const page = rrfPageKey(r);+ if (!votedPages.has(page)) {+ votedPages.add(page);+ pages.set(page, (pages.get(page) ?? 0) + rrfScore);+ }+ const key = rrfKey(r);+ const existing = chunks.get(key);+ if (existing) {+ existing.own += rrfScore;+ // #3783 — OR-propagate lexical-arm membership: a row that fusion+ // first saw via a vector list must still read keyword_hit when the+ // keyword arm ALSO surfaced it.+ if (r.keyword_hit === true) existing.keywordHit = true;+ } else {+ chunks.set(key, { result: r, score: 0, own: rrfScore, keywordHit: r.keyword_hit === true });+ }+ }+ }+ const entries = Array.from(chunks.values());+ const leads = new Map<string, RrfEntry>();+ for (const e of entries) {+ e.score = e.own;+ const page = rrfPageKey(e.result);+ const lead = leads.get(page);+ if (!lead || e.own > lead.own) leads.set(page, e);+ }+ for (const [page, lead] of leads) lead.score = pages.get(page) ?? lead.own;+ return entries;+}diff --git a/src/core/search/title-match.ts b/src/core/search/title-match.tsindex 00802fb841..ad57fc005f 100644--- a/src/core/search/title-match.ts+++ b/src/core/search/title-match.ts@@ -89,5 +89,26 @@ export function isTitlePhraseMatch(query: string, title: string): boolean {return containsTokenRun(tTokens, qTokens);}+/** A one-content-token title must be at least this long to count as mentioned. */+const MIN_SINGLE_TOKEN_TITLE_CHARS = 4;++/**+ * The reverse direction of `isTitlePhraseMatch`: is `title` mentioned INSIDE+ * `query` as a contiguous token run? "who is Alice Example" mentions the page+ * "Alice Example"; framed entity questions never equal a title, so the+ * exact-match boost needs this to fire at all. Guarded against generic titles:+ * the title needs >= MIN_CONTENT_TOKENS content tokens, or one content token of+ * at least MIN_SINGLE_TOKEN_TITLE_CHARS characters.+ */+export function isTitleMentionedInQuery(query: string, title: string): boolean {+ const qTokens = tokenizeTitle(query);+ const tTokens = tokenizeTitle(title);+ if (tTokens.length === 0 || tTokens.length > qTokens.length) return false;+ const tContent = contentTokens(tTokens);+ if (tContent.length === 0) return false;+ if (tContent.length < MIN_CONTENT_TOKENS && tContent[0].length < MIN_SINGLE_TOKEN_TITLE_CHARS) return false;+ return containsTokenRun(qTokens, tTokens);+}+// Exported for unit tests.export const __test__ = { tokenizeTitle, contentTokens, containsTokenRun, STOPWORDS, MIN_CONTENT_TOKENS };diff --git a/src/core/types.ts b/src/core/types.tsindex 6ba21247cc..bc31ffb89b 100644--- a/src/core/types.ts+++ b/src/core/types.ts@@ -1843,6 +1843,7 @@ export const DEGRADED_STAGES = ['cache_prestamp','reranker_skipped','rerank_passthrough',+ 'rerank_failed','keyword_relaxed_carried','safe_index_pending','vector_candidates_incomplete',@@ -1868,6 +1869,7 @@ export const DEGRADED_REASONS = [// #4648 — rerank_passthrough reasons (mirror RerankPassThroughReason).'empty_result_set','malformed_shape',+ 'budget','candidate_budget','iterative_scan_unavailable',] as const;@@ -1892,6 +1894,7 @@ export interface DegradedStageEntry {* short degraded TTL lets the next query recover a reranked result set* (master's v0.48.1.0 behavior, kept at the merge). It never reaches the* empty-result copy because a pass-through implies a non-empty batch.+ * - `rerank_failed` (the call threw: timeout / provider_error / budget) is transient too.* - `keyword_relaxed_carried` is recall-shaped by definition (see above).* Pinned by test/degraded-stages-recall.test.ts; a new fail-open stage must be* classified here in the same commit that adds it.diff --git a/src/eval/longmemeval/adapter.ts b/src/eval/longmemeval/adapter.tsindex 75c3c4352b..4d9ff2c354 100644--- a/src/eval/longmemeval/adapter.ts+++ b/src/eval/longmemeval/adapter.ts@@ -11,8 +11,16 @@* out of scope for v0.28.1. The chat/ slug prefix is verified by* test/eval-longmemeval.test.ts to NOT prefix-match any DEFAULT_SOURCE_BOOSTS* entry, so retrieval factor stays at 1.0.+ *+ * Session identity is OPAQUE everywhere the system or the reader can see it.+ * The dataset's gold session ids all start with `answer_` (and no distractor+ * does), so a raw id in a slug, title, frontmatter or reader prompt is a gold+ * label. `sessionSlug` hashes the id per question; scoring recovers the raw id+ * through `buildSlugToRawMap` (metrics.ts), which is never shown to the system.*/+import { createHash } from 'node:crypto';+export interface LongMemEvalTurn {role: 'user' | 'assistant';content: string;@@ -58,10 +66,10 @@ export interface PageInputForImport {* naturally on either role's text. Frontmatter pins type, date (if available),* and session_id so the JSONL emit step can recover session_id from a chunk.*/-function renderSession(session: LongMemEvalSession, date?: string): string {+function renderSession(opaqueId: string, session: LongMemEvalSession, date?: string): string {const fm: string[] = ['---', 'type: note'];if (date) fm.push(`date: ${date}`);- fm.push(`session_id: ${session.session_id}`);+ fm.push(`session_id: ${opaqueId}`);fm.push('---', '');const body: string[] = [];@@ -123,6 +131,23 @@ export function sanitizeSessionIdForSlug(sessionId: string): string {return sessionId.toLowerCase().replace(/[_.]/g, '-').replace(/[^a-z0-9-]/g, '-');}+/**+ * Opaque per-question session id: `s-` + the first 10 hex chars of+ * sha256(`question_id:normalized session id`). Hashing the NORMALIZED id keeps+ * the collision contract of the pre-opaque slugs (`a_b` and `a-b` still share+ * one page, which `collisionsTouchingGold` reports) while carrying no trace of+ * the raw id, so the `answer_` gold prefix never reaches retrieval or the reader.+ */+export function opaqueSessionId(questionId: string, sessionId: string): string {+ const digest = createHash('sha256').update(`${questionId}:${sanitizeSessionIdForSlug(sessionId)}`).digest('hex');+ return `s-${digest.slice(0, 10)}`;+}++/** The page slug a haystack session imports as. The ONE slug constructor. */+export function sessionSlug(questionId: string, sessionId: string): string {+ return `chat/${opaqueSessionId(questionId, sessionId)}`;+}+export function haystackToPages(question: LongMemEvalQuestion): PageInputForImport[] {const pages: PageInputForImport[] = [];const dates = question.haystack_dates ?? [];@@ -131,8 +156,8 @@ export function haystackToPages(question: LongMemEvalQuestion): PageInputForImpoconst session = sessions[i];const date = dates[i];pages.push({- slug: `chat/${sanitizeSessionIdForSlug(session.session_id)}`,- content: renderSession(session, date),+ slug: sessionSlug(question.question_id, session.session_id),+ content: renderSession(opaqueSessionId(question.question_id, session.session_id), session, date),});}return pages;diff --git a/src/eval/longmemeval/metrics.ts b/src/eval/longmemeval/metrics.tsindex 86294f71b7..69d64e8929 100644--- a/src/eval/longmemeval/metrics.ts+++ b/src/eval/longmemeval/metrics.ts@@ -7,12 +7,12 @@* deterministic transform over search rows + dataset fields, so the harness* (src/commands/eval-longmemeval.ts) and the tests score the same bytes.*- * INVARIANT: the join is on RAW session ids. `haystackToPages` lowercases and- * hyphenates ids to build slugs (`sharegpt_yywfIrx_0` -> `chat/sharegpt-yywfirx-0`),- * so a slug-tail compared against `answer_session_ids` never matches on the- * public _s split. `buildSlugToRawMap` inverts the slug construction per- * question and `distinctRetrievedSessions` joins through it; `normalizeSessionId`- * exists only for slug construction / fallback, never for the gold compare.+ * INVARIANT: the join is on RAW session ids. `haystackToPages` builds OPAQUE+ * slugs (`chat/s-<10 hex>`, adapter.ts `sessionSlug`) so no gold label reaches+ * the system, so a slug-tail never matches `answer_session_ids`.+ * `buildSlugToRawMap` is the private per-question inverse and+ * `distinctRetrievedSessions` joins through it; `normalizeSessionId` exists+ * only for legacy-row rawification, never for the gold compare.** INVARIANT: k semantics. `recall_*@k` is scored over the DISTINCT sessions* among the top-k CHUNK rows returned at `limit: k` (the receipt's@@ -24,6 +24,7 @@ import type { SearchResult } from '../../core/types.ts';import {normalizeSessions,sanitizeSessionIdForSlug,+ sessionSlug,type LongMemEvalQuestion,} from './adapter.ts';@@ -40,8 +41,8 @@ export const normalizeSessionId: (sessionId: string) => string = sanitizeSession/*** Slug tail after `chat/`. Falls back to the tail after the first `/`, then to* the slug itself, so a non-`chat/` slug still yields a stable id. Returns the- * NORMALIZED id (lowercase, hyphenated); use `distinctRetrievedSessions` with a- * `SlugToRawMap` to recover the raw dataset id.+ * OPAQUE id the system and the reader see; use `distinctRetrievedSessions` with+ * a `SlugToRawMap` to recover the raw dataset id.*/export function sessionIdFromSlug(slug: string): string {if (slug.startsWith(SESSION_SLUG_PREFIX)) return slug.slice(SESSION_SLUG_PREFIX.length);@@ -54,7 +55,7 @@ export function isAbstentionQuestion(questionId: string): boolean {return /_abs$/.test(questionId);}-/** `chat/<normalized>` slug -> the raw session id(s) that produced it (haystack order, deduped). */+/** `chat/<opaque>` slug -> the raw session id(s) that produced it (haystack order, deduped). */export type SlugToRawMap = Map<string, string[]>;/**@@ -67,7 +68,7 @@ export type SlugToRawMap = Map<string, string[]>;export function buildSlugToRawMap(question: LongMemEvalQuestion): SlugToRawMap {const map: SlugToRawMap = new Map();for (const session of normalizeSessions(question)) {- const slug = `${SESSION_SLUG_PREFIX}${normalizeSessionId(session.session_id)}`;+ const slug = sessionSlug(question.question_id, session.session_id);const list = map.get(slug);if (!list) map.set(slug, [session.session_id]);else if (!list.includes(session.session_id)) list.push(session.session_id);diff --git a/src/eval/longmemeval/reader.ts b/src/eval/longmemeval/reader.tsindex 00d03d9f50..343fb5ca6c 100644--- a/src/eval/longmemeval/reader.ts+++ b/src/eval/longmemeval/reader.ts@@ -27,7 +27,7 @@import type { ThinkLLMClient } from '../../core/think/index.ts';import type { SearchResult } from '../../core/types.ts';import { renderChatBlock, type ChatSessionForPrompt } from './sanitize.ts';-import { rawSessionId, type SlugToRawMap } from './metrics.ts';+import { rawSessionId, sessionIdFromSlug, type SlugToRawMap } from './metrics.ts';import { sha256Hex, stableStringify } from './run-config.ts';/** Re-exported for existing importers; the definition lives in metrics.ts (the SlugToRawMap owner). */@@ -149,7 +149,7 @@ export async function generateAnswer(question: { question: string; question_date?: string },results: readonly SearchResult[],pages: ReadonlyArray<{ slug: string; content: string; date?: string }>,- slugToRaw: SlugToRawMap,+ _slugToRaw: SlugToRawMap,model: string,trajectoryBlock: string = '',config: ReaderConfig = resolveReaderConfig(),@@ -163,7 +163,7 @@ export async function generateAnswer(seenSlugs.add(r.slug);const entry = byId.get(r.slug);sessions.push({- session_id: rawSessionId(r.slug, slugToRaw),+ session_id: sessionIdFromSlug(r.slug),date: entry?.date,body: entry?.body ?? r.chunk_text,});diff --git a/src/eval/longmemeval/resume.ts b/src/eval/longmemeval/resume.tsindex 2c5574eb71..a328af2bee 100644--- a/src/eval/longmemeval/resume.ts+++ b/src/eval/longmemeval/resume.ts@@ -318,7 +318,7 @@ export interface RowSearchMeta {const VECTOR_DEGRADED_STAGES: ReadonlySet<string> = new Set(['embed_unavailable', 'embed_timeout']);const EXPANSION_FAILED_STAGES: ReadonlySet<string> = new Set(['expansion_failed', 'expansion_partial']);-const RERANKER_SKIPPED_STAGES: ReadonlySet<string> = new Set(['reranker_skipped', 'rerank_passthrough']);+const RERANKER_SKIPPED_STAGES: ReadonlySet<string> = new Set(['reranker_skipped', 'rerank_passthrough', 'rerank_failed']);/*** Silent-degradation classifier shared by the live row and the resumediff --git a/src/eval/retrieval-quality/harness.ts b/src/eval/retrieval-quality/harness.tsindex b45d3557d0..4d4c41dc39 100644--- a/src/eval/retrieval-quality/harness.ts+++ b/src/eval/retrieval-quality/harness.ts@@ -63,6 +63,9 @@ export interface QuestionResult {/** v0.43 — fraction of relevant slugs found in top-10. The relational* headline metric (a relationship query often has several valid answers). */recall_at_10: number;+ /** The search call threw. Scored as a miss in every family (never as a+ * clean hard-negative) and counted in the report + gate. */+ errored?: true;}export interface FamilyReport {@@ -74,12 +77,16 @@ export interface FamilyReport {/** v0.43 — mean recall@K / recall@10 across the family's questions. */recall_at_k: number;recall_at_10: number;+ /** Questions in this family whose search call threw. */+ errored: number;}export interface RetrievalQualityReport {schema_version: 1;k: number;total: number;+ /** Questions whose search call threw (all families). Any error fails the gate. */+ errored: number;families: FamilyReport[];questions: QuestionResult[];}@@ -114,8 +121,18 @@ export async function runRetrievalQuality(): Promise<RetrievalQualityReport> {const results: QuestionResult[] = [];for (const q of questions) {- let ranked: string[] = [];- try { ranked = await searchFn(q.query); } catch { ranked = []; }+ let ranked: string[];+ try {+ ranked = await searchFn(q.query);+ } catch {+ // An empty list would score a hard-negative as clean (hit@1, RR=1).+ results.push({+ family: q.family, query: q.query, hit_at_1: false, hit_at_3: false, reciprocal_rank: 0,+ ...(q.family === 'hard-negative' ? { negative_clean: false } : {}),+ recall_at_k: 0, recall_at_10: 0, errored: true,+ });+ continue;+ }results.push(scoreQuestion(q, ranked));}const byFamily = new Map<Family, QuestionResult[]>();@@ -135,10 +152,15 @@ export async function runRetrievalQuality(mrr: n ? list.reduce((s, r) => s + r.reciprocal_rank, 0) / n : 0,recall_at_k: n ? list.reduce((s, r) => s + r.recall_at_k, 0) / n : 0,recall_at_10: n ? list.reduce((s, r) => s + r.recall_at_10, 0) / n : 0,+ errored: list.filter(r => r.errored).length,});}families.sort((a, b) => a.family.localeCompare(b.family));- return { schema_version: 1, k: K, total: results.length, families, questions: results };+ return {+ schema_version: 1, k: K, total: results.length,+ errored: results.filter(r => r.errored).length,+ families, questions: results,+ };}// ── Gate ────────────────────────────────────────────────────────────────@@ -175,7 +197,7 @@ function floorEnv(name: string, dflt: number): number {}export interface GateBreach { family: Family; metric: 'hit_at_1' | 'hit_at_3'; got: number; floor: number; }-export interface GateResult { pass: boolean; breaches: GateBreach[]; warnings: GateBreach[]; }+export interface GateResult { pass: boolean; breaches: GateBreach[]; warnings: GateBreach[]; errored: number; }export function evaluateGate(report: RetrievalQualityReport, opts: GateOpts = DEFAULT_GATE): GateResult {const byFamily = new Map(report.families.map(f => [f.family, f]));@@ -198,7 +220,8 @@ export function evaluateGate(report: RetrievalQualityReport, opts: GateOpts = DEwarnings.push({ family, metric: 'hit_at_3', got: fr.hit_at_3, floor: 0.8 });}}- return { pass: breaches.length === 0, breaches, warnings };+ // A search error is not a measurement: any errored question fails the gate.+ return { pass: breaches.length === 0 && report.errored === 0, breaches, warnings, errored: report.errored };}export function parseQuestionsJsonl(text: string): NamedThingQuestion[] {diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.mdindex b8c4b36fb7..82347903c3 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.59.11.0 -->+<!-- gbrain-template-stamp: 0.59.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/backlink-count-mention-filter.test.ts b/test/backlink-count-mention-filter.test.tsindex 042c662f0f..773e072275 100644--- a/test/backlink-count-mention-filter.test.ts+++ b/test/backlink-count-mention-filter.test.ts@@ -212,3 +212,24 @@ describe('getBacklinkCounts — #4380 page-id keying (multi-source namesakes)',expect(counts.get(pageB.id)).toBe(0);});});++describe('getBacklinkCounts counts distinct linking pages (read-path audit #18)', () => {+ test('duplicate edges and self-links do not inflate the count; a policy also drops soft-deleted contributors', async () => {+ const targetId = await seedTarget('people/dana');+ await seedSource('writing/one', 1);+ await seedSource('writing/two', 2);+ await seedSource('writing/gone', 3);+ await engine.addLinksBatch([+ { from_slug: 'writing/one', to_slug: 'people/dana', link_type: 'mentions', link_source: 'markdown', context: '' },+ { from_slug: 'writing/one', to_slug: 'people/dana', link_type: 'works_with', link_source: 'markdown', context: '' },+ { from_slug: 'writing/two', to_slug: 'people/dana', link_type: 'mentions', link_source: 'markdown', context: '' },+ { from_slug: 'writing/gone', to_slug: 'people/dana', link_type: 'mentions', link_source: 'markdown', context: '' },+ { from_slug: 'people/dana', to_slug: 'people/dana', link_type: 'mentions', link_source: 'markdown', context: '' },+ ]);+ await engine.executeRaw(`UPDATE pages SET deleted_at = now() WHERE slug = 'writing/gone'`);+ // Trusted unscoped call: distinct live-or-not linking pages, no self-link.+ expect((await engine.getBacklinkCounts([targetId])).get(targetId)).toBe(3);+ // A read policy additionally requires live contributors.+ expect((await engine.getBacklinkCounts([targetId], { sourceId: 'default' })).get(targetId)).toBe(2);+ });+});diff --git a/test/dedup.test.ts b/test/dedup.test.tsindex 23714fbf96..492a1fd178 100644--- a/test/dedup.test.ts+++ b/test/dedup.test.ts@@ -273,3 +273,17 @@ describe('dedup — source-aware composite key (v0.18.0)', () => {expect(wikiCompiledTruths[0].chunk_id).toBe(2); // wiki's own compiled_truth, NOT gstack's (id=3)});});++describe('compiled truth guarantee keeps evidence and score order (read-path audit #11)', () => {+ test('appends the compiled_truth chunk instead of evicting a matching chunk, output stays score-sorted', () => {+ const results = [+ makeResult({ slug: 'a', chunk_id: 1, score: 0.95, chunk_source: 'timeline', chunk_text: 'alpha timeline first match text' }),+ makeResult({ slug: 'a', chunk_id: 2, score: 0.90, chunk_source: 'timeline', chunk_text: 'second different timeline evidence words' }),+ makeResult({ slug: 'b', chunk_id: 3, score: 0.80, chunk_source: 'compiled_truth', chunk_text: 'page b compiled truth summary' }),+ makeResult({ slug: 'a', chunk_id: 4, score: 0.10, chunk_source: 'compiled_truth', chunk_text: 'page a compiled truth summary' }),+ ];+ const out = dedupResults(results);+ expect(out.map(r => r.chunk_id)).toEqual([1, 2, 3, 4]);+ for (let i = 1; i < out.length; i++) expect(out[i - 1].score).toBeGreaterThanOrEqual(out[i].score);+ });+});diff --git a/test/e2e/engine-parity.test.ts b/test/e2e/engine-parity.test.tsindex 440a0a8d12..c209694e9d 100644--- a/test/e2e/engine-parity.test.ts+++ b/test/e2e/engine-parity.test.ts@@ -149,6 +149,57 @@ describeBoth('Engine parity — Postgres vs PGLite', () => {});}+ test('searchKeyword honors exclude_slugs and type identically on BOTH engines (read-path audit #8)', async () => {+ const q = 'fat code thin harness';+ const pgAll = (await pgEngine.searchKeyword(q, { limit: 10 })).map((r: SearchResult) => r.slug);+ expect(pgAll).toContain('concepts/fat-code-thin-harness');+ const opts = { limit: 10, exclude_slugs: ['concepts/fat-code-thin-harness'] };+ const pgEx = (await pgEngine.searchKeyword(q, opts)).map((r: SearchResult) => r.slug);+ const pgliteEx = (await pgliteEngine.searchKeyword(q, opts)).map((r: SearchResult) => r.slug);+ expect(pgEx).not.toContain('concepts/fat-code-thin-harness');+ expect(new Set(pgliteEx)).toEqual(new Set(pgEx));+ const typed = { limit: 10, type: 'concept' as const };+ const pgTyped = (await pgEngine.searchKeyword(q, typed)).map((r: SearchResult) => r.type);+ const pgliteTyped = (await pgliteEngine.searchKeyword(q, typed)).map((r: SearchResult) => r.type);+ expect(pgTyped.length).toBeGreaterThan(0);+ expect(pgTyped.every(t => t === 'concept')).toBe(true);+ expect(pgliteTyped).toEqual(pgTyped);+ });++ test('findTrajectory keeps the NEWEST points under a limit on BOTH engines (read-path audit #4)', async () => {+ for (const eng of [pgEngine, pgliteEngine] as BrainEngine[]) {+ await eng.executeRaw(`DELETE FROM facts WHERE entity_slug = 'people/traj-parity'`);+ for (let i = 0; i < 6; i++) {+ await eng.executeRaw(+ `INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, valid_from, source, claim_metric, claim_value)+ VALUES ('default', 'people/traj-parity', $1, 'fact', 'world', $2::timestamptz, 'test', 'mrr', $3)`,+ [`mrr is ${i}`, new Date(Date.UTC(2024, 0, 1 + i)).toISOString(), i],+ );+ }+ }+ const opts = { entitySlug: 'people/traj-parity', remote: false, limit: 3 };+ const pg = (await pgEngine.findTrajectory(opts)).map(p => p.value);+ const pglite = (await pgliteEngine.findTrajectory(opts)).map(p => p.value);+ expect(pg).toEqual([3, 4, 5]);+ expect(pglite).toEqual(pg);+ });++ test('getTags excludePrivate / liveOnly behave identically on BOTH engines (read-path audit #19)', async () => {+ for (const eng of [pgEngine, pgliteEngine] as BrainEngine[]) {+ await eng.putPage('notes/tag-private', { type: 'note', title: 'P', compiled_truth: 'x', frontmatter: { visibility: 'private' } } as any);+ await eng.putPage('notes/tag-gone', { type: 'note', title: 'G', compiled_truth: 'x' } as any);+ await eng.addTag('notes/tag-private', 'p-tag');+ await eng.addTag('notes/tag-gone', 'g-tag');+ await eng.executeRaw(`UPDATE pages SET deleted_at = now() WHERE slug = 'notes/tag-gone'`);+ }+ for (const eng of [pgEngine, pgliteEngine] as BrainEngine[]) {+ expect(await eng.getTags('notes/tag-private')).toEqual(['p-tag']);+ expect(await eng.getTags('notes/tag-private', { excludePrivate: true })).toEqual([]);+ expect(await eng.getTags('notes/tag-gone')).toEqual(['g-tag']);+ expect(await eng.getTags('notes/tag-gone', { liveOnly: true })).toEqual([]);+ }+ });+test('searchKeyword orFallback: relaxed rows tagged keyword_relaxed on BOTH engines (2026-09 #3617 follow-up)', async () => {// A query whose terms never co-occur in one chunk: zero strict recall,// non-empty OR recall. Both engines must return the SAME tagged shape —diff --git a/test/engine-find-trajectory.test.ts b/test/engine-find-trajectory.test.tsindex 58fc8a79d9..931b663739 100644--- a/test/engine-find-trajectory.test.ts+++ b/test/engine-find-trajectory.test.ts@@ -115,6 +115,28 @@ describe('findTrajectory — chronological ordering (R3)', () => {});});+describe('findTrajectory — a capped series keeps its NEWEST points (read-path audit #4)', () => {+ test('limit returns the newest N, still chronological, so the latest value is current', async () => {+ const day0 = Date.UTC(2024, 0, 1);+ for (let i = 0; i < 150; i++) {+ await insertTyped({ entity_slug: 'traj-cap', metric: 'mrr', value: i, valid_from: new Date(day0 + i * 86_400_000) });+ }+ const points = await engine.findTrajectory({ entitySlug: 'traj-cap', remote: false, limit: 100 });+ expect(points.length).toBe(100);+ expect(points[points.length - 1].value).toBe(149);+ expect(points[0].value).toBe(50);+ expect(points.map(p => p.value)).toEqual(Array.from({ length: 100 }, (_, i) => i + 50));+ });++ test('same-day ties break on id, newest id last', async () => {+ const d = new Date('2026-03-01');+ const ids = [];+ for (let i = 0; i < 3; i++) ids.push(await insertTyped({ entity_slug: 'traj-tie', metric: 'mrr', value: i, valid_from: d }));+ const points = await engine.findTrajectory({ entitySlug: 'traj-tie', remote: false, limit: 2 });+ expect(points.map(p => p.fact_id)).toEqual([ids[1], ids[2]]);+ });+});+describe('findTrajectory — source scoping (D-CDX-6)', () => {test('scalar sourceId returns only that source', async () => {await insertTyped({ source_id: 'traj-src-A', entity_slug: 'traj-srcscope', metric: 'mrr', value: 50000, valid_from: new Date('2026-01-15') });diff --git a/test/eval-longmemeval-mixedcase.slow.test.ts b/test/eval-longmemeval-mixedcase.slow.test.tsindex d140f1df22..be5ae8cd24 100644--- a/test/eval-longmemeval-mixedcase.slow.test.ts+++ b/test/eval-longmemeval-mixedcase.slow.test.ts@@ -2,8 +2,8 @@* Ranker wave Phase 0 — the like-for-like LongMemEval harness, pinned on the* mixed-case `_s`-shaped fixture (test/fixtures/longmemeval-mixedcase.jsonl):*- * - raw-id join: `sharegpt_yywfIrx_0`-style gold ids match the slug-tail- * `chat/sharegpt-yywfirx-0` through the per-question slug→raw map (pre-fix+ * - raw-id join: `sharegpt_yywfIrx_0`-style gold ids match the opaque slug+ * `chat/s-<10 hex>` through the per-question slug→raw map (pre-fix* every recall_hit on the public split was false);* - strict vs lenient: mc-2 has two gold sessions and keyword hits only one* → recall_all_hit=false, recall_any_hit=true;@@ -43,6 +43,7 @@ import { redactSecrets, retrievalConfigHash, type KnobsFingerprint, type Retrievimport { makeStubClient } from './helpers/longmemeval-stub.ts';import type { ThinkLLMClient } from '../src/core/think/index.ts';import { checkResumeConfigHash, retrievedIdsAtK } from '../src/eval/longmemeval/resume.ts';+import { sessionSlug } from '../src/eval/longmemeval/adapter.ts';import { rerankerReadiness } from '../src/core/ai/reranker-readiness.ts';import { __setEmbedTransportForTests, configureGateway, resetGateway } from '../src/core/ai/gateway.ts';import { fnv1a } from '../src/eval/deterministic-embed.ts';@@ -260,7 +261,7 @@ describe('slug collision touching gold → error row (plan D32)', () => {expect(r['col-1'].error).toContain('slug_collision');expect(r['col-1'].hypothesis).toBe('');expect(r['col-1'].slug_collision).toBe(1);- expect(r['col-1'].slug_collision_gold).toEqual(['chat/alpha-b']);+ expect(r['col-1'].slug_collision_gold).toEqual([sessionSlug('col-1', 'alpha_b')]);expect(r['col-1'].recall_all_hit).toBeUndefined();// The run continued: the clean question still scored.expect(r['mc-1'].recall_all_hit).toBe(true);diff --git a/test/eval-longmemeval.slow.test.ts b/test/eval-longmemeval.slow.test.tsindex 4f89d82ca2..33513ece9b 100644--- a/test/eval-longmemeval.slow.test.ts+++ b/test/eval-longmemeval.slow.test.ts@@ -24,7 +24,7 @@ import {createBenchmarkBrain,resetTables,} from '../src/eval/longmemeval/harness.ts';-import { haystackToPages, type LongMemEvalQuestion } from '../src/eval/longmemeval/adapter.ts';+import { haystackToPages, opaqueSessionId, sessionSlug, type LongMemEvalQuestion } from '../src/eval/longmemeval/adapter.ts';import { loadResumeSet } from '../src/commands/eval-longmemeval.ts';import { importFromContent } from '../src/core/import-file.ts';import { DEFAULT_SOURCE_BOOSTS } from '../src/core/search/source-boost.ts';@@ -180,12 +180,13 @@ describe('adapter haystackToPages', () => {};const pages = haystackToPages(q);expect(pages.length).toBe(3);- expect(pages[0].slug).toBe('chat/sess-1');- expect(pages[1].slug).toBe('chat/sess-2');- expect(pages[2].slug).toBe('chat/sess-3');+ expect(pages[0].slug).toBe(sessionSlug('q-shape-1', 'sess-1'));+ expect(pages[1].slug).toBe(sessionSlug('q-shape-1', 'sess-2'));+ expect(pages[2].slug).toBe(sessionSlug('q-shape-1', 'sess-3'));+ expect(new Set(pages.map(p => p.slug)).size).toBe(3);expect(pages[0].content).toContain('type: note');expect(pages[0].content).toContain('date: 2025-01-15');- expect(pages[0].content).toContain('session_id: sess-1');+ expect(pages[0].content).toContain(`session_id: ${opaqueSessionId('q-shape-1', 'sess-1')}`);expect(pages[0].content).toContain('**user:** hi');expect(pages[0].content).toContain('**assistant:** hello');});@@ -202,7 +203,7 @@ describe('adapter haystackToPages', () => {],};const pages = haystackToPages(q);- expect(pages[0].content).toContain('session_id: sess-x');+ expect(pages[0].content).toContain(`session_id: ${opaqueSessionId('q-shape-2', 'sess-x')}`);expect(pages[0].content).not.toContain('date:');});@@ -228,12 +229,12 @@ describe('adapter haystackToPages', () => {};const pages = haystackToPages(q);expect(pages.length).toBe(2);- // Slugs got lowercased + underscores became hyphens (validator-safe).- expect(pages[0].slug).toBe('chat/sharegpt-abc-0');- expect(pages[1].slug).toBe('chat/sess-def-1');- // Frontmatter keeps the ORIGINAL session_id (no sanitization). The- // _s ids preserve through the round-trip; only the slug got rewritten.- expect(pages[0].content).toContain('session_id: sharegpt_AbC_0');+ // Slugs are opaque per-question ids (validator-safe, no gold label).+ expect(pages[0].slug).toBe(sessionSlug('q-s-1', 'sharegpt_AbC_0'));+ expect(pages[1].slug).toBe(sessionSlug('q-s-1', 'sess_DEF_1'));+ // Frontmatter carries the same opaque id; the raw id never reaches the page.+ expect(pages[0].content).toContain(`session_id: ${opaqueSessionId('q-s-1', 'sharegpt_AbC_0')}`);+ expect(pages[0].content).not.toContain('sharegpt_AbC_0');expect(pages[0].content).toContain('date: 2025-01-01');expect(pages[0].content).toContain('**user:** hi');expect(pages[1].content).toContain('**user:** bye');@@ -254,7 +255,7 @@ describe('adapter haystackToPages', () => {};const pages = haystackToPages(q);expect(pages.length).toBe(1);- expect(pages[0].slug).toBe('chat/lme-q-s-2-0');+ expect(pages[0].slug).toBe(sessionSlug('q-s-2', 'lme_q-s-2_0'));});});diff --git a/test/get-tags-remote-privacy.test.ts b/test/get-tags-remote-privacy.test.tsnew file mode 100644index 0000000000..2cd7c2ab82--- /dev/null+++ b/test/get-tags-remote-privacy.test.ts@@ -0,0 +1,51 @@+/**+ * Read-path audit #19: get_tags had no private or soft-delete filter, so a+ * remote caller learned that a `visibility: private` page exists and read its+ * tags. Remote callers now get [] for private and soft-deleted pages; trusted+ * local callers keep the full view.+ */+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 type { OperationContext } from '../src/core/operations.ts';++let engine: PGLiteEngine;+const get_tags = operations.find(o => o.name === 'get_tags')!;++const ctxOf = (remote: boolean): OperationContext => ({+ engine: engine as any, config: {} as any, logger: console as any, dryRun: false, remote, sourceId: 'default',+});++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await engine.putPage('notes/world', { type: 'note', title: 'World', compiled_truth: 'body' } as any);+ await engine.putPage('notes/secret', { type: 'note', title: 'Secret', compiled_truth: 'body', frontmatter: { visibility: 'private' } } as any);+ await engine.putPage('notes/gone', { type: 'note', title: 'Gone', compiled_truth: 'body' } as any);+ await engine.addTag('notes/world', 'world-tag');+ await engine.addTag('notes/secret', 'secret-tag');+ await engine.addTag('notes/gone', 'gone-tag');+ await engine.executeRaw(`UPDATE pages SET deleted_at = now() WHERE slug = 'notes/gone'`);+}, 60_000);++afterAll(async () => { await engine.disconnect(); });++describe('get_tags respects page visibility for remote callers', () => {+ test('world page tags are visible to remote callers', async () => {+ expect(await get_tags.handler(ctxOf(true), { slug: 'notes/world' })).toEqual(['world-tag']);+ });++ test('a private page returns no tags to a remote caller', async () => {+ expect(await get_tags.handler(ctxOf(true), { slug: 'notes/secret' })).toEqual([]);+ });++ test('a soft-deleted page returns no tags to a remote caller', async () => {+ expect(await get_tags.handler(ctxOf(true), { slug: 'notes/gone' })).toEqual([]);+ });++ test('trusted local callers keep the full view', async () => {+ expect(await get_tags.handler(ctxOf(false), { slug: 'notes/secret' })).toEqual(['secret-tag']);+ expect(await get_tags.handler(ctxOf(false), { slug: 'notes/gone' })).toEqual(['gone-tag']);+ });+});diff --git a/test/longmemeval-capture.test.ts b/test/longmemeval-capture.test.tsindex bc5af6895a..66f2f48f85 100644--- a/test/longmemeval-capture.test.ts+++ b/test/longmemeval-capture.test.ts@@ -7,7 +7,7 @@ import { describe, test, expect } from 'bun:test';import type { HybridSearchMeta, SearchResult } from '../src/core/types.ts';import { buildCaptureExtras, poolKey } from '../src/eval/longmemeval/capture.ts';import { buildSlugToRawMap } from '../src/eval/longmemeval/metrics.ts';-import type { LongMemEvalQuestion } from '../src/eval/longmemeval/adapter.ts';+import { sessionSlug, type LongMemEvalQuestion } from '../src/eval/longmemeval/adapter.ts';function row(slug: string, chunk_id: number, over: Partial<SearchResult> = {}): SearchResult {return {@@ -23,6 +23,7 @@ const Q = {answer_session_ids: ['Sess_A'],} as unknown as LongMemEvalQuestion;const MAP = buildSlugToRawMap(Q);+const A = sessionSlug('q', 'Sess_A'), B = sessionSlug('q', 'Sess_B'), C = sessionSlug('q', 'Sess_C');const autocutMeta = (kept: number, total: number): HybridSearchMeta =>({ vector_enabled: true, autocut: { applied: true, signal: 'rerank', cut: kept, kept, total, gapRatio: 0.5 } } as unknown as HybridSearchMeta);@@ -36,11 +37,11 @@ describe('poolKey', () => {describe('buildCaptureExtras', () => {const pool = [- row('chat/sess-b', 2, { rerank_score: 0.9 }),- row('chat/sess-a', 1, { rerank_score: 0.8 }),- row('chat/sess-c', 3, { alias_hit: true }), // unscored alias hop- row('chat/sess-c', 4, { exact_lookup: 'title' }), // unscored exact lookup- row('chat/sess-b', 5, { rerank_score: 0.1, relational_pinned: true }),+ row(B, 2, { rerank_score: 0.9 }),+ row(A, 1, { rerank_score: 0.8 }),+ row(C, 3, { alias_hit: true }), // unscored alias hop+ row(C, 4, { exact_lookup: 'title' }), // unscored exact lookup+ row(B, 5, { rerank_score: 0.1, relational_pinned: true }),];// Pre-rerank (RRF) order differs from pool order; the last pool row is absent from it.const preRerank = [pool[1], pool[0], pool[2], pool[3]];@@ -75,7 +76,7 @@ describe('buildCaptureExtras', () => {test('autocut_kept_keys: present iff autocut recorded a decision AND kept === results.length; equals results.map(poolKey)', () => {const results = pool.slice(0, 2);const exact = buildCaptureExtras({ pool, preRerank, meta: autocutMeta(2, 5), results, slugToRaw: MAP });- expect(exact.autocut_kept_keys).toEqual(['chat/sess-b#2', 'chat/sess-a#1']);+ expect(exact.autocut_kept_keys).toEqual([`${B}#2`, `${A}#1`]);expect(exact.autocut_kept_keys).toEqual(results.map(poolKey));// A further limit/budget slice hid the exact set → absent (replay falls back to count/gap validation).const sliced = buildCaptureExtras({ pool, preRerank, meta: autocutMeta(3, 5), results, slugToRaw: MAP });diff --git a/test/longmemeval-diagnostics.test.ts b/test/longmemeval-diagnostics.test.tsindex c4b62ebcaa..ec65396d67 100644--- a/test/longmemeval-diagnostics.test.ts+++ b/test/longmemeval-diagnostics.test.ts@@ -47,7 +47,7 @@ import {} from '../src/eval/longmemeval/diagnostics.ts';import { buildSlugToRawMap } from '../src/eval/longmemeval/metrics.ts';import { buildRunConfig, type RetrievalPins } from '../src/eval/longmemeval/run-config.ts';-import type { LongMemEvalQuestion } from '../src/eval/longmemeval/adapter.ts';+import { sessionSlug, type LongMemEvalQuestion } from '../src/eval/longmemeval/adapter.ts';import { createBenchmarkBrain } from '../src/eval/longmemeval/harness.ts';import { __setEmbedTransportForTests, configureGateway, resetGateway } from '../src/core/ai/gateway.ts';import { fnv1a } from '../src/eval/deterministic-embed.ts';@@ -228,7 +228,8 @@ describe('receipt parsing, top-k reading, split membership, summary, glossary',test('session rank builders: first row rank vs distinct-session rank through the slug→raw map', () => {const q = { question_id: 'q', question_type: 't', question: '', answer: '', haystack_sessions: [[], [], []], haystack_session_ids: ['Sess_A', 'Sess_B', 'Sess_C'], answer_session_ids: [] } as unknown as LongMemEvalQuestion;const map = buildSlugToRawMap(q);- const rows = [{ slug: 'chat/sess-a' }, { slug: 'chat/sess-a' }, { slug: 'chat/sess-c' }, { slug: 'chat/sess-b' }];+ const [a, b, c] = ['Sess_A', 'Sess_B', 'Sess_C'].map(id => sessionSlug('q', id));+ const rows = [{ slug: a }, { slug: a }, { slug: c }, { slug: b }];expect([...sessionRowRanks(rows, map)]).toEqual([['Sess_A', 1], ['Sess_C', 3], ['Sess_B', 4]]);expect([...sessionDistinctRanks(rows, map)]).toEqual([['Sess_A', 1], ['Sess_C', 2], ['Sess_B', 3]]);});diff --git a/test/longmemeval-gold-leak.slow.test.ts b/test/longmemeval-gold-leak.slow.test.tsnew file mode 100644index 0000000000..9bccd770c6--- /dev/null+++ b/test/longmemeval-gold-leak.slow.test.ts@@ -0,0 +1,94 @@+/**+ * LongMemEval gold-label leak guard. Every gold session id in the public+ * dataset starts with `answer_` and no distractor does, so a raw id anywhere+ * the system or the reader can see it is a free label. The harness must hand+ * the brain and the reader opaque per-question ids only, and still score on+ * the raw ids through its private slug→raw map.+ */+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs';+import { join } from 'path';+import { tmpdir } from 'os';+import { runEvalLongMemEval } from '../src/commands/eval-longmemeval.ts';+import { createBenchmarkBrain } from '../src/eval/longmemeval/harness.ts';+import { haystackToPages, type LongMemEvalQuestion } from '../src/eval/longmemeval/adapter.ts';+import { generateAnswer } from '../src/eval/longmemeval/reader.ts';+import { buildSlugToRawMap } from '../src/eval/longmemeval/metrics.ts';+import { makeStubClient } from './helpers/longmemeval-stub.ts';+import type { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { SearchResult } from '../src/core/types.ts';++const LEAK = /answer[_-]/i;+const GOLD = 'answer_1a2b3c4d_1';++const QUESTION: LongMemEvalQuestion = {+ question_id: 'leak-1',+ question_type: 'single-session-user',+ question: 'what did alice-example want to buy for the river trip',+ answer: 'a kayak',+ haystack_session_ids: ['sharegpt_Xyz_0', GOLD, '9f8e7d6c_2'],+ haystack_dates: ['2024/01/01 (Mon) 10:00', '2024/01/02 (Tue) 10:00', '2024/01/03 (Wed) 10:00'],+ haystack_sessions: [+ [{ role: 'user', content: 'Placeholder about widget-co invoices.' }, { role: 'assistant', content: 'Placeholder reply about invoices.' }],+ [{ role: 'user', content: 'alice-example wants to buy a kayak for the river trip.' }, { role: 'assistant', content: 'A kayak is a fine choice for a river trip.' }],+ [{ role: 'user', content: 'Placeholder about fund-a reserves.' }, { role: 'assistant', content: 'Placeholder reply about reserves.' }],+ ],+ answer_session_ids: [GOLD],+};++let engine: PGLiteEngine;+let tmp: string;++beforeAll(async () => {+ engine = await createBenchmarkBrain();+ tmp = mkdtempSync(join(tmpdir(), 'lme-gold-leak-'));+});+afterAll(async () => {+ if (engine) await engine.disconnect();+ rmSync(tmp, { recursive: true, force: true });+});++describe('LongMemEval gold-label leak', () => {+ test('adapter pages carry no raw session id in slug or content', () => {+ for (const page of haystackToPages(QUESTION)) {+ expect(page.slug).not.toMatch(LEAK);+ expect(page.content).not.toMatch(LEAK);+ expect(page.slug).toMatch(/^chat\/s-[0-9a-f]{10}$/);+ }+ });++ test('reader request carries no raw session id', async () => {+ const pages = haystackToPages(QUESTION);+ const results = pages.map((p, i) => ({ slug: p.slug, chunk_text: p.content, chunk_id: i + 1, score: 1 - i / 10 }) as SearchResult);+ const { client, calls } = makeStubClient('a kayak');+ await generateAnswer(client, QUESTION, results, pages, buildSlugToRawMap(QUESTION), 'anthropic:claude-sonnet-4-6');+ expect(calls.length).toBe(1);+ expect(calls[0].userText).toContain('<chat_session id="s-');+ expect(calls[0].system + calls[0].userText).not.toMatch(LEAK);+ });++ test('harness run: brain rows and reader prompt are opaque, scoring still joins on raw gold ids', async () => {+ const fixture = join(tmp, 'leak.jsonl');+ writeFileSync(fixture, JSON.stringify(QUESTION) + '\n', 'utf8');+ const out = join(tmp, 'leak-out.jsonl');+ const { client, calls } = makeStubClient('a kayak');+ await runEvalLongMemEval([fixture, '--keyword-only', '--no-trajectory', '--top-k', '3', '--output', out], { client, engine });++ expect(calls.length).toBe(1);+ expect(calls[0].userText).toContain('kayak');+ expect(calls[0].system + calls[0].userText).not.toMatch(LEAK);++ const pages = await engine.executeRaw<{ slug: string; title: string; compiled_truth: string; frontmatter: unknown }>(+ `SELECT slug, title, compiled_truth, frontmatter FROM pages`,+ );+ expect(pages.length).toBe(3);+ for (const p of pages) expect(JSON.stringify(p)).not.toMatch(LEAK);+ const chunks = await engine.executeRaw<{ chunk_text: string }>(`SELECT chunk_text FROM content_chunks`);+ expect(chunks.length).toBeGreaterThan(0);+ for (const c of chunks) expect(c.chunk_text).not.toMatch(LEAK);++ const row = JSON.parse(readFileSync(out, 'utf8').split('\n').filter(Boolean)[0]);+ expect(row.recall_all_hit).toBe(true);+ expect(row.retrieved[0].session_id).toBe(GOLD);+ }, 120_000);+});diff --git a/test/longmemeval-metrics.test.ts b/test/longmemeval-metrics.test.tsindex b6595d3273..c3770db6ee 100644--- a/test/longmemeval-metrics.test.ts+++ b/test/longmemeval-metrics.test.ts@@ -10,7 +10,9 @@ import { join } from 'path';import type { SearchResult } from '../src/core/types.ts';import {haystackToPages,+ opaqueSessionId,sanitizeSessionIdForSlug,+ sessionSlug,type LongMemEvalQuestion,} from '../src/eval/longmemeval/adapter.ts';import {@@ -83,11 +85,13 @@ describe('normalizeSessionId / sessionIdFromSlug / isAbstentionQuestion', () =>expect(normalizeSessionId(once)).toBe(once);});- test('normalized ids round-trip through the adapter slug', () => {+ test('adapter slugs are opaque per-question ids that round-trip through sessionIdFromSlug', () => {const q = sQuestion('q1', ['sharegpt_yywfIrx_0'], []);const pages = haystackToPages(q);- expect(pages[0].slug).toBe(`chat/${normalizeSessionId('sharegpt_yywfIrx_0')}`);- expect(sessionIdFromSlug(pages[0].slug)).toBe('sharegpt-yywfirx-0');+ expect(pages[0].slug).toBe(sessionSlug('q1', 'sharegpt_yywfIrx_0'));+ expect(pages[0].slug).toMatch(/^chat\/s-[0-9a-f]{10}$/);+ expect(sessionIdFromSlug(pages[0].slug)).toBe(opaqueSessionId('q1', 'sharegpt_yywfIrx_0'));+ expect(sessionSlug('q2', 'sharegpt_yywfIrx_0')).not.toBe(pages[0].slug);});test('sessionIdFromSlug strips chat/, then any first segment, else returns the slug', () => {@@ -109,8 +113,8 @@ describe('normalizeSessionId / sessionIdFromSlug / isAbstentionQuestion', () =>describe('rawSessionId — the ONE slug→raw resolver', () => {test('mapped slug → first raw id in haystack order; unmapped slug (or no map) → normalized tail; reader.ts re-exports the same function', () => {const map = buildSlugToRawMap(sQuestion('q', ['Sess_A', 'sess-a', 'Other_1'], []));- expect(rawSessionId('chat/sess-a', map)).toBe('Sess_A');- expect(rawSessionId('chat/other-1', map)).toBe('Other_1');+ expect(rawSessionId(sessionSlug('q', 'Sess_A'), map)).toBe('Sess_A');+ expect(rawSessionId(sessionSlug('q', 'Other_1'), map)).toBe('Other_1');expect(rawSessionId('chat/unmapped-9', map)).toBe('unmapped-9');expect(rawSessionId('chat/unmapped-9')).toBe('unmapped-9');expect(rawSessionId('notes/x')).toBe('x');@@ -124,8 +128,8 @@ describe('buildSlugToRawMap / detectSlugCollisions', () => {const map = buildSlugToRawMap(q);const slugs = haystackToPages(q).map(p => p.slug);expect(Array.from(map.keys()).sort()).toEqual([...slugs].sort());- expect(map.get('chat/sharegpt-yywfirx-0')).toEqual(['sharegpt_yywfIrx_0']);- expect(map.get('chat/sharegpt-qz-9-2')).toEqual(['sharegpt_Qz.9_2']);+ expect(map.get(sessionSlug('q1', 'sharegpt_yywfIrx_0'))).toEqual(['sharegpt_yywfIrx_0']);+ expect(map.get(sessionSlug('q1', 'sharegpt_Qz.9_2'))).toEqual(['sharegpt_Qz.9_2']);expect(detectSlugCollisions(map)).toEqual([]);});@@ -142,23 +146,23 @@ describe('buildSlugToRawMap / detectSlugCollisions', () => {],};const map = buildSlugToRawMap(q);- expect(map.get('chat/s-1')).toEqual(['S_1']);- expect(map.get('chat/s-2')).toEqual(['s-2']);+ expect(map.get(sessionSlug('q-oracle', 'S_1'))).toEqual(['S_1']);+ expect(map.get(sessionSlug('q-oracle', 's-2'))).toEqual(['s-2']);});test('a_b vs a-b collide on the slug and are reported once, sorted', () => {const q = sQuestion('q1', ['z_z', 'a_b', 'a-b', 'other', 'z-z'], ['a_b']);const map = buildSlugToRawMap(q);- expect(map.get('chat/a-b')).toEqual(['a_b', 'a-b']);- expect(detectSlugCollisions(map)).toEqual(['chat/a-b', 'chat/z-z']);- expect(collisionsTouchingGold(map, ['a_b'])).toEqual(['chat/a-b']);+ expect(map.get(sessionSlug('q1', 'a_b'))).toEqual(['a_b', 'a-b']);+ expect(detectSlugCollisions(map)).toEqual([sessionSlug('q1', 'a_b'), sessionSlug('q1', 'z_z')].sort());+ expect(collisionsTouchingGold(map, ['a_b'])).toEqual([sessionSlug('q1', 'a_b')]);expect(collisionsTouchingGold(map, ['other'])).toEqual([]);});test('an identical raw id repeated in the haystack is deduped, not a collision', () => {const q = sQuestion('q1', ['dup_1', 'dup_1'], ['dup_1']);const map = buildSlugToRawMap(q);- expect(map.get('chat/dup-1')).toEqual(['dup_1']);+ expect(map.get(sessionSlug('q1', 'dup_1'))).toEqual(['dup_1']);expect(detectSlugCollisions(map)).toEqual([]);});@@ -177,10 +181,10 @@ describe('distinctRetrievedSessions', () => {test('collapses chunk rows to raw ids in first-occurrence order with 1-based ranks', () => {const results = [- row('chat/sess-decoy-c', { chunk_id: 1, score: 0.9 }),- row('chat/sess-multi-a', { chunk_id: 2, score: 0.8, rerank_score: 0.7 }),- row('chat/sess-decoy-c', { chunk_id: 3, score: 0.6 }),- row('chat/sess-multi-a', { chunk_id: 4, score: 0.5 }),+ row(sessionSlug('q1', 'Sess_DECOY_c'), { chunk_id: 1, score: 0.9 }),+ row(sessionSlug('q1', 'Sess_MULTI_a'), { chunk_id: 2, score: 0.8, rerank_score: 0.7 }),+ row(sessionSlug('q1', 'Sess_DECOY_c'), { chunk_id: 3, score: 0.6 }),+ row(sessionSlug('q1', 'Sess_MULTI_a'), { chunk_id: 4, score: 0.5 }),];const distinct = distinctRetrievedSessions(results, map);expect(distinct).toEqual([@@ -329,10 +333,10 @@ describe('buildRow', () => {test('scores recall over the top-k distinct sessions but records every returned row', () => {const results = [- row('chat/sess-multi-a', { chunk_id: 11, score: 0.9, rerank_score: 0.8, alias_hit: true }),- row('chat/sess-decoy-c', { chunk_id: 12, score: 0.7 }),- row('chat/sess-multi-a', { chunk_id: 13, score: 0.6 }),- row('chat/sess-multi-b', { chunk_id: 14, score: 0.5 }),+ row(sessionSlug('mc-2', 'Sess_MULTI_a'), { chunk_id: 11, score: 0.9, rerank_score: 0.8, alias_hit: true }),+ row(sessionSlug('mc-2', 'Sess_DECOY_c'), { chunk_id: 12, score: 0.7 }),+ row(sessionSlug('mc-2', 'Sess_MULTI_a'), { chunk_id: 13, score: 0.6 }),+ row(sessionSlug('mc-2', 'Sess_MULTI_b'), { chunk_id: 14, score: 0.5 }),];const r = buildRow({ question: q, hypothesis: 'h', results, k: 2, slugToRaw: map, mode: 'balanced', extra: { intent: 'other' } });expect(r.question_id).toBe('mc-2');@@ -349,10 +353,10 @@ describe('buildRow', () => {expect(r.gold_found).toBe(1);expect(r.distinct_sessions_in_top_k).toBe(2);expect(r.retrieved).toEqual([- { slug: 'chat/sess-multi-a', chunk_id: 11, session_id: 'Sess_MULTI_a', rank: 1, score: 0.9, rerank_score: 0.8, alias_hit: true },- { slug: 'chat/sess-decoy-c', chunk_id: 12, session_id: 'Sess_DECOY_c', rank: 2, score: 0.7 },- { slug: 'chat/sess-multi-a', chunk_id: 13, session_id: 'Sess_MULTI_a', rank: 3, score: 0.6 },- { slug: 'chat/sess-multi-b', chunk_id: 14, session_id: 'Sess_MULTI_b', rank: 4, score: 0.5 },+ { slug: sessionSlug('mc-2', 'Sess_MULTI_a'), chunk_id: 11, session_id: 'Sess_MULTI_a', rank: 1, score: 0.9, rerank_score: 0.8, alias_hit: true },+ { slug: sessionSlug('mc-2', 'Sess_DECOY_c'), chunk_id: 12, session_id: 'Sess_DECOY_c', rank: 2, score: 0.7 },+ { slug: sessionSlug('mc-2', 'Sess_MULTI_a'), chunk_id: 13, session_id: 'Sess_MULTI_a', rank: 3, score: 0.6 },+ { slug: sessionSlug('mc-2', 'Sess_MULTI_b'), chunk_id: 14, session_id: 'Sess_MULTI_b', rank: 4, score: 0.5 },]);expect(r.retrieved_session_ids).toEqual(['Sess_MULTI_a', 'Sess_DECOY_c', 'Sess_MULTI_b']);expect(r.gold_missing_from_haystack).toEqual([]);@@ -377,7 +381,7 @@ describe('buildRow', () => {test('no gold: recall fields omitted (row stays out of the denominator), abstention flagged', () => {const abs = sQuestion('mc-9_abs', ['s_1'], []);- const r = buildRow({ question: abs, hypothesis: 'h', results: [row('chat/s-1')], k: 5, slugToRaw: buildSlugToRawMap(abs) });+ const r = buildRow({ question: abs, hypothesis: 'h', results: [row(sessionSlug('mc-9_abs', 's_1'))], k: 5, slugToRaw: buildSlugToRawMap(abs) });expect(r.abstention).toBe(true);expect('recall_all_hit' in r).toBe(false);expect('recall_any_hit' in r).toBe(false);@@ -388,7 +392,7 @@ describe('buildRow', () => {test('gold missing from haystack and slug collisions are stamped per row', () => {const bad = sQuestion('q-bad', ['a_b', 'a-b', 'c_1'], ['c_1', 'ghost']);- const r = buildRow({ question: bad, hypothesis: 'h', results: [row('chat/c-1')], k: 5, slugToRaw: buildSlugToRawMap(bad) });+ const r = buildRow({ question: bad, hypothesis: 'h', results: [row(sessionSlug('q-bad', 'c_1'))], k: 5, slugToRaw: buildSlugToRawMap(bad) });expect(r.gold_missing_from_haystack).toEqual(['ghost']);expect(r.slug_collision).toBe(1);expect(r.recall_any_hit).toBe(true);diff --git a/test/r1-namedthing-rerank-ab.test.ts b/test/r1-namedthing-rerank-ab.test.tsindex 0962b1a23c..f3a2506b3a 100644--- a/test/r1-namedthing-rerank-ab.test.ts+++ b/test/r1-namedthing-rerank-ab.test.ts@@ -170,8 +170,8 @@ function arm(records: QueryRecord[], armId: 'off' | 'on' = 'off'): ArmRun {return {arm: armId,records,- report: { schema_version: 1, k: 3, total: records.length, families: [], questions: [] },- gate: { pass: true, breaches: [], warnings: [] },+ report: { schema_version: 1, k: 3, total: records.length, errored: 0, families: [], questions: [] },+ gate: { pass: true, breaches: [], warnings: [], errored: 0 },};}diff --git a/test/retrieval-quality-harness.test.ts b/test/retrieval-quality-harness.test.tsindex 67073e15be..879b6e32c7 100644--- a/test/retrieval-quality-harness.test.ts+++ b/test/retrieval-quality-harness.test.ts@@ -123,3 +123,37 @@ describe('parseQuestionsJsonl', () => {expect(qs[1].forbidden).toEqual(['b']);});});++describe('search errors count as errors (read-path audit #10)', () => {+ const qs: NamedThingQuestion[] = [+ { family: 'hard-negative', query: 'boom', forbidden: ['bad'] },+ { family: 'title-substring', query: 'ok', relevant: ['a'] },+ ];+ const searchFn = async (query: string) => {+ if (query === 'boom') throw new Error('search down');+ return ['a'];+ };++ test('a thrown search is a miss, never a clean hard-negative', async () => {+ const report = await runRetrievalQuality(qs, searchFn);+ const boom = report.questions.find(q => q.query === 'boom')!;+ expect(boom.errored).toBe(true);+ expect(boom.hit_at_1).toBe(false);+ expect(boom.hit_at_3).toBe(false);+ expect(boom.reciprocal_rank).toBe(0);+ expect(boom.negative_clean).toBe(false);+ expect(report.errored).toBe(1);+ expect(report.families.find(f => f.family === 'hard-negative')!.errored).toBe(1);+ expect(report.families.find(f => f.family === 'hard-negative')!.hit_at_1).toBe(0);+ expect(report.questions.find(q => q.query === 'ok')!.errored).toBeUndefined();+ });++ test('any errored question fails the gate', async () => {+ const gate = evaluateGate(await runRetrievalQuality(qs, searchFn));+ expect(gate.errored).toBe(1);+ expect(gate.pass).toBe(false);+ const clean = evaluateGate(await runRetrievalQuality(qs.slice(1), searchFn));+ expect(clean.errored).toBe(0);+ expect(clean.pass).toBe(true);+ });+});diff --git a/test/search/auto-entity-detail-soft.test.ts b/test/search/auto-entity-detail-soft.test.tsnew file mode 100644index 0000000000..5409e09a2e--- /dev/null+++ b/test/search/auto-entity-detail-soft.test.ts@@ -0,0 +1,88 @@+/**+ * Auto-detected entity intent ("who is …", "tell me about …") suggests+ * detail=low. It used to hard-filter every arm to compiled_truth in SQL, and+ * the zero-result escalation only covered an EXPLICIT low, so a timeline-only+ * answer was invisible. Auto low is now a soft preference: no SQL filter, a+ * mild compiled-truth tilt. An explicit `detail: 'low'` keeps the filter.+ */+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { resetPgliteState } from '../helpers/reset-pglite.ts';+import { basisEmbedding } from '../../src/eval/deterministic-embed.ts';+import { installPageProjection, readProjectionSnapshot } from '../../src/core/page-state/projections.ts';+import {+ AUTO_LOW_COMPILED_TRUTH_TILT,+ compiledTruthFusionBoost,+ hybridSearch,+ rrfFusionWeighted,+} from '../../src/core/search/hybrid.ts';+import { classifyQuery } from '../../src/core/search/query-intent.ts';+import type { HybridSearchMeta, SearchResult } from '../../src/core/types.ts';++let engine: PGLiteEngine;+beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);+afterAll(async () => { await engine.disconnect(); });+beforeEach(async () => { await resetPgliteState(engine); });++async function seed(slug: string, type: string, chunks: Array<{ text: string; source: 'compiled_truth' | 'timeline'; dim: number }>, title: string) {+ const ct = chunks.filter(c => c.source === 'compiled_truth').map(c => c.text).join('\n');+ const tl = chunks.filter(c => c.source === 'timeline').map(c => c.text).join('\n');+ await engine.putPage(slug, { type, title, compiled_truth: ct, timeline: tl } as any);+ const snap = (await readProjectionSnapshot(engine, slug, 'default', { allowUnsealed: true }))!;+ await installPageProjection(engine, snap, chunks.map((c, i) => ({+ chunk_index: i, chunk_text: c.text, chunk_source: c.source, embedding: basisEmbedding(c.dim, 1536), token_count: 10,+ })) as any, { seal: true });+}++const noRerank = { enabled: false, topNIn: 0, topNOut: null } as any;+const QUERY = 'who is the founder of the Widget Guild';++describe('auto entity intent: detail=low is a soft preference', () => {+ test('the probe query classifies as entity / low', () => {+ expect(classifyQuery(QUERY).intent).toBe('entity');+ expect(classifyQuery(QUERY).suggestedDetail).toBe('low');+ });++ test('a timeline-only answer is found under auto detail', async () => {+ await seed('meetings/2024-03-01-guild', 'meeting', [+ { text: 'Guild kickoff: Alice Example founded the Widget Guild and chairs it.', source: 'timeline', dim: 7 },+ ], 'Kickoff');+ await seed('notes/unrelated', 'note', [{ text: 'Grocery list: apples and bread.', source: 'compiled_truth', dim: 9 }], 'Groceries');+ let meta: HybridSearchMeta | undefined;+ const auto = await hybridSearch(engine, QUERY, {+ queryEmbedFn: () => basisEmbedding(7, 1536), reranker: noRerank, onMeta: (m) => { meta = m; },+ });+ expect(auto[0]?.slug).toBe('meetings/2024-03-01-guild');+ expect(auto[0]?.chunk_source).toBe('timeline');+ expect(meta?.detail_resolved).toBe('low');+ }, 60_000);++ test('an explicit detail=low still hard-filters to compiled truth', async () => {+ await seed('meetings/2024-03-01-guild', 'meeting', [+ { text: 'Guild kickoff: Alice Example founded the Widget Guild and chairs it.', source: 'timeline', dim: 7 },+ ], 'Kickoff');+ await seed('notes/unrelated', 'note', [{ text: 'Grocery list: apples and bread.', source: 'compiled_truth', dim: 9 }], 'Groceries');+ const explicit = await hybridSearch(engine, QUERY, {+ queryEmbedFn: () => basisEmbedding(7, 1536), reranker: noRerank, detail: 'low',+ });+ expect(explicit.every(r => r.chunk_source === 'compiled_truth')).toBe(true);+ }, 60_000);++ test('boost argument: explicit low = full boost, auto low = soft tilt, others = none', () => {+ expect(compiledTruthFusionBoost('low', 'low')).toBe(true);+ expect(compiledTruthFusionBoost('low', undefined)).toBe(AUTO_LOW_COMPILED_TRUTH_TILT);+ expect(compiledTruthFusionBoost('medium', undefined)).toBe(false);+ expect(compiledTruthFusionBoost(undefined, undefined)).toBe(false);+ expect(compiledTruthFusionBoost('high', 'high')).toBe(false);+ });++ test('the soft tilt multiplies compiled_truth rows by the tilt, not 2x', () => {+ const r = (slug: string, source: 'compiled_truth' | 'timeline'): SearchResult => ({+ slug, page_id: 1, title: slug, type: 'note', chunk_text: slug, chunk_source: source, chunk_id: 1, chunk_index: 0, score: 0, stale: false,+ } as SearchResult);+ const out = rrfFusionWeighted([{ list: [r('tl', 'timeline'), r('ct', 'compiled_truth')], k: 60 }], AUTO_LOW_COMPILED_TRUTH_TILT);+ const ct = out.find(x => x.slug === 'ct')!;+ expect(ct.score).toBeCloseTo((60 / 61) * AUTO_LOW_COMPILED_TRUTH_TILT, 12);+ expect(out[0].slug).toBe('ct');+ });+});diff --git a/test/search/eval-vector-query-embed.test.ts b/test/search/eval-vector-query-embed.test.tsnew file mode 100644index 0000000000..3b10809194--- /dev/null+++ b/test/search/eval-vector-query-embed.test.ts@@ -0,0 +1,39 @@+/**+ * Read-path audit #9: `gbrain eval --strategy vector` embedded queries with+ * the DOCUMENT-side `embed()`; hybrid uses `embedQuery` (input_type=query on+ * asymmetric providers), so the vector baseline was handicapped. The vector+ * strategy must send the query-side input type.+ */+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../../src/core/ai/gateway.ts';+import { runEval } from '../../src/core/search/eval.ts';++let engine: PGLiteEngine;+const seen: Array<Record<string, unknown> | undefined> = [];++beforeAll(async () => {+ configureGateway({ embedding_model: 'voyage:voyage-3-large', embedding_dimensions: 1024, env: { VOYAGE_API_KEY: 'test' } });+ __setEmbedTransportForTests((async (p: any) => {+ seen.push(p.providerOptions?.openaiCompatible);+ return { embeddings: p.values.map(() => Array.from({ length: 1024 }, () => 0.1)), values: p.values, usage: { tokens: 1 } };+ }) as any);+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 120_000);++afterAll(async () => {+ await engine.disconnect();+ __setEmbedTransportForTests(null);+ resetGateway();+});++describe('eval vector strategy', () => {+ test('embeds the query with input_type=query', async () => {+ const report = await runEval(engine, [{ query: 'widget pricing', relevant: ['notes/a'] }], { strategy: 'vector' }, 5);+ expect(report.queries.length).toBe(1);+ expect(seen.length).toBeGreaterThan(0);+ expect(seen.every(o => o?.input_type === 'query')).toBe(true);+ }, 60_000);+});diff --git a/test/search/exclude-filters-hybrid.test.ts b/test/search/exclude-filters-hybrid.test.tsnew file mode 100644index 0000000000..ee66de6d55--- /dev/null+++ b/test/search/exclude-filters-hybrid.test.ts@@ -0,0 +1,59 @@+/**+ * Read-path audit #8: hybridSearch rebuilt its engine opts and dropped+ * exclude_slugs / exclude_slug_prefixes / include_slug_prefixes, and PGLite's+ * searchKeyword ignored exclude_slugs and type (Postgres honors both).+ */+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { resetPgliteState } from '../helpers/reset-pglite.ts';+import { installPageProjection, readProjectionSnapshot } from '../../src/core/page-state/projections.ts';+import { hybridSearch } from '../../src/core/search/hybrid.ts';+import { basisEmbedding } from '../../src/eval/deterministic-embed.ts';++let engine: PGLiteEngine;+beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);+afterAll(async () => { await engine.disconnect(); });+beforeEach(async () => { await resetPgliteState(engine); });++async function seed(slug: string, type: string, text: string, dim: number) {+ await engine.putPage(slug, { type, title: slug, compiled_truth: text } as any);+ const snap = (await readProjectionSnapshot(engine, slug, 'default', { allowUnsealed: true }))!;+ await installPageProjection(engine, snap, [{+ chunk_index: 0, chunk_text: text, chunk_source: 'compiled_truth', embedding: basisEmbedding(dim, 1536), token_count: 5,+ }] as any, { seal: true });+}++const rr = { reranker: { enabled: false, topNIn: 0, topNOut: null } as any, queryEmbedFn: () => basisEmbedding(3, 1536) };++describe('exclusion filters', () => {+ test('PGLite searchKeyword honors exclude_slugs and type', async () => {+ await seed('notes/a', 'note', 'widget alpha', 3);+ await seed('people/b', 'person', 'widget beta', 3);+ expect((await engine.searchKeyword('widget', { exclude_slugs: ['notes/a'] })).map(r => r.slug)).toEqual(['people/b']);+ expect((await engine.searchKeyword('widget', { type: 'person' as any })).map(r => r.slug)).toEqual(['people/b']);+ }, 60_000);++ test('hybridSearch passes exclude_slugs and exclude_slug_prefixes to every arm', async () => {+ await seed('notes/a', 'note', 'widget alpha', 3);+ await seed('private-drafts/b', 'note', 'widget beta', 3);+ await seed('notes/c', 'note', 'widget gamma', 3);+ const out = await hybridSearch(engine, 'widget', { ...rr, exclude_slugs: ['notes/a'], exclude_slug_prefixes: ['private-drafts/'] });+ expect(out.map(r => r.slug)).toEqual(['notes/c']);+ }, 60_000);++ test('include_slug_prefixes re-admits a hard-excluded prefix through hybridSearch', async () => {+ await seed('test/fixture-page', 'note', 'widget delta', 3);+ const plain = await hybridSearch(engine, 'widget', rr);+ const admitted = await hybridSearch(engine, 'widget', { ...rr, include_slug_prefixes: ['test/'] });+ expect(plain.map(r => r.slug)).not.toContain('test/fixture-page');+ expect(admitted.map(r => r.slug)).toContain('test/fixture-page');+ }, 60_000);++ test('the alias hop never injects an excluded slug', async () => {+ await seed('notes/a', 'note', 'widget alpha', 3);+ await seed('projects/hall', 'note', 'unrelated text entirely', 9);+ await engine.setPageAliases('projects/hall', 'default', ['hall of light']);+ const out = await hybridSearch(engine, 'hall of light', { ...rr, exclude_slugs: ['projects/hall'] });+ expect(out.map(r => r.slug)).not.toContain('projects/hall');+ }, 60_000);+});diff --git a/test/search/hybrid-reranker-integration.serial.test.ts b/test/search/hybrid-reranker-integration.serial.test.tsindex fdc90ca533..428842a101 100644--- a/test/search/hybrid-reranker-integration.serial.test.ts+++ b/test/search/hybrid-reranker-integration.serial.test.ts@@ -418,6 +418,32 @@ describe('hybridSearch — fail-open contract end-to-end', () => {}});+ test('read-path audit #5: a hard reranker failure stamps degraded[] with rerank_failed', async () => {+ const auditDir = mkdtempSync(join(tmpdir(), 'gbrain-rerank-failed-'));+ const prevAudit = process.env.GBRAIN_AUDIT_DIR;+ process.env.GBRAIN_AUDIT_DIR = auditDir;+ try {+ let degraded: Array<{ stage: string; reason?: string }> = [];+ const out = await hybridSearch(engine, 'alpha keyword', {+ limit: 10,+ reranker: {+ enabled: true,+ topNIn: 30,+ topNOut: null,+ rerankerFn: async () => { throw new Error('HTTP 503 upstream'); },+ },+ onMeta: (meta) => { degraded = meta.degraded ?? []; },+ });+ expect(out.length).toBeGreaterThan(0);+ expect(out.every(r => r.rerank_score === undefined)).toBe(true);+ expect(degraded).toContainEqual({ stage: 'rerank_failed', reason: 'provider_error' });+ } finally {+ if (prevAudit === undefined) delete process.env.GBRAIN_AUDIT_DIR;+ else process.env.GBRAIN_AUDIT_DIR = prevAudit;+ rmSync(auditDir, { recursive: true, force: true });+ }+ });+test('#4648 contrast: reranker DISABLED pass-through does NOT stamp degraded[]', async () => {let degraded: Array<{ stage: string; reason?: string }> = [];const out = await hybridSearch(engine, 'alpha keyword', {diff --git a/test/search/identity-tiers-keep-rerank-order.test.ts b/test/search/identity-tiers-keep-rerank-order.test.tsnew file mode 100644index 0000000000..7f227080bc--- /dev/null+++ b/test/search/identity-tiers-keep-rerank-order.test.ts@@ -0,0 +1,65 @@+/**+ * The alias hop and the exact-lookup tier run AFTER the reranker. `score` on a+ * reranked row is still the fusion score, so a global re-sort by `score`+ * threw away the cross-encoder order. Both tiers must place identity rows and+ * leave every other row in its input (reranked) order.+ */+import { describe, test, expect } from 'bun:test';+import { applyExactLookupTier } from '../../src/core/search/exact-lookup.ts';+import { applyAliasHop } from '../../src/core/search/hybrid.ts';+import type { SearchResult } from '../../src/core/types.ts';++const mk = (slug: string, score: number, rerank?: number): SearchResult => ({+ slug, page_id: slug.length, title: slug, type: 'note', source_id: 'default',+ chunk_id: Math.round(score * 1000), chunk_index: 0, chunk_text: slug, chunk_source: 'compiled_truth',+ score, stale: false, ...(rerank === undefined ? {} : { rerank_score: rerank }),+} as SearchResult);++const noLinksEngine: any = { executeRaw: async () => { throw new Error('no'); }, getLinksByType: async () => [] };+const aliasEngine = (alias: string, slug: string): any => ({+ resolveAliases: async () => new Map([[alias, [{ slug, source_id: 'default' }]]]),+ getPage: async () => ({ id: 99, slug, title: slug, type: 'note', source_id: 'default', compiled_truth: 'body', frontmatter: {} }),+});++describe('identity tiers keep the reranker order', () => {+ test('exact-title tier: identity row first, the rest in reranked order', async () => {+ const reranked = [mk('c', 0.3, 0.95), mk('b', 0.5, 0.6), mk('a', 0.9, 0.1), mk('acme widget', 0.2, 0.05)];+ const out = await applyExactLookupTier(noLinksEngine, reranked, 'Acme Widget', { titleCandidates: [mk('acme widget', 0.2, 0.05)] });+ expect(out[0].slug).toBe('acme widget');+ expect(out[0].exact_lookup).toBe('title');+ expect(out.slice(1).map(r => r.slug)).toEqual(['c', 'b', 'a']);+ });++ test('exact-title tier injecting an absent page keeps the rest in reranked order', async () => {+ const reranked = [mk('c', 0.3, 0.95), mk('b', 0.5, 0.6), mk('a', 0.9, 0.1)];+ const out = await applyExactLookupTier(noLinksEngine, reranked, 'Acme Widget', { titleCandidates: [mk('acme widget', 0.2)] });+ expect(out.map(r => r.slug)).toEqual(['acme widget', 'c', 'b', 'a']);+ expect(out[0].score).toBeGreaterThan(0.9);+ });++ test('alias hop on the reranker #1 keeps it #1 and the rest in reranked order', async () => {+ const reranked = [mk('c', 0.3, 0.95), mk('b', 0.5, 0.6), mk('a', 0.9, 0.1)];+ const out = await applyAliasHop(aliasEngine('c', 'c'), reranked, 'c', {});+ expect(out.map(r => r.slug)).toEqual(['c', 'b', 'a']);+ expect(out[0].alias_hit).toBe(true);+ });++ test('alias hop on a mid-list row never reorders the non-identity rows', async () => {+ const reranked = [mk('c', 0.3, 0.95), mk('b', 0.5, 0.6), mk('d', 0.1, 0.2), mk('a', 0.9, 0.1)];+ const out = await applyAliasHop(aliasEngine('d', 'd'), reranked, 'd', {});+ expect(out.filter(r => r.slug !== 'd').map(r => r.slug)).toEqual(['c', 'b', 'a']);+ });++ test('alias hop injecting an absent page puts it first, the rest in reranked order', async () => {+ const reranked = [mk('c', 0.3, 0.95), mk('b', 0.5, 0.6), mk('a', 0.9, 0.1)];+ const out = await applyAliasHop(aliasEngine('zeta', 'zeta'), reranked, 'zeta', {});+ expect(out.map(r => r.slug)).toEqual(['zeta', 'c', 'b', 'a']);+ expect(out[0].score).toBeGreaterThan(0.9);+ });++ test('score-ordered (un-reranked) input: the 1.10x present boost still climbs past lower scores', async () => {+ const fused = [mk('a', 0.9), mk('b', 0.5), mk('c', 0.48), mk('d', 0.1)];+ const out = await applyAliasHop(aliasEngine('c', 'c'), fused, 'c', {});+ expect(out.map(r => r.slug)).toEqual(['a', 'c', 'b', 'd']);+ });+});diff --git a/test/search/rerank.test.ts b/test/search/rerank.test.tsindex da21b0a285..ab6c40dce6 100644--- a/test/search/rerank.test.ts+++ b/test/search/rerank.test.ts@@ -265,6 +265,43 @@ describe('applyReranker — fail-open on every RerankError reason', () => {});});+describe('applyReranker — a hard failure reports onFailure (read-path audit #5)', () => {+ const failWith = async (err: unknown) => {+ const seen: string[] = [];+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gbrain-rerank-onfailure-'));+ try {+ await withEnv({ GBRAIN_AUDIT_DIR: tmpDir }, async () => {+ const results = [makeResult('a', 1.0, 'a'), makeResult('b', 0.5, 'b')];+ const out = await applyReranker('q', results, {+ enabled: true, topNIn: 2, topNOut: null,+ rerankerFn: async () => { throw err; },+ onFailure: (reason) => { seen.push(reason); },+ onSkip: () => { seen.push('skip'); },+ });+ expect(out).toEqual(results);+ });+ } finally {+ fs.rmSync(tmpDir, { recursive: true, force: true });+ }+ return seen;+ };++ test('HTTP / network / unknown errors report provider_error', async () => {+ expect(await failWith(new RerankError('HTTP 503 upstream', 'network', 503))).toEqual(['provider_error']);+ expect(await failWith(new RerankError('forced', 'auth', 401))).toEqual(['provider_error']);+ expect(await failWith(new Error('arbitrary'))).toEqual(['provider_error']);+ });++ test('timeout and budget keep their reason', async () => {+ expect(await failWith(new RerankError('slow', 'timeout'))).toEqual(['timeout']);+ expect(await failWith(new BudgetExhausted('cap', { reason: 'no_pricing', spent: 0, cap: 1, modelId: 'acmecorp:r' }))).toEqual(['budget']);+ });++ test('a missing key is a skip, not a failure', async () => {+ expect(await failWith(new RerankError('no key', 'no_key'))).toEqual(['skip']);+ });+});+describe('applyReranker — #4648 success-shaped pass-throughs leave a trace', () => {test('empty result set for a non-empty batch: audit row (empty_result_set) + onPassThrough + unchanged results', async () => {const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gbrain-rerank-empty-'));diff --git a/test/search/rrf-page-grain.test.ts b/test/search/rrf-page-grain.test.tsnew file mode 100644index 0000000000..9e76d2974b--- /dev/null+++ b/test/search/rrf-page-grain.test.ts@@ -0,0 +1,130 @@+/**+ * RRF fuses at PAGE grain. Every arm is page-grain (best chunk per page) but+ * picks its own representative chunk, so chunk-keyed fusion split one page's+ * cross-arm agreement across several entries. These tests pin that a page's+ * votes sum across arms whatever chunk each arm picked, that one list votes+ * for a page once (its best rank), that only the page's lead chunk carries the+ * page vote (so a second chunk cannot crowd another page out of a+ * chunk-limited result), and the end-to-end probe from the read-path audit: a+ * page ranked #1 by keyword AND vector must beat a page ranked #2 by both.+ */+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { installPageProjection, readProjectionSnapshot } from '../../src/core/page-state/projections.ts';+import { hybridSearch, rrfFusion, rrfFusionWeighted } from '../../src/core/search/hybrid.ts';+import type { SearchResult } from '../../src/core/types.ts';++function row(slug: string, chunk_id: number, over: Partial<SearchResult> = {}): SearchResult {+ return {+ slug, page_id: 1, title: slug, type: 'note', chunk_text: `${slug} chunk ${chunk_id}`,+ chunk_source: 'compiled_truth', chunk_id, chunk_index: chunk_id, score: 0.5, stale: false, ...over,+ } as SearchResult;+}++describe('rrf page-grain fusion (pure)', () => {+ test('a page #1 in both arms via DIFFERENT chunks beats a page #2 in both', () => {+ const vector = [row('a', 2), row('b', 10), row('f0', 20), row('f1', 21)];+ const keyword = [row('a', 1), row('b', 10)];+ const out = rrfFusionWeighted([{ list: vector, k: 60 }, { list: keyword, k: 60 }], false);+ // The page's lead (tie on own vote -> first list, the vector arm's chunk)+ // carries the summed page vote; its other chunk keeps its own vote.+ expect(out.map(r => `${r.slug}#${r.chunk_id}`)).toEqual(['a#2', 'b#10', 'a#1', 'f0#20', 'f1#21']);+ expect(out[0].score).toBe(1);+ expect(out[1].score).toBeCloseTo((2 / 61) / (2 / 60), 12);+ expect(out[2].score).toBeCloseTo((1 / 60) / (2 / 60), 12);+ });++ test('a page\'s second chunk never crowds out another page\'s lead', () => {+ const vector = [row('a', 1), row('b', 10), row('c', 20)];+ const keyword = [row('a', 2), row('b', 10), row('c', 20)];+ const out = rrfFusionWeighted([{ list: vector, k: 60 }, { list: keyword, k: 60 }], false);+ expect(out.slice(0, 3).map(r => r.slug)).toEqual(['a', 'b', 'c']);+ expect(out[3].slug).toBe('a');+ });++ test('unweighted rrfFusion sums per page too', () => {+ const out = rrfFusion([[row('a', 2), row('b', 10)], [row('a', 1), row('b', 10)]], 60, false);+ expect(out.map(r => `${r.slug}#${r.chunk_id}`)).toEqual(['a#2', 'b#10', 'a#1']);+ });++ test('one list votes for a page once, at its best rank', () => {+ const single = [row('a', 1), row('a', 2), row('b', 10)];+ const other = [row('b', 10)];+ const out = rrfFusionWeighted([{ list: single, k: 60 }, { list: other, k: 60 }], false);+ // a: 1/60 (its second chunk adds no second vote); b: 1/62 + 1/60.+ expect(out[0].slug).toBe('b');+ const a = out.filter(r => r.slug === 'a');+ expect(a.length).toBe(2);+ expect(a[0].chunk_id).toBe(1);+ expect(a[0].score).toBeCloseTo((1 / 60) / (1 / 62 + 1 / 60), 12);+ });++ test('same slug in different sources stays two pages', () => {+ const out = rrfFusionWeighted([+ { list: [row('a', 1, { source_id: 's1' }), row('a', 2, { source_id: 's2' })], k: 60 },+ { list: [row('a', 3, { source_id: 's1' })], k: 60 },+ ], false);+ expect(out[0].source_id).toBe('s1');+ expect(out.find(r => r.source_id === 's2')!.score).toBeLessThan(out[0].score);+ });++ test('weights scale the page vote; keyword_hit stays per chunk', () => {+ const out = rrfFusionWeighted([+ { list: [row('a', 1, { keyword_hit: true })], k: 60 },+ { list: [row('a', 2), row('b', 5)], k: 60, weight: 0.5 },+ ], false);+ expect(out.map(r => r.slug)).toEqual(['a', 'a', 'b']);+ expect(out.find(r => r.chunk_id === 1)!.keyword_hit).toBe(true);+ expect(out.find(r => r.chunk_id === 2)!.keyword_hit).toBeUndefined();+ });+});++describe('rrf page-grain fusion (PGLite probe)', () => {+ let engine: PGLiteEngine;+ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ }, 120_000);+ afterAll(async () => { await engine.disconnect(); });++ const vec = (pairs: Array<[number, number]>) => {+ const v = new Float32Array(1536);+ for (const [i, x] of pairs) v[i] = x;+ const n = Math.hypot(...v);+ for (let i = 0; i < v.length; i++) v[i] /= n;+ return v;+ };+ async function seed(slug: string, title: string, chunks: Array<{ text: string; emb: Float32Array }>) {+ await engine.putPage(slug, { type: 'note', title, compiled_truth: chunks.map(c => c.text).join('\n\n') } as any);+ const snap = (await readProjectionSnapshot(engine, slug, 'default', { allowUnsealed: true }))!;+ await installPageProjection(engine, snap, chunks.map((c, i) => ({+ chunk_index: i, chunk_text: c.text, chunk_source: 'compiled_truth', embedding: c.emb, token_count: 10,+ })) as any, { seal: true });+ }++ test('page #1 in BOTH keyword and vector arms (different chunks) ranks first', async () => {+ await seed('notes/page-a', 'Alpha', [+ { text: 'Introductory remarks about the project.', emb: vec([[50, 1]]) },+ { text: 'zebra migration zebra migration zebra migration observed', emb: vec([[60, 1]]) },+ { text: 'Savanna herds move seasonally across the plains.', emb: vec([[7, 1]]) },+ ]);+ await seed('notes/page-b', 'Beta', [{ text: 'zebra migration notes', emb: vec([[7, 1], [8, 1]]) }]);+ for (let i = 0; i < 5; i++) {+ await seed(`notes/filler-${i}`, `Filler ${i}`, [{ text: `unrelated filler text number ${i}`, emb: vec([[100 + i, 1], [7, 0.2]]) }]);+ }+ const kw = await engine.searchKeyword('zebra migration', { limit: 10 });+ const vq = await engine.searchVector(vec([[7, 1]]), { limit: 10 });+ expect(`${kw[0].slug}#${kw[0].chunk_index}`).toBe('notes/page-a#1');+ expect(`${vq[0].slug}#${vq[0].chunk_index}`).toBe('notes/page-a#2');+ const out = await hybridSearch(engine, 'zebra migration', {+ queryEmbedFn: () => vec([[7, 1]]),+ intentWeighting: false,+ reranker: { enabled: false, topNIn: 0, topNOut: null } as any,+ graph_signals: false,+ });+ expect(out[0].slug).toBe('notes/page-a');+ expect(out[0].chunk_index).toBe(2);+ expect(out[1].slug).toBe('notes/page-b');+ }, 60_000);+});diff --git a/test/search/title-mention-boost.test.ts b/test/search/title-mention-boost.test.tsnew file mode 100644index 0000000000..fd97089246--- /dev/null+++ b/test/search/title-mention-boost.test.ts@@ -0,0 +1,128 @@+/**+ * Read-path audit #6: the exact-match intent boost only fired when the whole+ * query equalled a title or slug, but entity intent is DEFINED by framing+ * words ("who is …"), so it never fired. A title, slug tail or declared alias+ * mentioned inside the query now fires the same bounded boost.+ */+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { isTitleMentionedInQuery } from '../../src/core/search/title-match.ts';+import {+ aliasMentionCandidates,+ applyAliasMentionBoost,+ applyExactMatchBoost,+ weightsForIntent,+} from '../../src/core/search/intent-weights.ts';+import { classifyQuery } from '../../src/core/search/query-intent.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { basisEmbedding } from '../../src/eval/deterministic-embed.ts';+import { installPageProjection, readProjectionSnapshot } from '../../src/core/page-state/projections.ts';+import { hybridSearch } from '../../src/core/search/hybrid.ts';+import type { SearchResult } from '../../src/core/types.ts';++const row = (slug: string, title: string, score = 1): SearchResult => ({+ slug, title, page_id: 1, type: 'person', chunk_text: title, chunk_source: 'compiled_truth',+ chunk_id: 1, chunk_index: 0, score, stale: false, source_id: 'default',+} as SearchResult);++describe('isTitleMentionedInQuery', () => {+ test('a multi-token title inside a framed question', () => {+ expect(isTitleMentionedInQuery('who is Alice Example', 'Alice Example')).toBe(true);+ expect(isTitleMentionedInQuery('tell me about Acme Widget Co', 'Acme Widget Co')).toBe(true);+ expect(isTitleMentionedInQuery('what did alice-example say?', 'Alice Example')).toBe(true);+ });++ test('token boundaries, not substrings; order matters', () => {+ expect(isTitleMentionedInQuery('who is Alice Examples', 'Alice Example')).toBe(false);+ expect(isTitleMentionedInQuery('who is Example Alice', 'Alice Example')).toBe(false);+ expect(isTitleMentionedInQuery('Alice', 'Alice Example')).toBe(false);+ });++ test('generic titles are guarded', () => {+ expect(isTitleMentionedInQuery('what is the plan of the day', 'The')).toBe(false);+ expect(isTitleMentionedInQuery('who is bob', 'Bob')).toBe(false);+ expect(isTitleMentionedInQuery('tell me about Mingtang', 'Mingtang')).toBe(true);+ });+});++describe('applyExactMatchBoost fires on a mentioned title', () => {+ test('"who is Alice Example" boosts page "Alice Example" under entity intent', () => {+ const q = 'who is Alice Example';+ expect(classifyQuery(q).intent).toBe('entity');+ const results = [row('people/alice-example', 'Alice Example'), row('people/charlie-example', 'Charlie Example')];+ applyExactMatchBoost(results, q, weightsForIntent('entity'));+ expect(results[0].score).toBe(1.25);+ expect(results[0].exact_match_boost).toBe(1.25);+ expect(results[1].score).toBe(1);+ });++ test('the slug tail counts too', () => {+ const results = [row('people/alice-example', 'AE')];+ applyExactMatchBoost(results, 'tell me about alice example', weightsForIntent('entity'));+ expect(results[0].score).toBe(1.25);+ });++ test('general intent stays a no-op', () => {+ const results = [row('people/alice-example', 'Alice Example')];+ applyExactMatchBoost(results, 'Alice Example notes', weightsForIntent('general'));+ expect(results[0].score).toBe(1);+ });+});++describe('applyAliasMentionBoost', () => {+ test('n-gram candidates skip short single tokens', () => {+ const c = aliasMentionCandidates('who is the Hall of Light');+ expect(c).toContain('hall of light');+ expect(c).toContain('light');+ expect(c).not.toContain('who');+ expect(c).not.toContain('is');+ });++ test('a page whose alias is mentioned in the query gets the boost once', async () => {+ const results = [row('places/mingtang', 'Mingtang'), row('places/other', 'Other Place')];+ const seen: string[][] = [];+ await applyAliasMentionBoost(results, 'tell me about the hall of light', weightsForIntent('entity'), async (aliases) => {+ seen.push(aliases);+ return new Map([['hall of light', [{ slug: 'places/mingtang', source_id: 'default' }]]]);+ });+ expect(seen[0]).toContain('hall of light');+ expect(results[0].score).toBe(1.25);+ expect(results[1].score).toBe(1);+ // Already boosted by the title path → not boosted twice.+ const again = [row('places/mingtang', 'Mingtang')];+ applyExactMatchBoost(again, 'tell me about mingtang, the hall of light', weightsForIntent('entity'));+ await applyAliasMentionBoost(again, 'tell me about mingtang, the hall of light', weightsForIntent('entity'), async () =>+ new Map([['hall of light', [{ slug: 'places/mingtang', source_id: 'default' }]]]));+ expect(again[0].score).toBe(1.25);+ });++ test('resolver failure is fail-open', async () => {+ const results = [row('places/mingtang', 'Mingtang')];+ await applyAliasMentionBoost(results, 'tell me about the hall of light', weightsForIntent('entity'), async () => { throw new Error('no table'); });+ expect(results[0].score).toBe(1);+ });+});++describe('framed entity query ranks the named page first (PGLite)', () => {+ let engine: PGLiteEngine;+ beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);+ afterAll(async () => { await engine.disconnect(); });++ async function seed(slug: string, title: string, text: string, dim: number) {+ await engine.putPage(slug, { type: 'person', title, compiled_truth: text } as any);+ const snap = (await readProjectionSnapshot(engine, slug, 'default', { allowUnsealed: true }))!;+ await installPageProjection(engine, snap, [{+ chunk_index: 0, chunk_text: text, chunk_source: 'compiled_truth', embedding: basisEmbedding(dim, 1536), token_count: 10,+ }] as any, { seal: true });+ }++ test('"who is Alice Example": the Alice Example page outranks a closer-embedded neighbour', async () => {+ await seed('people/alice-example', 'Alice Example', 'Alice Example runs the widget lab and mentors founders.', 5);+ await seed('people/charlie-example', 'Charlie Example', 'Charlie Example works with Alice Example on the widget lab.', 6);+ const out = await hybridSearch(engine, 'who is Alice Example', {+ queryEmbedFn: () => basisEmbedding(6, 1536),+ reranker: { enabled: false, topNIn: 0, topNOut: null } as any,+ });+ expect(out[0].slug).toBe('people/alice-example');+ expect(out[0].exact_match_boost).toBe(1.25);+ }, 60_000);+});diff --git a/test/unified-multimodal.serial.test.ts b/test/unified-multimodal.serial.test.tsindex e0a051e6e1..ded0c4cbc1 100644--- a/test/unified-multimodal.serial.test.ts+++ b/test/unified-multimodal.serial.test.ts@@ -17,7 +17,8 @@ import {configureGateway,resetGateway,} from '../src/core/ai/gateway.ts';-import { hybridSearch } from '../src/core/search/hybrid.ts';+import { cosineSimilarity, hybridSearch } from '../src/core/search/hybrid.ts';+import { installPageProjection, readProjectionSnapshot } from '../src/core/page-state/projections.ts';import { runReindexMultimodal } from '../src/commands/reindex-multimodal.ts';let engine: PGLiteEngine;@@ -124,6 +125,46 @@ describe('hybridSearch unified routing (Phase 3)', () => {expect(voyageCalled).toBeGreaterThanOrEqual(1);});+ test('read-path audit #7: the unified rescore hydrates embedding_multimodal, not the text column', async () => {+ await engine.setConfig('search.unified_multimodal', 'true');+ fetchHandler = async (url) => new Response(JSON.stringify({+ data: [{ embedding: Array.from({ length: url.includes('multimodalembeddings') ? 1024 : 1536 }, () => 0.1), index: 0 }],+ }), { status: 200 });+ await engine.putPage('notes/mm', { type: 'note', title: 'MM', compiled_truth: 'multimodal body text' } as any);+ const snap = (await readProjectionSnapshot(engine, 'notes/mm', 'default', { allowUnsealed: true }))!;+ const textVec = new Float32Array(1536); textVec[3] = 1;+ await installPageProjection(engine, snap, [{+ chunk_index: 0, chunk_text: 'multimodal body text', chunk_source: 'compiled_truth', embedding: textVec, token_count: 5,+ }] as any, { seal: true });+ await engine.executeRaw(+ `UPDATE content_chunks SET embedding_multimodal = $1::vector WHERE page_id = (SELECT id FROM pages WHERE slug = 'notes/mm')`,+ ['[' + Array.from({ length: 1024 }, () => 0.1).join(',') + ']'],+ );+ const columns: string[] = [];+ const original = engine.getEmbeddingsByChunkIds.bind(engine);+ (engine as any).getEmbeddingsByChunkIds = async (ids: number[], column?: string) => {+ columns.push(column ?? 'embedding');+ return original(ids, column);+ };+ try {+ const results = await hybridSearch(engine, 'multimodal body', { limit: 5 });+ expect(columns).toContain('embedding_multimodal');+ expect(columns).not.toContain('embedding');+ const hit = results.find(r => r.slug === 'notes/mm')!;+ expect(hit.cosine).toBeCloseTo(1, 5);+ } finally {+ (engine as any).getEmbeddingsByChunkIds = original;+ }+ });++ test('cosineSimilarity refuses vectors from different spaces (length mismatch → 0, never NaN)', () => {+ const q = new Float32Array(1024).fill(0.1);+ const d = new Float32Array(1536).fill(0.1);+ expect(cosineSimilarity(q, d)).toBe(0);+ expect(cosineSimilarity(d, q)).toBe(0);+ expect(cosineSimilarity(q, q)).toBeCloseTo(1, 6);+ });+test('D8 fail-open: empty unified column + not strict → falls back to text', async () => {// Set unified flag but DON'T set unified_multimodal_only. Empty DB → unified returns [].await engine.setConfig('search.unified_multimodal', 'true');