Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Revert "feat(search): W3 rerank gate stage 2 — search.reranker.gate on skips the cross-encoder"
garrytan1f0223694456
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0688504b22..fc7a0c6556 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,11 +12,11 @@ identifiers and attribution are available in the pre-removal Git revision## [Unreleased] - memory proof wave 2 W3 + W5, confidence-gated reranking and the page-unit ranking cut (#6445)-**Search can skip the cross-encoder when retrieval already found the answer, and a page-unit call's own budget can size its ranked hits. Both are off by default; `shadow` measures how often the skip would happen without changing results.**+**Search can grade its candidates before the cross-encoder and report how often the reranker was paying for an answer retrieval already found, and a page-unit call's own budget can size its ranked hits. Both are off by default, and the grade never changes results.**### Itemized changes-- `search.reranker.gate` (off by default) grades search candidates before the cross-encoder. `shadow` records how often the reranker was paying for an answer retrieval already found, in the response's `rerank_gate` metadata, on `--explain` and in a new `rerank_gate` section of `gbrain search stats`, and leaves results unchanged. `on` skips the cross-encoder when the top result is a strong vector match (cosine at least `search.evidence_cosine_floor` and `search.reranker.gate_min_gap` ahead of every other page); that skip is reported as `rerank_gate.skipped`, not as a degradation. The cache key now includes the gate keys and `search.evidence_cosine_floor`.+- `search.reranker.gate` (off by default) grades search candidates before the cross-encoder. `shadow` records how often the reranker was paying for an answer retrieval already found, in the response's `rerank_gate` metadata, on `--explain` and in a new `rerank_gate` section of `gbrain search stats`, and leaves results unchanged. A grade is strong when the top result is a vector match with cosine at least `search.evidence_cosine_floor` and `search.reranker.gate_min_gap` ahead of every other page. There is no skip mode: on the dev sets no question reached the 0.8 floor with voyage-4 embeddings, and the reranker changed about half the delivered tokens, so skipping it is not shipped. The cache key now includes the gate keys and `search.evidence_cosine_floor`.- `search.page_rank_budget_ratio` (off by default) lets a `return_unit: "page"` call's own budget size the ranked hit list. Today ranking cuts hits to the mode's `search.tokenBudget` whatever the caller asked for, so under tokenmax delivery is handed far more pages than fit and returns them as slivers. With a ratio set, `search`, `query` and `recall` cut to `min(mode cut, ratio × caller budget)` and report it as `page_rank_cut`. Calls without a budget and other units are unchanged.- `recall` with `return_unit` and `budget_tokens` fills its budget. Delivery used to be sized to the whole budget, and the facts-first packer then dropped whole delivered blocks. It also re-costed those blocks with a chars/4 estimate while delivery had counted cl100k tokens, so even a call with no facts came back about 7% short. Delivery now gets what the facts leave (except under `query_first`), and delivered blocks cost what delivery counted.diff --git a/docs/architecture/key-files/commands-5.md b/docs/architecture/key-files/commands-5.mdindex 24aa33b1d1..508222095b 100644--- a/docs/architecture/key-files/commands-5.md+++ b/docs/architecture/key-files/commands-5.md@@ -17,7 +17,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/search-diagnose.ts` — `gbrain search diagnose "<query>" --target <slug> [--json] [--source <id>]`: Phase-0 retrieval diagnostic. Traces WHERE a target page surfaces (or fails to) across keyword / vector (per-page max-pool) / alias / hybrid layers and names the layer responsible for an incident, so an operator can pin whether the fix is max-pool/innerLimit (vector) vs title/alias. The verdict names the layer that DOES surface the target (or "none"). Pinned by `test/search/search-diagnose.test.ts`.-- `src/commands/search.ts:gbrain search stats` — `rerank_gate` section (eligible, graded, would_skip and `would_skip_rate` over graded, `skipped` (actual skips under `on`), provider_calls, `by_reason`, `ineligible` by why), read from the reserved `(date, 'rerank_gate', <counter>)` rows of `search_telemetry` (no DDL; diverted out of `total_calls` like the empty-result rows; written only when `search.reranker.gate` is not `off`; cache hits add nothing); human output prints it when anything was graded. `graph_signals` section (enabled/source/failures_count/failures_by_reason). JSON envelope adds a `graph_signals` sibling property; `_meta.metric_glossary` adds `graph_signals.enabled` + `graph_signals.failures_by_reason`. Human output prints the section after the existing block. Reads `search.graph_signals` config first, falls back to the mode default. Pinned by `test/search/search-stats-graph-signals.test.ts`. Both `gbrain search stats` and `gbrain search tune` also surface a `coverage` disclosure (JSON: `{cli_invocations: 'recorded_on_clean_exit', reason}`; human: a one-line caveat) sourced from `telemetryCoverage()`/`TELEMETRY_COVERAGE_CAVEAT` in `src/core/search/telemetry.ts`: a short-lived CLI call's buffer flushes during the bounded CLI teardown drain, so a CLEAN exit is recorded; hard kills, drains that exceed their bound, and anything buffered when an engine disconnects outside the CLI teardown path still drop — the disclosure is display-only and reads its truth from the telemetry module's single-source constants. Pinned by the coverage-disclosure tests in `test/commands-search.test.ts`.+- `src/commands/search.ts:gbrain search stats` — `rerank_gate` section (eligible, graded, would_skip and `would_skip_rate` over graded, provider_calls, `by_reason`, `ineligible` by why), read from the reserved `(date, 'rerank_gate', <counter>)` rows of `search_telemetry` (no DDL; diverted out of `total_calls` like the empty-result rows; written only when `search.reranker.gate` is not `off`; cache hits add nothing); human output prints it when anything was graded. `graph_signals` section (enabled/source/failures_count/failures_by_reason). JSON envelope adds a `graph_signals` sibling property; `_meta.metric_glossary` adds `graph_signals.enabled` + `graph_signals.failures_by_reason`. Human output prints the section after the existing block. Reads `search.graph_signals` config first, falls back to the mode default. Pinned by `test/search/search-stats-graph-signals.test.ts`. Both `gbrain search stats` and `gbrain search tune` also surface a `coverage` disclosure (JSON: `{cli_invocations: 'recorded_on_clean_exit', reason}`; human: a one-line caveat) sourced from `telemetryCoverage()`/`TELEMETRY_COVERAGE_CAVEAT` in `src/core/search/telemetry.ts`: a short-lived CLI call's buffer flushes during the bounded CLI teardown drain, so a CLEAN exit is recorded; hard kills, drains that exceed their bound, and anything buffered when an engine disconnects outside the CLI teardown path still drop — the disclosure is display-only and reads its truth from the telemetry module's single-source constants. Pinned by the coverage-disclosure tests in `test/commands-search.test.ts`.- `src/commands/serve-http-grants.ts` + `admin/src/components/ClientGrant.tsx` — typed admin grant request validation and shared profile/advanced permission editor. Register/rescope/TTL routes in `serve-http-registration.ts`, `serve-http-grants.ts`, and `serve-http-admin-api.ts` use canonical grant validation and audit; legacy response shapes remain available. Registration and permission-edit failures add safe classifications, stage, outcome and inspection remedies; an unacknowledged mutation stays outcome-unknown, while read/preview failures and known refusals remain failed. New UI creation defaults to memory-writer and requires a preview, while edits carry the displayed revision and require a fresh preview after any field change or conflict. Detail/catalog endpoints expose non-secret grants and the shared harness registry. Operation authority snapshots, source sets, delegated tools/namespaces, spend, concurrency, and future TTL are independently reviewable; profile regrant is explicit. `admin/src/pages/Agents.tsx` previews machine/public PKCE/confidential PKCE registration and current permissions, and exposes versioned lifecycle actions. Explicit downloads select machine `HarnessCredentials` or native `OAuthClientSetup`; mixed clients require a flow choice. Loading errors preserve stale rows with Retry and disable creation when required source metadata is missing. Browser downloads and native connection evidence remain distinct. Rebuild committed `admin/dist` and `src/admin-embedded.ts` after SPA edits.diff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.mdindex 62427dfc88..5828f78265 100644--- a/docs/architecture/key-files/core-search-2.md+++ b/docs/architecture/key-files/core-search-2.md@@ -3,7 +3,7 @@[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.-- `src/core/search/crag.ts` + `src/core/search/hybrid/rerank-gate.ts` — the CRAG retrieval-confidence grade on the final list (`gradeRetrievalConfidence`, read by the `query` op's `crag` meta and escalation) and the W3 rerank gate's PRE-rerank grade. `gradePreRerank` is pure and reads the deduped candidates in fused order plus the identity lookups, never mutating them: strong is exactly one exact-lookup page, else exactly one full-query alias page, else a full-title identity at rank 1 (normalized title equals the normalized query; a phrase inside a longer title is not identity), else `high_vector_match` (rank-1 raw cosine ≥ `search.evidence_cosine_floor`) whose gap over the best cosine of a DIFFERENT page (image rows excluded; rank-1's own chunks never count) is at least δ (`search.reranker.gate_min_gap`, 0.05). More than one identity page, or a single-token alias hop that would move rank 1, is `identity_ambiguous`; multimodal queries and image rows are never strong; `applyRerankGateTrust` demotes a strong page below `max(caller min_trust, unknown)` to `below_trust_floor`. `RERANK_GATE_SKIP_REASONS` (only `high_vector_match`) decides `would_skip`; title, alias and exact-lookup strengths are `skip_blocked: shadow_only_reason`, and an active System One rerank slot is `decide_rerank_slot`. `prepareRerankGate` (the stage) runs only when `search.reranker.gate` is not `off`, alongside the reranker call: it reads `lookupAliasHop` and `structuralExactLookup` once, grades, reads rank-1's page tier through `stampPageTrust` on a copy, and returns `meta.rerank_gate` (`mode`, `eligible`/`ineligible_reason` — reranker off, egress denied, no candidates — `grade`, `reason`, `top_cosine`, `gap`, `candidates`, `would_skip`, `skip_blocked`, `provider_called`) plus the lookups, which `sizeReturnPool` applies (`applyAliasHopLookup`, `applyExactLookupHits`) instead of looking up again. `shadow` results, provider payloads and lookup counts are identical to `off`. Under `on` `rerankAndPin` awaits the grade first: `would_skip` skips the provider call, keeps fused order through the reranker's own `topNOut` slice (`sliceTopNOut`, shared with `applyReranker`), runs the feedback stage on fused scores, does not fire the relational rerank pin, and stamps `skipped: true` with `provider_called: false`; nothing goes into `degraded[]` (a deliberate skip, not `reranker_skipped`), and `--explain` prints `rerank skipped (gate: <reason>)`. Pinned by `test/search/rerank-gate-grade.test.ts`, `test/search/rerank-gate-hybrid.test.ts` (both engines), `test/search/rerank-gate-knobs.test.ts`, `test/search/rerank-gate-telemetry.test.ts` (both engines), `test/search/rerank-gate-skip.test.ts` (`on`, both engines; fixture in `test/helpers/rerank-gate-fixture.ts`) and the gate case in `test/search/relational-rerank-pin-hybrid.serial.test.ts` (no pin, no autocut under a skip).+- `src/core/search/crag.ts` + `src/core/search/hybrid/rerank-gate.ts` — the CRAG retrieval-confidence grade on the final list (`gradeRetrievalConfidence`, read by the `query` op's `crag` meta and escalation) and the W3 rerank gate's PRE-rerank grade. `gradePreRerank` is pure and reads the deduped candidates in fused order plus the identity lookups, never mutating them: strong is exactly one exact-lookup page, else exactly one full-query alias page, else a full-title identity at rank 1 (normalized title equals the normalized query; a phrase inside a longer title is not identity), else `high_vector_match` (rank-1 raw cosine ≥ `search.evidence_cosine_floor`) whose gap over the best cosine of a DIFFERENT page (image rows excluded; rank-1's own chunks never count) is at least δ (`search.reranker.gate_min_gap`, 0.05). More than one identity page, or a single-token alias hop that would move rank 1, is `identity_ambiguous`; multimodal queries and image rows are never strong; `applyRerankGateTrust` demotes a strong page below `max(caller min_trust, unknown)` to `below_trust_floor`. `RERANK_GATE_SKIP_REASONS` (only `high_vector_match`) decides `would_skip`; title, alias and exact-lookup strengths are `skip_blocked: shadow_only_reason`, and an active System One rerank slot is `decide_rerank_slot`. `prepareRerankGate` (the stage) runs only when `search.reranker.gate` is not `off`, alongside the reranker call: it reads `lookupAliasHop` and `structuralExactLookup` once, grades, reads rank-1's page tier through `stampPageTrust` on a copy, and returns `meta.rerank_gate` (`mode`, `eligible`/`ineligible_reason` — reranker off, egress denied, no candidates — `grade`, `reason`, `top_cosine`, `gap`, `candidates`, `would_skip`, `skip_blocked`, `provider_called`) plus the lookups, which `sizeReturnPool` applies (`applyAliasHopLookup`, `applyExactLookupHits`) instead of looking up again. `shadow` results, provider payloads and lookup counts are identical to `off`. Pinned by `test/search/rerank-gate-grade.test.ts`, `test/search/rerank-gate-hybrid.test.ts` (both engines), `test/search/rerank-gate-knobs.test.ts`, `test/search/rerank-gate-telemetry.test.ts` (both engines).- `src/core/search/evidence-delivery.ts` — the `return_unit` evidence assembler (default `auto`: conversation pages by type or `chat/`/`conversations/` slug come back whole under `search.return_budget_conversation` (24,000), every other hit is its unchanged chunk; `effectivePlan` skips the stage when an implied `auto` sees no conversation hit, so that path and `chunk` stay byte-identical). `resolveEvidencePlan` validates `return_unit` / `return_window` (invalid_params naming the allowed values and an example), reads `search.return_unit` / `think.return_unit`, `search.return_window`, `search.return_budget_default` (6,000), `search.return_budget_conversation` (24,000) and clamps remote budgets to `search.return_budget_max_remote` (32,000, reported). Snippet precedence: explicit `snippet_chars` > explicit `return_unit` > subagent default cap > config unit. `deliverEvidence` groups hits by page_id (one block per page at its best rank), makes ONE `engine.getChunkWindows` call (re-authorizes every page; unauthorized pages are dropped, never served from hit text), builds the page text from the stored body sanitized whole and passed through `credentialSafeProjection` before slicing (`pageEvidenceText`: compiled truth + serializer timeline sentinel + timeline; frontmatter excluded; private-key spans become newline-padded `<REDACTED:private_key_pem>` tokens, the same text the chunkers cut from), locates the hit chunks in it (`locateChunks`: exact, then whitespace-insensitive, since the chunker trims and folds whitespace), cuts `window` / `section` (ATX headings outside code fences, or conversation rounds detected structurally, never by page type) / `page` / `auto` (fenced-code hits are placed by their code minus the chunker's synthesized header), counts tokens as the sum of per-line cl100k counts, reserves each page's matching span before enriching by rank, caps blocks at 60,000 characters, redacts secrets before final accounting, and returns NEW rows with `delivered` plus a `delivery` meta. The plan records `budgetExplicit` (the caller passed the budget) and the resolved `packing` (`search.auto_packing` or the library override); `capEngaged` (unit `auto`, explicit budget, packing not `off`) routes allocation to `allocateCapped`: global rank one first (cut with `EVIDENCE_CUT_MARKER` when it alone exceeds the budget), the rank-order prefix of other non-conversation chunks that fits (rest `budget_note`), then conversations by `cap_only` (floors, then enrichment), `breadth_capped` (longest prefix whose title + floor + `return_window` target window fits; rest `breadth_cap`) or `depth_first` (each session grown in turn); nothing spills. `capEvidenceToBudget` recounts title + `chunk_text` at the final boundary (after redaction and `capDeliveredSnippets`, whose marker is paid from the row's own allocation) and rewrites `budget_used`. Without an explicit budget none of this runs and the bytes are the pre-cap path's. Fetch failure/timeout (5 s) falls back to the hit chunk only for live hits. `assembleEvidenceForHits` / op `assemble_evidence` deliver the exact evidence `query` returns for a frozen `(source_id, slug, chunk_id)` list, `effective_date` included (`applyEffectiveDate`, the live rows' normalizer); `evidenceFingerprint` hashes it (gbrain-evals E1/E3 parity). With `search.evidence_date_header` on (`plan.dateHeader`), each block (including `auto` passthrough chunks) starts with its one-line date header from `evidence-date.ts`, reserved in the block floor like the title, counted in `delivered.tokens`, with spans shifted past it and `delivery.date_header: true`; a failed date read renders `unknown` and adds `date_header_unavailable`. Normative spec: `docs/evidence-delivery.md`. Tests: `test/evidence-delivery.test.ts`, `test/evidence-delivery-golden.test.ts`, `test/e2e/evidence-delivery-leak.test.ts`, `test/e2e/evidence-delivery-parity.test.ts`; bench `scripts/bench-evidence-delivery.ts`.- `src/core/search/page-rank-cut.ts` — W5 page-unit ranking cut (default off): with `return_unit: page`, a caller budget and `search.page_rank_budget_ratio` set, `resolveEvidencePlan` stores `rankCut` (ratio × budget) on the plan; `search`/`query`/`recall` pass it as `HybridSearchOpts.pageRankCut`, and `applyPageRankCut` folds `min(mode tokenBudget, cut)` into the resolved knobs in both the inner request and the cache resolver. `meta.page_rank_cut` reports ratio, caller budget, mode cut, applied cut, candidates and kept. Tests: `test/search/page-rank-cut.test.ts` (both engines).diff --git a/docs/guides/search-modes.md b/docs/guides/search-modes.mdindex d2f1650ed5..c9d95d3c69 100644--- a/docs/guides/search-modes.md+++ b/docs/guides/search-modes.md@@ -141,15 +141,10 @@ Several of the knobs deserve a sentence:records the grade in the response's `rerank_gate` metadata, on the`--explain` header and in `gbrain search stats`, and still reranks: resultsare identical to `off`. Use it to see how often the reranker is paying for- an answer retrieval already found. `on` skips the cross-encoder when the- grade is a strong vector match (title, alias and exact-lookup strengths stay- shadow-only until they are measured on a corpus that has them, and the gate- never skips while the System One rerank slot is on): results keep their- fused order, cut to the reranker's own output size, the relational rerank- pin does not fire, and `rerank_gate.skipped` says so. A skip is a deliberate- optimization, so it is not listed in `degraded`; `--explain` prints- "rerank skipped (gate: high_vector_match)". It stays off until the eval- shows no loss. The floor and δ are part of the cache key. **Say to your agent:** *"Show me how often my searches would not need+ an answer retrieval already found. No mode skips the reranker: on the+ memory-proof dev sets no question's top cosine reached 0.8 with voyage-4+ embeddings, and the reranker changed about half of the delivered evidence.+ The floor and δ are part of the cache key. **Say to your agent:** *"Show me how often my searches would not needthe reranker"* (no skill backs this; your agent runs`gbrain config set search.reranker.gate shadow`, later`gbrain search stats`, and `gbrain config set search.reranker.gate off`diff --git a/src/commands/search.ts b/src/commands/search.tsindex 9fbf2969e1..ed9dd4394f 100644--- a/src/commands/search.ts+++ b/src/commands/search.ts@@ -206,7 +206,7 @@ async function runStatsSubcommand(engine: BrainEngine, args: string[]): Promise<total_budget_dropped: 'sum of results dropped because the call exceeded its tokenBudget',graph_signals_enabled: 'whether graph_signals is on for the active mode (or via search.graph_signals override)',graph_signals_failures_count: 'count of fail-open events in the JSONL audit over the window',- rerank_gate_would_skip_rate: 'rerank_gate.would_skip / rerank_gate.graded — fraction of graded searches whose pre-rerank grade was strong for a skip reason (search.reranker.gate shadow or on); rerank_gate.skipped counts actual skips under on',+ rerank_gate_would_skip_rate: 'rerank_gate.would_skip / rerank_gate.graded — fraction of graded searches whose pre-rerank grade was strong for a skip reason (search.reranker.gate shadow)',},},}, null, 2));@@ -271,7 +271,6 @@ function printRerankGateSection(g: RerankGateStats): void {console.log(' Rerank gate:');console.log(` graded: ${g.graded} of ${g.eligible} eligible`);console.log(` would skip: ${g.would_skip} (${(g.would_skip_rate * 100).toFixed(1)}%)`);- if (g.skipped > 0) console.log(` skipped: ${g.skipped}`);console.log(` reranker calls: ${g.provider_calls}`);for (const [reason, count] of Object.entries(g.by_reason).sort((a, b) => b[1] - a[1])) {console.log(` ${reason.padEnd(20)} ${count}`);diff --git a/src/core/ops/search.ts b/src/core/ops/search.tsindex f6c02018f1..d1194c72e4 100644--- a/src/core/ops/search.ts+++ b/src/core/ops/search.ts@@ -1270,7 +1270,7 @@ const search_stats: Operation = {total_budget_dropped: 'sum of results dropped because the call exceeded its tokenBudget',graph_signals_enabled: 'whether graph_signals is on for the active mode (or via search.graph_signals override)',graph_signals_failures_count: 'count of fail-open events in the JSONL audit over the window',- rerank_gate_would_skip_rate: 'rerank_gate.would_skip / rerank_gate.graded — fraction of graded searches whose pre-rerank grade was strong for a skip reason (search.reranker.gate shadow or on); rerank_gate.skipped counts actual skips under on',+ rerank_gate_would_skip_rate: 'rerank_gate.would_skip / rerank_gate.graded — fraction of graded searches whose pre-rerank grade was strong for a skip reason (search.reranker.gate shadow)',},},};diff --git a/src/core/search/crag.ts b/src/core/search/crag.tsindex 733be1fed5..3d1e0b424f 100644--- a/src/core/search/crag.ts+++ b/src/core/search/crag.ts@@ -283,14 +283,10 @@ export function confidenceRank(level: RetrievalConfidence): number {// boost and the stamped raw cosine.// ----------------------------------------------------------------------------/**- * `search.reranker.gate`: off (no grade), shadow (grade + stamp- * `meta.rerank_gate`, still rerank) or on (a `would_skip` grade skips the- * cross-encoder).- */-export type RerankGateMode = 'off' | 'shadow' | 'on';+/** `search.reranker.gate`: off (no grade) or shadow (grade + stamp `meta.rerank_gate`, still rerank). */+export type RerankGateMode = 'off' | 'shadow';-export const RERANK_GATE_MODES: ReadonlyArray<RerankGateMode> = Object.freeze(['off', 'shadow', 'on']);+export const RERANK_GATE_MODES: ReadonlyArray<RerankGateMode> = Object.freeze(['off', 'shadow']);export const DEFAULT_RERANK_GATE: RerankGateMode = 'off';diff --git a/src/core/search/explain-formatter.ts b/src/core/search/explain-formatter.tsindex 1c70af083a..71112b4fd2 100644--- a/src/core/search/explain-formatter.ts+++ b/src/core/search/explain-formatter.ts@@ -155,7 +155,6 @@ export function formatDegradedSummary(degraded: HybridSearchMeta['degraded'] | u*/export function formatRerankGateSummary(gate: HybridSearchMeta['rerank_gate'] | undefined): string | null {if (!gate) return null;- if (gate.skipped) return `rerank skipped (gate: ${gate.reason})`;if (!gate.eligible) return `rerank gate (${gate.mode}): not graded (${gate.ineligible_reason})`;const signal = [gate.top_cosine !== undefined ? `cosine ${fmt(gate.top_cosine)}` : null,diff --git a/src/core/search/hybrid/rank.ts b/src/core/search/hybrid/rank.tsindex 7e4b79fd23..08131a58ed 100644--- a/src/core/search/hybrid/rank.ts+++ b/src/core/search/hybrid/rank.ts@@ -15,7 +15,7 @@ import { type PostFusionOpts, RRF_K, cosineReScore, resolveWalkDedupCap, rrfFusiimport { type RelationalEvidenceSlotDecision, ensureRelationalEvidenceSlot } from '../relational-recall.ts';import { type RelationalRerankPinDecision, pinRelationalRows } from '../relational-rerank-pin.ts';import { applyFeedbackStage } from '../feedback-boost.ts';-import { type RerankFailedReason, type RerankPassThroughReason, type RerankSkipReason, applyReranker, sliceTopNOut } from '../rerank.ts';+import { type RerankFailedReason, type RerankPassThroughReason, type RerankSkipReason, applyReranker } from '../rerank.ts';import type { RerankMeta } from '../../ai/gateway.ts';import { applyEvidenceGate, recordRerankReceipts, startRerankShadow } from '../decide-stage.ts';import { rerankEgressDenied } from '../decide-retrieval.ts';@@ -289,14 +289,8 @@ export async function rerankAndPin(// W3 rerank gate (no-op under `off`): grades a read-only view of `deduped`// and reads the identity tiers without applying them, alongside the// reranker call. The reranker's input is unchanged.- // Under `on` the grade comes first: a `would_skip` grade (never with the- // System One rerank slot on) skips the provider call and keeps fused order- // through the reranker's own topNOut slice.const gatePending = prepareRerankGate(req, { deduped, rerankerOpts, egressDenied, exactLookupOpts, multimodal });- const gateSkip = resolvedMode.reranker_gate === 'on' && (await gatePending).meta?.would_skip === true;- const reranked = gateSkip- ? sliceTopNOut(deduped, rerankerOpts.topNOut)- : rerankerOpts.enabled && !egressDenied+ const reranked = rerankerOpts.enabled && !egressDenied? await applyReranker(query, deduped, {...(rerankerOpts as any),...(s1?.effective === 'on' ? { timeoutMs: Math.max(1, Math.min(rerankerOpts.timeoutMs ?? resolvedMode.reranker_timeout_ms, req.decide!.budget.remaining())) } : {}),@@ -311,15 +305,12 @@ export async function rerankAndPin(}): deduped;const gate = await gatePending;- const rerankGate: RerankGateMeta | undefined = gateSkip- ? { ...gate.meta!, skipped: true }- : gate.meta?.eligible+ const rerankGate: RerankGateMeta | undefined = gate.meta?.eligible? { ...gate.meta, provider_called: s1Failure !== 'no_key' }: gate.meta;- const rerankerRan = !gateSkip && reranked !== deduped;if (s1 && rerankerOpts.enabled) recordRerankReceipts(req.decide, query, reranked.slice(0, rerankerOpts.topNIn).filter((r) => s1Failure !== undefined || r.rerank_score !== undefined), s1Meta, s1Failure);if (s1Shadow) await s1Shadow(reranked);- const ordered = await applyFeedbackStage(engine, reranked, { reranked: rerankerRan });+ const ordered = await applyFeedbackStage(engine, reranked, { reranked: reranked !== deduped });// Ranker wave (R1 receipt) — relational-arm rows bypass reranker DEMOTION:// re-pinned above the reranked text rows in fused order, bounded by@@ -328,7 +319,7 @@ export async function rerankAndPin(// order already carries the arm) and never for image modality (the arm is// not fused there). Contract + tie policy: relational-rerank-pin.ts.let relationalRerankPin: RelationalRerankPinDecision | undefined;- const rerankPinned = rerankerRan && effectiveModality !== 'image'+ const rerankPinned = reranked !== deduped && effectiveModality !== 'image'? pinRelationalRows(ordered, relationalList, { max: resolvedMode.relational_rerank_pin, fusedOrder: deduped, onPin: (d) => { relationalRerankPin = d; } }): ordered;return { rerankPinned, relationalRerankPin, rerankGate, identityLookups: gate.lookups };diff --git a/src/core/search/hybrid/rerank-gate.ts b/src/core/search/hybrid/rerank-gate.tsindex 7da383ca9f..b8beeb4be3 100644--- a/src/core/search/hybrid/rerank-gate.ts+++ b/src/core/search/hybrid/rerank-gate.ts@@ -43,8 +43,6 @@ export interface RerankGateMeta {would_skip: boolean;/** Why a strong grade would not skip: a shadow-only reason (A57) or the System One rerank slot. */skip_blocked?: 'shadow_only_reason' | 'decide_rerank_slot';- /** `on` only: the gate skipped the cross-encoder (a deliberate skip, never in `degraded[]`). */- skipped?: true;/** A reranker provider call was made for this request. */provider_called: boolean;}diff --git a/src/core/search/mode.ts b/src/core/search/mode.tsindex c192a04b57..83d231457a 100644--- a/src/core/search/mode.ts+++ b/src/core/search/mode.ts@@ -214,9 +214,9 @@ export interface ModeBundle {/*** W3 — confidence-gated reranking (crag.ts `gradePreRerank`). `off` never* grades; `shadow` grades the deduped candidates before the cross-encoder,- * stamps `meta.rerank_gate` and still reranks (results identical to `off`);- * `on` skips the cross-encoder on a `would_skip` grade (`skipped: true`).- * Off in every bundle; per-call rerankGate → config → bundle; `rrg=`.+ * stamps `meta.rerank_gate` and still reranks (results identical to `off`).+ * `off` in every bundle. Override: per-call HybridSearchOpts.rerankGate →+ * `search.reranker.gate` → bundle. knobsHash part `rrg=`.*/reranker_gate: RerankGateMode;/**diff --git a/src/core/search/modes-report.ts b/src/core/search/modes-report.tsindex c9aedfbb1c..f654e22d61 100644--- a/src/core/search/modes-report.ts+++ b/src/core/search/modes-report.ts@@ -39,7 +39,7 @@ export const KNOB_DESCRIPTIONS: Record<keyof ModeBundle, string> = {// v0.46.15 retrieval wave knobsevidence_cosine_floor: 'Cosine floor for evidence high_vector_match; also decides the rerank gate grade (0..1)',// W3 confidence-gated reranking- reranker_gate: 'Confidence-gated reranking: off; shadow (grade before the reranker, stamp meta.rerank_gate, still rerank); on (a strong high_vector_match grade skips the reranker)',+ reranker_gate: 'Confidence-gated reranking: off, or shadow (grade before the reranker, stamp meta.rerank_gate, still rerank)',reranker_gate_min_gap: 'Rerank gate δ: cosine margin rank-1 needs over the best other page to count as a strong vector match (0..1, 0.05 default)',autocut_min_top: 'Weak-top floor — autocut no-ops when the top score is below this (0 disables)',// v0.36 cross-modal knobs (D3 registry)diff --git a/src/core/search/rerank.ts b/src/core/search/rerank.tsindex 4fa6a33a71..3eb03ffaf0 100644--- a/src/core/search/rerank.ts+++ b/src/core/search/rerank.ts@@ -255,10 +255,8 @@ export async function applyReranker(if (rerankMeta) {try { opts.onMeta?.(rerankMeta); } catch { /* caller hook must never break search */ }}- return sliceTopNOut([...reorderedHead, ...tail], opts.topNOut);-}--/** The reranker's output slice; the rerank gate's skip applies the same one. */-export function sliceTopNOut(results: SearchResult[], topNOut: number | null): SearchResult[] {- return topNOut !== null && topNOut > 0 ? results.slice(0, topNOut) : results;+ const combined = [...reorderedHead, ...tail];+ return opts.topNOut !== null && opts.topNOut > 0+ ? combined.slice(0, opts.topNOut)+ : combined;}diff --git a/src/core/search/telemetry.ts b/src/core/search/telemetry.tsindex 9e82274efc..12c89e6452 100644--- a/src/core/search/telemetry.ts+++ b/src/core/search/telemetry.ts@@ -91,7 +91,6 @@ export function rerankGateCounters(gate: NonNullable<HybridSearchMeta['rerank_gaif (!gate.eligible) return [`ineligible:${gate.ineligible_reason ?? 'unknown'}`];const out = ['eligible', 'graded', `reason:${gate.reason ?? 'unknown'}`];if (gate.would_skip) out.push('would_skip');- if (gate.skipped) out.push('skipped');if (gate.provider_called) out.push('provider_calls');return out;}@@ -498,8 +497,6 @@ export interface RerankGateStats {would_skip: number;/** would_skip / graded (0 when nothing was graded). */would_skip_rate: number;- /** `on` only: searches where the gate skipped the cross-encoder. */- skipped: number;provider_calls: number;/** Graded searches by grade reason (strong and not-strong reasons). */by_reason: Record<string, number>;@@ -508,7 +505,7 @@ export interface RerankGateStats {}function emptyRerankGateStats(): RerankGateStats {- return { eligible: 0, graded: 0, would_skip: 0, would_skip_rate: 0, skipped: 0, provider_calls: 0, by_reason: {}, ineligible: {} };+ return { eligible: 0, graded: 0, would_skip: 0, would_skip_rate: 0, provider_calls: 0, by_reason: {}, ineligible: {} };}/** Fold one reserved rerank-gate row into the section. */@@ -519,7 +516,7 @@ function addRerankGateRow(stats: RerankGateStats, counter: string, count: number} else if (counter.startsWith('ineligible:')) {const k = counter.slice('ineligible:'.length);stats.ineligible[k] = (stats.ineligible[k] ?? 0) + count;- } else if (counter === 'eligible' || counter === 'graded' || counter === 'would_skip' || counter === 'skipped' || counter === 'provider_calls') {+ } else if (counter === 'eligible' || counter === 'graded' || counter === 'would_skip' || counter === 'provider_calls') {stats[counter] += count;}}diff --git a/test/helpers/rerank-gate-fixture.ts b/test/helpers/rerank-gate-fixture.tsdeleted file mode 100644index 037a341ee7..0000000000--- a/test/helpers/rerank-gate-fixture.ts+++ /dev/null@@ -1,110 +0,0 @@-/**- * W3 rerank gate fixture shared by test/search/rerank-gate-hybrid.test.ts- * (shadow) and test/search/rerank-gate-skip.test.ts (on): seven queries, one- * per grade outcome, a deterministic query embedder and a stub reranker that- * reverses fused order (so a skipped or reordered input shows), with counters- * on the alias-table and page reads.- */-import type { BrainEngine } from '../../src/core/engine.ts';-import type { RerankInput, RerankResult } from '../../src/core/ai/gateway.ts';-import { hybridSearch } from '../../src/core/search/hybrid.ts';-import { basisEmbedding } from '../../src/eval/deterministic-embed.ts';-import type { HybridSearchMeta, SearchResult } from '../../src/core/types.ts';-import { installFixtureChunks } from './page-projection.ts';--export const DIM = 1536;--/** Unit vector with cosine `cos` to basis `dim` and 0 to every other fixture dim. */-function leaning(cos: number, dim: number, privateDim: number): Float32Array {- const e = new Float32Array(DIM);- e[dim] = cos;- e[privateDim] = Math.sqrt(1 - cos * cos);- return e;-}--export const QUERY_DIM: Record<string, number> = {- 'orbital period of the gold probe': 12,- 'tidal locking near twins': 13,- 'Acme Widget': 14,- 'the hall': 15,- 'hall of light': 16,- 'notes/gold-probe': 12,- 'magnetar spin rate': 17,-};--export const EXPECTED: Record<string, { grade: 'strong' | 'not_strong'; reason: string; would_skip: boolean; skip_blocked?: string }> = {- 'orbital period of the gold probe': { grade: 'strong', reason: 'high_vector_match', would_skip: true },- 'tidal locking near twins': { grade: 'not_strong', reason: 'gap_below_min', would_skip: false },- 'Acme Widget': { grade: 'strong', reason: 'exact_lookup', would_skip: false, skip_blocked: 'shadow_only_reason' },- 'the hall': { grade: 'not_strong', reason: 'identity_ambiguous', would_skip: false },- 'hall of light': { grade: 'strong', reason: 'alias_hit', would_skip: false, skip_blocked: 'shadow_only_reason' },- 'notes/gold-probe': { grade: 'strong', reason: 'exact_lookup', would_skip: false, skip_blocked: 'shadow_only_reason' },- 'magnetar spin rate': { grade: 'not_strong', reason: 'below_trust_floor', would_skip: false },-};--export async function seed(engine: BrainEngine): Promise<void> {- const page = async (slug: string, title: string, chunks: Array<[string, Float32Array]>) => {- await engine.putPage(slug, { type: 'note', title, compiled_truth: chunks.map(([t]) => t).join('\n\n') });- await installFixtureChunks(engine, slug, chunks.map(([text, embedding], i) => ({- chunk_index: i, chunk_text: text, chunk_source: 'compiled_truth' as const, embedding, token_count: 12,- })));- };- await page('notes/gold-probe', 'Gold Probe', [['the orbital period of the gold probe is ninety minutes', basisEmbedding(12, DIM)]]);- await page('notes/decoy-one', 'Decoy One', [['an orbital period table for other probes', leaning(0.6, 12, 700)]]);- await page('notes/decoy-two', 'Decoy Two', [['gold mining notes, unrelated probe', leaning(0.5, 12, 701)]]);- await page('notes/twin-a', 'Twin A', [- ['tidal locking near twins: the inner pair', leaning(0.95, 13, 702)],- ['tidal locking near twins: the second half', leaning(0.94, 13, 703)],- ]);- await page('notes/twin-b', 'Twin B', [['tidal locking near twins: the outer pair', leaning(0.93, 13, 704)]]);- await page('companies/acme-widget', 'Acme Widget', [- ['acme widget makes small brass gears', leaning(0.3, 14, 705)],- ['acme widget was founded in a garage', leaning(0.31, 14, 706)],- ]);- await page('notes/acme-widget-review', 'Acme Widget Review', [['a review of the acme widget gearbox', leaning(0.5, 14, 707)]]);- await page('places/the-hall', 'The Great Hall', [['the hall seats four hundred', leaning(0.4, 15, 708)]]);- await page('places/other-hall', 'Other Hall', [['the other hall is closed on mondays', leaning(0.3, 15, 709)]]);- await page('projects/mingtang', 'Mingtang', [['the mingtang ritual building', leaning(0.2, 16, 710)]]);- await page('notes/magnetar', 'Magnetar Notes', [['magnetar spin rate measurements', basisEmbedding(17, DIM)]]);- await page('notes/magnetar-other', 'Pulsar Notes', [['pulsar spin rate measurements', leaning(0.3, 17, 711)]]);- await engine.setPageAliases('places/the-hall', 'default', ['the hall']);- await engine.setPageAliases('places/other-hall', 'default', ['the hall']);- await engine.setPageAliases('projects/mingtang', 'default', ['hall of light']);- await engine.executeRaw("UPDATE pages SET trust_tier = 'external_untrusted' WHERE source_id = 'default' AND slug = 'notes/magnetar'");-}--export interface Run { results: SearchResult[]; meta: HybridSearchMeta; payloads: RerankInput[]; aliasReads: number; pageReads: number }--export async function run(- engine: BrainEngine, query: string, rerankGate: 'off' | 'shadow' | 'on',- { topNOut = null, rerankerEnabled = true }: { topNOut?: number | null; rerankerEnabled?: boolean } = {},-): Promise<Run> {- const payloads: RerankInput[] = [];- let aliasReads = 0;- let pageReads = 0;- const counted = new Proxy(engine, {- get(target, prop, receiver) {- const value = Reflect.get(target, prop, receiver);- if (prop === 'resolveAliases') return (...args: unknown[]) => { aliasReads++; return (value as Function).apply(target, args); };- if (prop === 'getPage') return (...args: unknown[]) => { pageReads++; return (value as Function).apply(target, args); };- return typeof value === 'function' ? value.bind(target) : value;- },- });- let meta: HybridSearchMeta | undefined;- const results = await hybridSearch(counted, query, {- limit: 10,- autocut: false,- rerankGate,- queryEmbedFn: () => basisEmbedding(QUERY_DIM[query], DIM),- onMeta: (m) => { meta = m; },- reranker: {- enabled: rerankerEnabled, topNIn: 30, topNOut,- // Reverse the fused order so a skipped or reordered input would show.- rerankerFn: async (input: RerankInput): Promise<RerankResult[]> => {- payloads.push(structuredClone({ query: input.query, documents: input.documents }) as RerankInput);- return input.documents.map((_, i) => ({ index: input.documents.length - 1 - i, relevanceScore: 1 - i * 0.05 }));- },- },- });- return { results, meta: meta!, payloads, aliasReads, pageReads };-}diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 3f50385367..fb6a628dd0 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -116,7 +116,6 @@ test/repair-frontmatter.test.tstest/scripts/test-stress-postgres.test.tstest/search/page-rank-cut.test.tstest/search/rerank-gate-hybrid.test.ts-test/search/rerank-gate-skip.test.tstest/search/rerank-gate-telemetry.test.tstest/shared-content-freshness.test.tstest/shared-skills-catalog.test.tsdiff --git a/test/search/relational-rerank-pin-hybrid.serial.test.ts b/test/search/relational-rerank-pin-hybrid.serial.test.tsindex 69b1cb9ef5..766f3d5458 100644--- a/test/search/relational-rerank-pin-hybrid.serial.test.ts+++ b/test/search/relational-rerank-pin-hybrid.serial.test.ts@@ -119,19 +119,18 @@ afterAll(async () => {type Run = { results: SearchResult[]; meta: HybridSearchMeta | undefined; slugs: string[] };-async function run(query: string, perCall: { relationalRerankPin?: number; autocut?: boolean; rerankGate?: 'off' | 'shadow' | 'on'; vector?: Float32Array } = {}): Promise<Run> {+async function run(query: string, perCall: { relationalRerankPin?: number; autocut?: boolean } = {}): Promise<Run> {let meta: HybridSearchMeta | undefined;- const { vector, ...rest } = perCall;const results = await hybridSearch(engine, query, {limit: 10,sourceId: 'default',- queryEmbedFn: () => vector ?? queryVector,+ queryEmbedFn: () => queryVector,onMeta: (m) => { meta = m; },// Autocut is OFF in every bundle since rule R2; this file pins the pin's// contract THROUGH autocut (pinned rows survive the cut, text-row autocut// is byte-identical), so it turns autocut on per call explicitly.autocut: true,- ...rest,+ ...perCall,});return { results, meta, slugs: results.map((r) => r.slug) };}@@ -305,32 +304,3 @@ describe('R1 paired shape across every "who invested in" question', () => {expect(offHit1, table).toBe(0);}, 120_000);});--describe('W3 rerank gate on: a skip keeps fused order, so neither the relational pin nor autocut fires', () => {- test('a strong vector grade on the seed company skips the reranker; the same vector with the gate off reranks and pins', async () => {- const seed = RELATIONAL_QUESTIONS.find((q) => q.query === Q)!.seed as string;- const vector = relationalBasisEmbedding(seed, queryVector.length);- const before = rerankCalls.length;- // A topNOut slice makes the skipped list a new array, so only the gate's- // own guard keeps the pin from firing on fused order.- await engine.setConfig('search.reranker.top_n_out', '30');- try {- const gated = await run(Q, { rerankGate: 'on', vector });- expect(rerankCalls.length).toBe(before);- expect(gated.meta?.rerank_gate).toMatchObject({ mode: 'on', grade: 'strong', reason: 'high_vector_match', would_skip: true, skipped: true, provider_called: false });- expect(degradedStages(gated.meta)).toEqual([]);- expect(gated.meta?.relational_rerank_pin).toBeUndefined();- expect(gated.results.some((r) => r.relational_pinned)).toBe(false);- expect(gated.results.some((r) => r.rerank_score !== undefined)).toBe(false);- expect(gated.meta?.autocut).toMatchObject({ applied: false, signal: 'none' });- expect(gated.slugs[0]).toBe(seed);-- const reranked = await run(Q, { rerankGate: 'off', vector });- expect(rerankCalls.length).toBe(before + 1);- expect(reranked.meta?.relational_rerank_pin?.pinned.length).toBeGreaterThan(0);- expect(reranked.results.some((r) => r.relational_pinned)).toBe(true);- } finally {- await engine.unsetConfig('search.reranker.top_n_out');- }- });-});diff --git a/test/search/rerank-gate-grade.test.ts b/test/search/rerank-gate-grade.test.tsindex c240ed5adf..cf300ba94b 100644--- a/test/search/rerank-gate-grade.test.ts+++ b/test/search/rerank-gate-grade.test.ts@@ -147,7 +147,6 @@ describe('parse contracts', () => {test('gate literals only, any case; everything else is unset', () => {expect(normalizeRerankGate(' Shadow ')).toBe('shadow');expect(normalizeRerankGate('off')).toBe('off');- expect(normalizeRerankGate('ON')).toBe('on');for (const v of ['', 'true', 'yes', 1, null, undefined, {}]) expect(normalizeRerankGate(v)).toBeUndefined();});test('δ is a number in [0, 1]', () => {diff --git a/test/search/rerank-gate-hybrid.test.ts b/test/search/rerank-gate-hybrid.test.tsindex 183bd2d4bb..0ccecde314 100644--- a/test/search/rerank-gate-hybrid.test.ts+++ b/test/search/rerank-gate-hybrid.test.ts@@ -12,21 +12,114 @@* Fails when: the gate's lookups mutate or reorder candidates (the alias hop* and exact-lookup tier mutate scores and inject rows), a lookup runs twice,* the grade reads the wrong rank-1 or page, or off starts stamping meta.- * Seams: the deterministic `queryEmbedFn` and a stub `rerankerFn`- * (test/helpers/rerank-gate-fixture.ts); PGLite always, Postgres when- * DATABASE_URL is set.+ * Seams: the deterministic `queryEmbedFn` and a stub `rerankerFn`; PGLite+ * always, Postgres when DATABASE_URL is set.*/import { afterAll, beforeAll, describe, expect, test } from 'bun:test';import type { BrainEngine } from '../../src/core/engine.ts';import { PGLiteEngine } from '../../src/core/pglite-engine.ts';-import { configureGateway, resetGateway, type RerankInput } from '../../src/core/ai/gateway.ts';+import { configureGateway, resetGateway, type RerankInput, type RerankResult } from '../../src/core/ai/gateway.ts';import { hybridSearch } from '../../src/core/search/hybrid.ts';import { basisEmbedding } from '../../src/eval/deterministic-embed.ts';-import type { HybridSearchMeta } from '../../src/core/types.ts';+import type { HybridSearchMeta, SearchResult } from '../../src/core/types.ts';+import { installFixtureChunks } from '../helpers/page-projection.ts';import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';-import { DIM, EXPECTED, run, seed } from '../helpers/rerank-gate-fixture.ts';import { testBackends } from '../helpers/test-backends.ts';+const DIM = 1536;++/** Unit vector with cosine `cos` to basis `dim` and 0 to every other fixture dim. */+function leaning(cos: number, dim: number, privateDim: number): Float32Array {+ const e = new Float32Array(DIM);+ e[dim] = cos;+ e[privateDim] = Math.sqrt(1 - cos * cos);+ return e;+}++const QUERY_DIM: Record<string, number> = {+ 'orbital period of the gold probe': 12,+ 'tidal locking near twins': 13,+ 'Acme Widget': 14,+ 'the hall': 15,+ 'hall of light': 16,+ 'notes/gold-probe': 12,+ 'magnetar spin rate': 17,+};++const EXPECTED: Record<string, { grade: 'strong' | 'not_strong'; reason: string; would_skip: boolean; skip_blocked?: string }> = {+ 'orbital period of the gold probe': { grade: 'strong', reason: 'high_vector_match', would_skip: true },+ 'tidal locking near twins': { grade: 'not_strong', reason: 'gap_below_min', would_skip: false },+ 'Acme Widget': { grade: 'strong', reason: 'exact_lookup', would_skip: false, skip_blocked: 'shadow_only_reason' },+ 'the hall': { grade: 'not_strong', reason: 'identity_ambiguous', would_skip: false },+ 'hall of light': { grade: 'strong', reason: 'alias_hit', would_skip: false, skip_blocked: 'shadow_only_reason' },+ 'notes/gold-probe': { grade: 'strong', reason: 'exact_lookup', would_skip: false, skip_blocked: 'shadow_only_reason' },+ 'magnetar spin rate': { grade: 'not_strong', reason: 'below_trust_floor', would_skip: false },+};++async function seed(engine: BrainEngine): Promise<void> {+ const page = async (slug: string, title: string, chunks: Array<[string, Float32Array]>) => {+ await engine.putPage(slug, { type: 'note', title, compiled_truth: chunks.map(([t]) => t).join('\n\n') });+ await installFixtureChunks(engine, slug, chunks.map(([text, embedding], i) => ({+ chunk_index: i, chunk_text: text, chunk_source: 'compiled_truth' as const, embedding, token_count: 12,+ })));+ };+ await page('notes/gold-probe', 'Gold Probe', [['the orbital period of the gold probe is ninety minutes', basisEmbedding(12, DIM)]]);+ await page('notes/decoy-one', 'Decoy One', [['an orbital period table for other probes', leaning(0.6, 12, 700)]]);+ await page('notes/decoy-two', 'Decoy Two', [['gold mining notes, unrelated probe', leaning(0.5, 12, 701)]]);+ await page('notes/twin-a', 'Twin A', [+ ['tidal locking near twins: the inner pair', leaning(0.95, 13, 702)],+ ['tidal locking near twins: the second half', leaning(0.94, 13, 703)],+ ]);+ await page('notes/twin-b', 'Twin B', [['tidal locking near twins: the outer pair', leaning(0.93, 13, 704)]]);+ await page('companies/acme-widget', 'Acme Widget', [+ ['acme widget makes small brass gears', leaning(0.3, 14, 705)],+ ['acme widget was founded in a garage', leaning(0.31, 14, 706)],+ ]);+ await page('notes/acme-widget-review', 'Acme Widget Review', [['a review of the acme widget gearbox', leaning(0.5, 14, 707)]]);+ await page('places/the-hall', 'The Great Hall', [['the hall seats four hundred', leaning(0.4, 15, 708)]]);+ await page('places/other-hall', 'Other Hall', [['the other hall is closed on mondays', leaning(0.3, 15, 709)]]);+ await page('projects/mingtang', 'Mingtang', [['the mingtang ritual building', leaning(0.2, 16, 710)]]);+ await page('notes/magnetar', 'Magnetar Notes', [['magnetar spin rate measurements', basisEmbedding(17, DIM)]]);+ await page('notes/magnetar-other', 'Pulsar Notes', [['pulsar spin rate measurements', leaning(0.3, 17, 711)]]);+ await engine.setPageAliases('places/the-hall', 'default', ['the hall']);+ await engine.setPageAliases('places/other-hall', 'default', ['the hall']);+ await engine.setPageAliases('projects/mingtang', 'default', ['hall of light']);+ await engine.executeRaw("UPDATE pages SET trust_tier = 'external_untrusted' WHERE source_id = 'default' AND slug = 'notes/magnetar'");+}++interface Run { results: SearchResult[]; meta: HybridSearchMeta; payloads: RerankInput[]; aliasReads: number; pageReads: number }++async function run(engine: BrainEngine, query: string, rerankGate: 'off' | 'shadow'): Promise<Run> {+ const payloads: RerankInput[] = [];+ let aliasReads = 0;+ let pageReads = 0;+ const counted = new Proxy(engine, {+ get(target, prop, receiver) {+ const value = Reflect.get(target, prop, receiver);+ if (prop === 'resolveAliases') return (...args: unknown[]) => { aliasReads++; return (value as Function).apply(target, args); };+ if (prop === 'getPage') return (...args: unknown[]) => { pageReads++; return (value as Function).apply(target, args); };+ return typeof value === 'function' ? value.bind(target) : value;+ },+ });+ let meta: HybridSearchMeta | undefined;+ const results = await hybridSearch(counted, query, {+ limit: 10,+ autocut: false,+ rerankGate,+ queryEmbedFn: () => basisEmbedding(QUERY_DIM[query], DIM),+ onMeta: (m) => { meta = m; },+ reranker: {+ enabled: true, topNIn: 30, topNOut: null,+ // Reverse the fused order so a skipped or reordered input would show.+ rerankerFn: async (input: RerankInput): Promise<RerankResult[]> => {+ payloads.push(structuredClone({ query: input.query, documents: input.documents }) as RerankInput);+ return input.documents.map((_, i) => ({ index: input.documents.length - 1 - i, relevanceScore: 1 - i * 0.05 }));+ },+ },+ });+ return { results, meta: meta!, payloads, aliasReads, pageReads };+}+for (const backend of testBackends()) {describe(`${backend}: rerank gate shadow`, () => {let engine: BrainEngine;diff --git a/test/search/rerank-gate-knobs.test.ts b/test/search/rerank-gate-knobs.test.tsindex b8965957e0..e121dea72c 100644--- a/test/search/rerank-gate-knobs.test.ts+++ b/test/search/rerank-gate-knobs.test.ts@@ -35,7 +35,6 @@ describe('rerank gate knobs', () => {test('config parse: recognized values set the override, anything else falls through', () => {expect(loadOverridesFromConfig({ 'search.reranker.gate': 'SHADOW' }).reranker_gate).toBe('shadow');- expect(loadOverridesFromConfig({ 'search.reranker.gate': 'on' }).reranker_gate).toBe('on');expect(loadOverridesFromConfig({ 'search.reranker.gate': 'maybe' }).reranker_gate).toBeUndefined();expect(loadOverridesFromConfig({ 'search.reranker.gate_min_gap': '0' }).reranker_gate_min_gap).toBe(0);expect(loadOverridesFromConfig({ 'search.reranker.gate_min_gap': '2' }).reranker_gate_min_gap).toBeUndefined();@@ -51,10 +50,9 @@ describe('rerank gate knobs', () => {test('knobsHash changes with the gate, δ and the floor; explicit defaults hash as the default', () => {const base = knobsHash(resolveSearchMode({ mode: 'balanced' }));const shadow = knobsHash(resolveSearchMode({ mode: 'balanced', perCall: { reranker_gate: 'shadow' } }));- const on = knobsHash(resolveSearchMode({ mode: 'balanced', perCall: { reranker_gate: 'on' } }));const gap = knobsHash(resolveSearchMode({ mode: 'balanced', overrides: { reranker_gate_min_gap: 0 } }));const floor = knobsHash(resolveSearchMode({ mode: 'balanced', overrides: { evidence_cosine_floor: 0.75 } }));- expect(new Set([base, shadow, on, gap, floor]).size).toBe(5);+ expect(new Set([base, shadow, gap, floor]).size).toBe(4);expect(knobsHash(resolveSearchMode({ mode: 'balanced', overrides: { reranker_gate: 'off', reranker_gate_min_gap: 0.05, evidence_cosine_floor: 0.8 } }))).toBe(base);});});@@ -72,7 +70,5 @@ describe('rerank gate --explain line', () => {.toBe('rerank gate (shadow): strong alias_hit — would rerank (shadow_only_reason) (3 candidates)');expect(formatRerankGateSummary({ mode: 'shadow', eligible: false, ineligible_reason: 'egress_denied', candidates: 3, would_skip: false, provider_called: false })).toBe('rerank gate (shadow): not graded (egress_denied)');- expect(formatRerankGateSummary({ mode: 'on', eligible: true, grade: 'strong', reason: 'high_vector_match', top_cosine: 0.91, gap: 0.12, candidates: 9, would_skip: true, skipped: true, provider_called: false }))- .toBe('rerank skipped (gate: high_vector_match)');});});diff --git a/test/search/rerank-gate-skip.test.ts b/test/search/rerank-gate-skip.test.tsdeleted file mode 100644index e2e9b7f386..0000000000--- a/test/search/rerank-gate-skip.test.ts+++ /dev/null@@ -1,124 +0,0 @@-/**- * W3 stage 2 — `search.reranker.gate: on` through hybridSearch: a- * `would_skip` grade skips the cross-encoder; every other grade reranks- * exactly as `off` does.- *- * Protects: a skip makes no provider call, keeps fused order through the- * reranker's own topNOut slice, stamps `rerank_gate.skipped` with- * `provider_called: false`, adds nothing to `degraded[]` and prints- * "rerank skipped (gate: …)" on --explain; a not-strong grade and the- * shadow-only strengths (exact lookup, alias) rerank with payloads and- * results identical to `off`; an active System One rerank slot blocks the- * skip.- * Fails when: the skip calls the provider, reorders or over-returns rows,- * lands in degraded[], or skips on a reason outside RERANK_GATE_SKIP_REASONS- * or with the decide slot on.- * Seams: test/helpers/rerank-gate-fixture.ts (deterministic embedder, stub- * reverse-order reranker); PGLite always, Postgres when DATABASE_URL is set.- * The relational rerank pin and autocut under a skip are pinned in- * test/search/relational-rerank-pin-hybrid.serial.test.ts.- */-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';-import type { BrainEngine } from '../../src/core/engine.ts';-import { PGLiteEngine } from '../../src/core/pglite-engine.ts';-import { configureGateway, resetGateway } from '../../src/core/ai/gateway.ts';-import { formatResultsExplain } from '../../src/core/search/explain-formatter.ts';-import { hybridSearch } from '../../src/core/search/hybrid.ts';-import { prepareRerankGate } from '../../src/core/search/hybrid/rerank-gate.ts';-import type { HybridRequest } from '../../src/core/search/hybrid/request.ts';-import { resolveSearchMode } from '../../src/core/search/mode.ts';-import { basisEmbedding } from '../../src/eval/deterministic-embed.ts';-import type { SearchResult } from '../../src/core/types.ts';-import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';-import { DIM, EXPECTED, QUERY_DIM, run, seed } from '../helpers/rerank-gate-fixture.ts';-import { testBackends } from '../helpers/test-backends.ts';--const STRONG = 'orbital period of the gold probe';-const rows = (rs: SearchResult[]) => JSON.stringify(rs.map((r) => ({ slug: r.slug, chunk_id: r.chunk_id, score: r.score, rerank_score: r.rerank_score ?? null })));--for (const backend of testBackends()) {- describe(`${backend}: rerank gate on`, () => {- let engine: BrainEngine;- let close: () => Promise<void> = async () => {};-- beforeAll(async () => {- configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: DIM, env: {} });- if (backend === 'pglite') {- const pglite = new PGLiteEngine();- await pglite.connect({});- await pglite.initSchema();- engine = pglite;- close = () => pglite.disconnect();- } else {- const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);- engine = pg.engine;- close = pg.close;- }- await seed(engine);- }, 120_000);-- afterAll(async () => {- resetGateway();- await close();- });-- for (const query of Object.keys(EXPECTED)) {- const skips = EXPECTED[query].would_skip;- test(`${query}: ${skips ? 'skips the reranker and keeps fused order' : 'reranks exactly as off'}`, async () => {- const on = await run(engine, query, 'on');- const off = await run(engine, query, 'off');- expect(on.meta.rerank_gate).toMatchObject({ mode: 'on', eligible: true, ...EXPECTED[query] });- expect((on.meta.degraded ?? []).filter((d) => d.stage.startsWith('rerank'))).toEqual([]);- if (skips) {- const fused = await run(engine, query, 'off', { rerankerEnabled: false });- expect(on.payloads).toHaveLength(0);- expect(on.meta.rerank_gate).toMatchObject({ skipped: true, provider_called: false });- expect(rows(on.results)).toBe(rows(fused.results));- expect(rows(on.results)).not.toBe(rows(off.results));- } else {- expect(on.meta.rerank_gate?.skipped).toBeUndefined();- expect(on.meta.rerank_gate?.provider_called).toBe(true);- expect(on.payloads).toEqual(off.payloads);- expect(JSON.stringify(on.results)).toBe(JSON.stringify(off.results));- }- });- }-- test('a skip applies the reranker topNOut slice', async () => {- const fused = await run(engine, STRONG, 'off', { rerankerEnabled: false });- const on = await run(engine, STRONG, 'on', { topNOut: 2 });- const off = await run(engine, STRONG, 'off', { topNOut: 2 });- expect(fused.results.length).toBeGreaterThan(2);- expect(off.results).toHaveLength(2);- expect(on.results).toHaveLength(2);- expect(on.payloads).toHaveLength(0);- expect(rows(on.results)).toBe(rows(fused.results.slice(0, 2)));- });-- test('--explain names the skip and lists no degradation', async () => {- const on = await run(engine, STRONG, 'on');- const explain = formatResultsExplain(on.results, on.meta);- expect(explain).toContain('rerank skipped (gate: high_vector_match)');- expect(explain).not.toContain('degraded');- });-- test('an active System One rerank slot blocks the skip', async () => {- let deduped: SearchResult[] = [];- await hybridSearch(engine, STRONG, {- limit: 10, rerankGate: 'off', queryEmbedFn: () => basisEmbedding(QUERY_DIM[STRONG], DIM),- reranker: { enabled: false, topNIn: 30, topNOut: null },- onRerankPool: (_pool, d) => { deduped = d.map((r) => ({ ...r })); },- });- expect(deduped.length).toBeGreaterThan(1);- const grade = (effective: 'off' | 'shadow' | 'on') => prepareRerankGate({- engine, query: STRONG, opts: {}, aliasHopOpts: {},- resolvedMode: resolveSearchMode({ mode: 'balanced', perCall: { reranker_gate: 'on' } }),- decide: { policies: { rerank: { effective } } },- } as unknown as HybridRequest, { deduped, rerankerOpts: { enabled: true, topNIn: 30 }, egressDenied: false, exactLookupOpts: {}, multimodal: false });- expect((await grade('off')).meta).toMatchObject({ reason: 'high_vector_match', would_skip: true });- for (const effective of ['shadow', 'on'] as const) {- expect((await grade(effective)).meta).toMatchObject({ reason: 'high_vector_match', would_skip: false, skip_blocked: 'decide_rerank_slot' });- }- });- });-}diff --git a/test/search/rerank-gate-telemetry.test.ts b/test/search/rerank-gate-telemetry.test.tsindex 7c5d22e309..9cb2e127a6 100644--- a/test/search/rerank-gate-telemetry.test.ts+++ b/test/search/rerank-gate-telemetry.test.ts@@ -35,7 +35,6 @@ const gapMiss: Gate = { mode: 'shadow', eligible: true, grade: 'not_strong', reaconst titleOnly: Gate = { mode: 'shadow', eligible: true, grade: 'strong', reason: 'exact_lookup', candidates: 3, would_skip: false, skip_blocked: 'shadow_only_reason', provider_called: true };const noKey: Gate = { ...strongVector, provider_called: false };const off: Gate = { mode: 'shadow', eligible: false, ineligible_reason: 'reranker_off', candidates: 4, would_skip: false, provider_called: false };-const gatedSkip: Gate = { ...strongVector, mode: 'on', skipped: true, provider_called: false };async function flushFrom(engine: BrainEngine, metas: HybridSearchMeta[]): Promise<void> {_resetTelemetryWriterForTest();@@ -75,7 +74,6 @@ for (const backend of testBackends()) {graded: 5,would_skip: 3,would_skip_rate: 3 / 5,- skipped: 0,provider_calls: 4,by_reason: { high_vector_match: 3, gap_below_min: 1, exact_lookup: 1 },ineligible: { reranker_off: 1 },@@ -92,14 +90,7 @@ for (const backend of testBackends()) {test('a gate-off window reads an empty section', async () => {await flushFrom(engine, [meta(), meta()]);const stats = await readSearchStats(engine, { days: 1 });- expect(stats.rerank_gate).toEqual({ eligible: 0, graded: 0, would_skip: 0, would_skip_rate: 0, skipped: 0, provider_calls: 0, by_reason: {}, ineligible: {} });- });-- test('gate on: a skip counts as would_skip and skipped with no provider call', async () => {- await flushFrom(engine, [meta(gatedSkip), meta(gatedSkip), meta({ ...gapMiss, mode: 'on' })]);- const stats = await readSearchStats(engine, { days: 1 });- expect(stats.total_calls).toBe(3);- expect(stats.rerank_gate).toMatchObject({ graded: 3, would_skip: 2, skipped: 2, provider_calls: 1 });+ expect(stats.rerank_gate).toEqual({ eligible: 0, graded: 0, would_skip: 0, would_skip_rate: 0, provider_calls: 0, by_reason: {}, ineligible: {} });});});}