Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(search): W3 rerank gate stage 1 — search.reranker.gate off|shadow, the pre-rerank confidence grade in meta.rerank_gate and search stats (shadow results identical to off)
garrytand3f49c297e44
diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.mdindex 8a36b7eb27..ff8238f72f 100644--- a/docs/architecture/KEY_FILES.md+++ b/docs/architecture/KEY_FILES.md@@ -48,7 +48,7 @@ boundary and add its link here rather than raising the cap.| [Core Persistence (engine graduation)](key-files/core-persistence-graduation.md) | `engine-graduation*.ts`, `graduation-*.ts`, `src/commands/migrate-graduation.ts`, its doctor finding || [Managed sync and persistence stalls](key-files/persistence-stalls.md) | preparation budgets, `claim-phase.ts`, `consumer.ts`, `group-publish.ts`, `journal.ts`, `diagnostics.ts`, `worktree-manifest.ts` || [Core Search (1/2)](key-files/core-search-1.md) | `src/core/search/` through `src/core/search/rerank.ts` |-| [Core Search (2/2)](key-files/core-search-2.md) | `src/core/search/return-policy.ts` through `src/core/search/vector-pool.ts`, the relational arm and multi-hop chain modules, `hub-dampening.ts` |+| [Core Search (2/2)](key-files/core-search-2.md) | `src/core/search/return-policy.ts` through `src/core/search/vector-pool.ts`, the relational arm and multi-hop chain modules, `hub-dampening.ts`, `crag.ts` and the rerank gate || [Core Services (1/3)](key-files/core-services-1.md) | `src/core/advisor/{types,run,render,recommended-set,history,apply,collect-*}.ts` through `src/core/connectors/` || [Core Services (1/3, continued)](key-files/core-services-1-continued.md) | `src/core/context/` through `src/core/context/ipc-path.ts` || [Core Services (2/3)](key-files/core-services-2.md) | `src/core/conversation-parser/` through `src/core/progressive-batch/`, except `src/core/persistence/` |diff --git a/docs/architecture/key-files/commands-5.md b/docs/architecture/key-files/commands-5.mdindex 9e76065c24..7eb270eee5 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` — `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-1.md b/docs/architecture/key-files/core-search-1.mdindex fcba5f6b6a..7b9a45274b 100644--- a/docs/architecture/key-files/core-search-1.md+++ b/docs/architecture/key-files/core-search-1.md@@ -5,7 +5,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/` — Hybrid search: vector + keyword + RRF + multi-query expansion + dedup. `searchKeyword`/`searchKeywordChunks`/`searchVector` apply source-aware ranking at the SQL layer (curated content like `originals/`, `concepts/`, `writing/` outranks bulk content like `<fork>/chat/`, `daily/`, `media/x/`). `searchVector` uses a two-stage CTE so source-boost re-ranking doesn't kill the HNSW index. Hard-exclude prefixes (`test/`, `archive/`, `attachments/`, `.raw/` by default) filter at retrieval, not post-rank. Both gates honor `detail !== 'high'` so temporal queries surface chat pages normally.-- `src/core/search/alias-hop.ts` — the post-rerank alias hop (`applyAliasHop`, re-exported by `hybrid.ts`), the opt-in single-token hop (`applyAliasTokenHop`, #5428) and the exclude contract both identity injections share (`IdentityTierOpts`, `isExcludedIdentity`; `exact-lookup.ts` imports it). Behavior is documented under the `hybrid.ts` entry. Pinned by `test/search/alias-hop.test.ts`, `test/search/alias-token-hop.test.ts`, `test/search/injection-excludes-keyword-boost.test.ts`.+- `src/core/search/alias-hop.ts` — the post-rerank alias hop (`applyAliasHop` = `lookupAliasHop`, the alias-table read, then `applyAliasHopLookup`; `aliasHopCanonicals` is the filtered, ordered, capped canonical list both apply and the rerank gate read; re-exported by `hybrid.ts`), the opt-in single-token hop (`applyAliasTokenHop`, #5428) and the exclude contract both identity injections share (`IdentityTierOpts`, `isExcludedIdentity`; `exact-lookup.ts` imports it). Behavior is documented under the `hybrid.ts` entry. Pinned by `test/search/alias-hop.test.ts`, `test/search/alias-token-hop.test.ts`, `test/search/injection-excludes-keyword-boost.test.ts`.- `src/core/search/alias-normalize.ts` — ONE normalizer shared by the WRITE path (ingest projects frontmatter `aliases:` into `page_aliases`) and the READ path (search matches query against `page_aliases`), so stored aliases can't silently fail to match queries via divergent normalization (same single-source posture as `cjk.ts`). `normalizeAlias(raw)` does NFKC + lowercase + whitespace-collapse + trim + strip one layer of wrapping quotes/brackets; returns `''` for empty (callers MUST skip empty aliases). `normalizeAliasList(value)` coerces a frontmatter scalar / array / comma-list / garbage into a deduped list of normalized non-empty aliases — used by both the ingest projection and the `reindex --aliases` backfill.- `src/core/search/arm-confidence.ts` — arm-confidence-weighted fusion for the keyword arm (`search.keyword_arm_confidence_floor`; `null` = off in every bundle — the pre-registered Cat 13 E2 mechanism FAILED its held-out rule at the calibrated floor 0.6121 (53.0 → 53.0), so the knob ships default off for operators and the receipt is published). `keywordArmConfidence(rows)` reads the strict keyword arm's raw `score` column into a scale-free statistic (`top`, `second`, `margin_ratio`; TypeScript-side — engines still return raw `ts_rank × sourceFactor`, no SQL change); `decideKeywordArmWeight({keywordList, floor, vectorArmVoted, relationalQuery})` down-weights the keyword AND title fusion entries to `KEYWORD_ARM_WEAK_WEIGHT` (0.5) only when the floor is set, the keyword list is non-empty, a text vector arm voted, the query is not relational, and `margin_ratio < floor`; otherwise it emits no weight (byte-identical fusion). It is called from `composeFusionLists` (`fusion-lists.ts`) so the weight lands through the same per-list `weight` primitive as the expansion budget, never a k change. `normalizeKeywordArmConfidenceFloor` is the ONE range contract (number in `(0, 1]` or a string parsing to one; `null`/`false`/`off` → `null`; anything else → `undefined` = fall through), shared by `mode.ts:loadOverridesFromConfig` and both per-call seams in `hybrid.ts`. The decision (`{top, second, margin_ratio, downweighted}`) is surfaced as `HybridSearchMeta.keyword_arm_confidence` even with the floor off, so a calibration run can pick a floor from per-probe receipts; knobs-hash part `kacf=`. Pinned by `test/search/arm-confidence.test.ts` (pure contract) and `test/search/arm-confidence-hybrid.test.ts` (hermetic PGLite: a weak keyword arm is down-weighted only with the floor set; off is byte-identical).@@ -34,7 +34,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `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`. Both identity injections (alias hop and exact-lookup tier) take one `IdentityTierOpts` built once per request and skip any slug `isExcludedIdentity` rejects: caller `exclude_slugs` plus the resolved prefix excludes (`resolveHardExcludes`: defaults, `GBRAIN_SEARCH_EXCLUDE`, per-call prefixes, minus `include_slug_prefixes`), on all three return paths. Opt-in single-token hop (#5428; per-call `aliasTokenHop` or brain config `search.alias_token_hop=true`, read in the mode snapshot): when the whole query is not an alias, a query token that is the alias of exactly one person/company identity page (`isIdentityEntity`) moves that page to the front or injects it, at most two pages, order-preserving for the rest. 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. A rejected keyword or title arm fails open and stamps `keyword_arm_failed` / `title_arm_failed` (reason `timeout | provider_error`) in `meta.degraded`, so MCP callers can tell a partial read from a clean miss. In `both` modality `cosineReScore` rescores image-arm rows in the image space (`embedding_image`, multimodal query vector); text rows keep the text column. The intent identity boosts (exact/mentioned title or slug, mentioned alias) run through one `applyIdentityBoosts` closure on the fused path and both keyword-only paths. 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).Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). `hybridSearch` and `hybridSearchCached` are short orchestrators over the named stages in `src/core/search/hybrid/` (next entry); the file keeps the post-fusion boosts, RRF, cosine rescore, the cache-write drainer and the public helpers.-- `src/core/search/hybrid/` — hybridSearch pipeline stages, called in a fixed order so every engine query and provider call happens exactly as before: `request.ts` (`resolveHybridRequest` builds a `HybridRequest` once: mode, embedding column, limits (per-arm pool from `perArmPoolLimit` in `src/core/search/eval-pool-depth.ts`: today's max(2·limit, floor, offset+limit) capped at 100 unless an eval sets `--eval-pool-depth`), intent, `searchOpts`, identity-tier opts, and the accumulators `vectorPoolUnderfill` / `expansionApplied` / `lastResultsCount` / `lastRank1Score` that stages write only as `req.<field>`; `emitHybridMeta`, `applyIdentityBoosts`), `arms.ts` (lexical, relational, modality + expansion, vector arms), `keyword-only.ts` (the no-provider and all-vector-arms-empty return paths; `opts.decide.keywordOnly`, the System One S6 fire retrieval, takes the no-provider path on purpose without the vector-unavailable degraded marker or warning), `rank.ts` (fusion + post-fusion boosts, A2 expansion, rerank + relational pin, identity tiers + adaptive return + autocut + relational slot, main return), `cache-stages.ts` (hybridSearchCached mode resolution, semantic-cache handle, skip gate, hit path; the result cache stays hard-disabled), `degraded.ts`, `effective-modes.ts`. Stages import public helpers back from `hybrid.ts` at call time only (the `exact-lookup.ts` pattern); `hybrid.ts` exports nothing new. Pinned by `test/hybrid-golden.test.ts` (exact `(id, score)`, cold and warm).+- `src/core/search/hybrid/` — hybridSearch pipeline stages, called in a fixed order so every engine query and provider call happens exactly as before: `request.ts` (`resolveHybridRequest` builds a `HybridRequest` once: mode, embedding column, limits (per-arm pool from `perArmPoolLimit` in `src/core/search/eval-pool-depth.ts`: today's max(2·limit, floor, offset+limit) capped at 100 unless an eval sets `--eval-pool-depth`), intent, `searchOpts`, identity-tier opts, and the accumulators `vectorPoolUnderfill` / `expansionApplied` / `lastResultsCount` / `lastRank1Score` that stages write only as `req.<field>`; `emitHybridMeta`, `applyIdentityBoosts`), `arms.ts` (lexical, relational, modality + expansion, vector arms), `keyword-only.ts` (the no-provider and all-vector-arms-empty return paths; `opts.decide.keywordOnly`, the System One S6 fire retrieval, takes the no-provider path on purpose without the vector-unavailable degraded marker or warning), `rank.ts` (fusion + post-fusion boosts, A2 expansion, rerank + relational pin, identity tiers + adaptive return + autocut + relational slot, main return), `cache-stages.ts` (hybridSearchCached mode resolution, semantic-cache handle, skip gate, hit path; the result cache stays hard-disabled), `degraded.ts`, `effective-modes.ts`, `rerank-gate.ts` (the W3 pre-rerank grade; see the `crag.ts` entry in Core Search 2/2). Stages import public helpers back from `hybrid.ts` at call time only (the `exact-lookup.ts` pattern); `hybrid.ts` exports nothing new. Pinned by `test/hybrid-golden.test.ts` (exact `(id, score)`, cold and warm).- `src/core/search/eval-pool-depth.ts` — eval-only candidate pool depth for the System One recall experiment: `setEvalPoolDepth(N)` (N ≤ 300; only `gbrain eval longmemeval --eval-pool-depth` calls it) raises `searchLimitCap()` (the per-arm cap both engines' keyword/vector arms clamp to, default `MAX_SEARCH_LIMIT` 100) and makes every arm fetch N (`perArmPoolLimit`, used by `hybrid/request.ts`). Production depth is unchanged. Tests: `test/eval-pool-depth.test.ts`.diff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.mdindex af4cc5199e..3cc02c560d 100644--- a/docs/architecture/key-files/core-search-2.md+++ b/docs/architecture/key-files/core-search-2.md@@ -3,6 +3,8 @@[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`. 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/evidence-date.ts` — C1 dated evidence blocks: the fixed header grammar (`[observed YYYY-MM-DD|unknown]` for page blocks; `[observed unknown; valid FROM to UNTIL]` for `recall` facts), `pageObservationDate` (effective-date precedence with `event_date` removed and no row-timestamp fallback; mirrors #6020's `resolveObservationDate`, the seam to swap once it lands), `formatBrainDay` from `effective-date.ts` (midnight UTC renders as written, other instants in `brain.timezone`; the one function think's `<page date>` also renders through, while the header's `observed` stays when the text was said, never the content date), `loadPageDateHeaders` (one `pages` read per delivery; only the derived day leaves it) and `evidenceDateHeaderEnabled` (`search.evidence_date_header`, default off). Tests: `test/evidence-date-header.test.ts`.diff --git a/docs/guides/search-modes.md b/docs/guides/search-modes.mdindex 58d3a5d9d8..57b820bf13 100644--- a/docs/guides/search-modes.md+++ b/docs/guides/search-modes.md@@ -40,6 +40,7 @@ and maintenance commands remain available.| `searchLimit` default | 10 | 25 | 50 || `reranker` (cross-encoder) | off | `voyage:rerank-2.5` | `voyage:rerank-2.5` || `autocut` (rerank-cliff cut) | off | off | off |+| `reranker_gate` | off | off | off |The `expansion` row is not decisive for any shipped verb today: `gbrain query`(the only verb that can expand) expands by default in every mode — pass@@ -65,7 +66,7 @@ its model's input/output charges are separate from downstream reading costs.- **`tokenmax`** — no token budget, 50 results by default.Pairs with an expensive downstream model you want fully fed.-Seven of the knobs deserve a sentence:+Several of the knobs deserve a sentence:- **`expansion`** rewrites your query into multiple variants via a cheapLLM call when available (the historical Haiku estimate is roughly $1.50 per@@ -130,6 +131,22 @@ Seven of the knobs deserve a sentence:vector-only matches"* (no skill backs this; your agent runs`gbrain config set search.metadata_boost_gate always`, and`gbrain config set search.metadata_boost_gate lexical` restores the default).+- **`reranker_gate`** (config key `search.reranker.gate`; off in every+ bundle) grades the fused candidates before the cross-encoder runs, from what+ exists before reranking: an exact slug or full-title lookup that finds+ exactly one page, a declared alias that names exactly one page, or a top+ result whose raw cosine is at least `search.evidence_cosine_floor` (0.8) and+ leads the best other page by `search.reranker.gate_min_gap` (δ, 0.05). Image+ queries and pages marked `external_untrusted` never grade strong. `shadow`+ records the grade in the response's `rerank_gate` metadata, on the+ `--explain` header and in `gbrain search stats`, and still reranks: results+ are identical to `off`. Use it to see how often the reranker is paying for+ an answer retrieval already found. The floor and δ are part of the cache+ key. **Say to your agent:** *"Show me how often my searches would not need+ the 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`+ restores the default).- **`keyword_arm_confidence_floor`** (config key`search.keyword_arm_confidence_floor`; off in every bundle) down-weights thekeyword and title arms in the fusion when the keyword arm's top-vs-second@@ -204,7 +221,8 @@ realistic-scale walkthrough live in```bashgbrain search modes # what is running, with per-knob attributiongbrain search modes --reset # clear search.* overrides (mode bundle wins)-gbrain search stats [--days N] # cache hit rate, intent mix, budget drops+gbrain search stats [--days N] # cache hit rate, intent mix, budget drops,+ # rerank gate counts when the gate is ongbrain search tune [--apply] # data-driven recommendationsgbrain search diagnose "<query>" --target <slug># trace where a page surfaces (or fails to)diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 7d15f69540..8042c5d576 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -22,8 +22,8 @@ src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live insrc/core/operations.ts 344 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; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +2 retrieval feedback: feedbackOperations import and spread (ops/feedback.ts); +1 #6007: pageBatchOperations import (spread shares the pages line); +1 P5: wanted_pages area row; +2 C4 pinned questions: questionsOperations import and spread (ops/questions.ts)src/core/pglite-engine.ts 3008 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +5 GBRA-67: readPageSnapshotsBatch delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages delegate (SQL in engine-sql/pages.ts)src/core/postgres-engine.ts 3010 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +23 #6278 PR 1.5: cancelSettleMs() and the settle timer in runUnsafe that discards a reserved connection whose cancel a transaction-mode pooler never completed; +3 #6317 lane 2: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts) and the prepare mark; +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +1 GBRA-69 extract batching: replaceDerivedLinksBatch delegate (batch logic in derived-links.ts); +9 GBRA-75: getBacklinkCounts and getHealth statements run JIT-off through the private jitOffRead transaction helper (engine methods cannot move); +3 GBRA-75 wave 7: searchKeyword and searchVector start the once-per-engine background search statistics guard (logic in search/projection-statistics.ts); +7 GBRA-67: readPageSnapshotsBatch scoped-read delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages scoped-read delegate (SQL in engine-sql/pages.ts); +7 #6383: poolIncidents hooks on the instance/module/connection-manager pools (counter and lines in pool-gauge.ts, budget in db.ts) and stuckDiscards/buildFailures in getPoolDiagnostics-src/core/search/hybrid.ts 1618 ratchet +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key; +5 green master wave (embedding opt-out): HybridSearchOpts._embeddingOptedOut (interface field) read once per request and threaded to the cache-lookup embed and the keyword-only gate; +24 P2 explain RRF attribution stamp in rrfFusionWeighted, backlink_count stamp, explain_target stage observations, explain/explainTarget opts; +1 query facts arm: HybridSearchOpts.onQueryEmbedding (interface field; its one-line call is paid inside the ceiling) after the vector arms, so the facts arm reuses the query embedding without a second model call; re-summed at the master a08578ca5 merge (1591 master lines + 3 integration lines: the onQueryEmbedding hook)-src/core/types.ts 2263 ratchet +7 fix wave 11 W6.2/W6.3 (#5989, #6132): SearchOpts.hnswIterativeScan and cjkKeyword, the keyword_candidates_incomplete stage and HybridSearchMeta.keyword_candidates (logic in engine-sql/cjk-search.ts); +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +1 green master wave: embedding_disabled degraded reason (closed vocabulary); +2 #5951: Chunk.source_id (get_chunks names each row's source); 1 P2 SearchResult explain fields (rrf attribution, blend_norm_rrf, score_details, backlink_count) + RrfAttribution (interface fields); +11 #5575 (L1b): PageReadScope minTrust/suppressFlagged, SearchResult trust_tier/origin/unconfirmed, TimelineOpts eligibility (interface fields cannot move); +1 C4: question page type row; +6 entity anchoring: optional SearchResult.entity_anchored row stamp (logic in search/entity-anchor.ts); +4 query facts arm: optional SearchResult.fact_row and superseded_claim row fields (logic in search/facts-arm.ts); +2 query facts arm: SearchResult result_type/fact_id/page_slug/follow_up (fact rows are never page-shaped)+src/core/search/hybrid.ts 1627 ratchet +9 W3 confidence-gated reranking: HybridSearchOpts.rerankGate and the gate/lookup threading through rerankAndPin and sizeReturnPool (logic in search/hybrid/rerank-gate.ts, crag.ts gradePreRerank); +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key; +5 green master wave (embedding opt-out): HybridSearchOpts._embeddingOptedOut (interface field) read once per request and threaded to the cache-lookup embed and the keyword-only gate; +24 P2 explain RRF attribution stamp in rrfFusionWeighted, backlink_count stamp, explain_target stage observations, explain/explainTarget opts; +1 query facts arm: HybridSearchOpts.onQueryEmbedding (interface field; its one-line call is paid inside the ceiling) after the vector arms, so the facts arm reuses the query embedding without a second model call; re-summed at the master a08578ca5 merge (1591 master lines + 3 integration lines: the onQueryEmbedding hook)+src/core/types.ts 2271 ratchet +8 W3 confidence-gated reranking: HybridSearchMeta.rerank_gate (RerankGateMeta in search/hybrid/rerank-gate.ts); +7 fix wave 11 W6.2/W6.3 (#5989, #6132): SearchOpts.hnswIterativeScan and cjkKeyword, the keyword_candidates_incomplete stage and HybridSearchMeta.keyword_candidates (logic in engine-sql/cjk-search.ts); +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +1 green master wave: embedding_disabled degraded reason (closed vocabulary); +2 #5951: Chunk.source_id (get_chunks names each row's source); 1 P2 SearchResult explain fields (rrf attribution, blend_norm_rrf, score_details, backlink_count) + RrfAttribution (interface fields); +11 #5575 (L1b): PageReadScope minTrust/suppressFlagged, SearchResult trust_tier/origin/unconfirmed, TimelineOpts eligibility (interface fields cannot move); +1 C4: question page type row; +6 entity anchoring: optional SearchResult.entity_anchored row stamp (logic in search/entity-anchor.ts); +4 query facts arm: optional SearchResult.fact_row and superseded_claim row fields (logic in search/facts-arm.ts); +2 query facts arm: SearchResult result_type/fact_id/page_slug/follow_up (fact rows are never page-shaped)src/core/minions/queue.ts 2528 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys; +18 Lane D: deferJob (a deferral returns a job to delayed with no attempt counted and no stacktrace growth); the ceiling had 17 lines of slack; +5 agent operator follow-up Item 5 merged over master: claim-time spend fence token and legacy_default stamp (logic in minions/spend-authorization.ts)src/commands/init.ts 1878 ratchet +2 fix wave 9 lane F #5253: leaving deferred setup also clears the DB-plane embedding_disabled row (both init branches); 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-init; -14: first-run bundle + quickstart registration helpers live in init-first-run.ts (writeback/skills asks folded into the bundle); +5 agent operator follow-up Item 2: --surface flag (value flag, parse, help line, module-level registration surface, type import) for the printed harness registration; +2 fix wave lane B3: both engine paths stamp a database init created as a fresh install for the behavior_changes notice (core/behavior-change-notice.ts)src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)@@ -36,11 +36,11 @@ src/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refreshsrc/commands/hook.ts 1926 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + import; +2 fix wave 11 integration: W1 router help guard import beside the W2 managed-root importsrc/core/chunkers/code.ts 1602 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts); +10 Lua grammar swap: GRAMMAR_REVISIONS + chunkerStamp() (per-language re-chunk gate); +4: CodeChunkOptions.timeoutMs (per-call parse cap; markdown fences parse under a short cap) and the "Parsing failed" → ChunkerTimeoutError mapping in parseWithTimeout-src/core/config.ts 1939 ratchet +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts)+src/core/config.ts 1942 ratchet +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts)src/core/bootstrap/harness.ts 2610 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts)src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl optionsrc/core/ops/pages.ts 683 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept)-src/core/search/mode.ts 1594 ratchet +10 System One v1: decide.* snapshot subset in loadSearchModeConfig, append-only dec= knobsHash part; +5 #3617 follow-up: v27 same-knobs behavioral-change note (relaxed-row fusion demotion rides the bump); new row: crossed the 1500 unlisted cap in the 2026-08 eval fix wave — KNOBS_HASH v=27 adaptive-return fold (ar/arem/arom/armk/ari parts + KnobsHashContext.adaptiveReturn field + contamination rationale comments) | merged v0.48.1.0 (+#4787) true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: four knobs (expansion_variant_budget, relational_rerank_pin, keyword_arm_confidence_floor, metadata_boost_gate) + v29 hash parts + doc receipts (+218); #4781 loadSearchModeConfig reads the config table once via loadConfigSnapshot (+6); +4 #4359: update loadSearchModeConfig docstring — the cached path now reads config once (threaded snapshot), not twice; retired provider integration removed; +12 fw3-search: search.source_boosts + search.alias_token_hop read in the mode snapshot; +10 #5691: KnobsHashContext.queryPrefix and its append-only qp= part; P7 relational_planner / relational_orient_onehop knobs (interface docs, bundles, overrides, config parse, hash parts); +18 P7 relational_chain_slots knob (interface doc, bundles, override, config parse, rcs= hash part)+src/core/search/mode.ts 1647 ratchet +53 W3 confidence-gated reranking: reranker_gate / reranker_gate_min_gap bundle fields, overrides, config parse and KNOB_CONFIG_KEY rows, knobsHash v=31 rrg=/rrgg=/ecf= parts (parse contracts in crag.ts); +10 System One v1: decide.* snapshot subset in loadSearchModeConfig, append-only dec= knobsHash part; +5 #3617 follow-up: v27 same-knobs behavioral-change note (relaxed-row fusion demotion rides the bump); new row: crossed the 1500 unlisted cap in the 2026-08 eval fix wave — KNOBS_HASH v=27 adaptive-return fold (ar/arem/arom/armk/ari parts + KnobsHashContext.adaptiveReturn field + contamination rationale comments) | merged v0.48.1.0 (+#4787) true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: four knobs (expansion_variant_budget, relational_rerank_pin, keyword_arm_confidence_floor, metadata_boost_gate) + v29 hash parts + doc receipts (+218); #4781 loadSearchModeConfig reads the config table once via loadConfigSnapshot (+6); +4 #4359: update loadSearchModeConfig docstring — the cached path now reads config once (threaded snapshot), not twice; retired provider integration removed; +12 fw3-search: search.source_boosts + search.alias_token_hop read in the mode snapshot; +10 #5691: KnobsHashContext.queryPrefix and its append-only qp= part; P7 relational_planner / relational_orient_onehop knobs (interface docs, bundles, overrides, config parse, hash parts); +18 P7 relational_chain_slots knob (interface doc, bundles, override, config parse, rcs= hash part)src/commands/eval-longmemeval.ts 1519 ratchet new row: crossed the 1500 unlisted cap in fw3-search (#5092 benchmark-brain recycling: configureBrain split + recycler wiring + test seams; the recycler itself lives in src/eval/longmemeval/harness.ts); +1 P6: tokenmax synopsis-tier wiring (logic in eval/longmemeval/synopsis-tier.ts)src/commands/doctor/checks/extraction-sync.ts 1512 ratchet +1 undeclared_db_only_pages computes the source Git scope once per source (logic in core/markdown.ts sourceGitScope); new row: crossed the 1500 unlisted cap at the fix wave 9 merge: +7 lane W #5028 (extract_atoms freshness judged by the phase itself) and +3 lane F #5863 (extract_health dates a high halt rate by its last halt), each under the cap alone; +7 #5019: content_hash_duplicates fix pins the pairs' source (GBRAIN_SOURCE) and names a delete that runs; +1 fix wave 10 lane L1 #5556: links_extraction_lag denominator excludes quarantined pages (quarantineFilterFragment import)src/core/search/evidence-delivery.ts 1512 ratchet new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8)diff --git a/src/commands/search.ts b/src/commands/search.tsindex e137529d1d..ed9dd4394f 100644--- a/src/commands/search.ts+++ b/src/commands/search.ts@@ -42,6 +42,7 @@ import {telemetryCoverage,TELEMETRY_COVERAGE_CAVEAT,type GraphSignalsStatsSection,+ type RerankGateStats,} from '../core/search/telemetry.ts';import {buildModesReport,@@ -205,6 +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)',},},}, null, 2));@@ -257,10 +259,27 @@ async function runStatsSubcommand(engine: BrainEngine, args: string[]): Promise<console.log('');console.log(` Window: ${stats.oldest_seen ?? '?'} → ${stats.newest_seen ?? '?'}`);}+ if (stats.rerank_gate.graded > 0 || Object.keys(stats.rerank_gate.ineligible).length > 0) {+ console.log('');+ printRerankGateSection(stats.rerank_gate);+ }console.log('');printGraphSignalsSection(gsSection);}+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)}%)`);+ 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}`);+ }+ for (const [why, count] of Object.entries(g.ineligible).sort((a, b) => b[1] - a[1])) {+ console.log(` not graded (${why}): ${count}`);+ }+}+function printGraphSignalsSection(gs: GraphSignalsStatsSection): void {console.log(' Graph signals:');const sourceLabel = gs.source === 'config' ? 'config override' : 'mode default';diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 548ebfc68a..965639f2a4 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -373,6 +373,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.147.0', text: 'In a brain folder with the Git durability hook, a write that arrives while the effect worker commits a backlog of Git effects now publishes after the group in flight, inside its 5 s wait, instead of returning pending after the whole backlog; Git effects still commit in order. A write waiting on a busy worktree is reported as `writer_busy` without a stale preparing phase.' },// `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.{ since: '0.60.151.0', text: '`delta` and `context_pack` called without `include_private`, and the per-turn context block that harness hooks inject, now apply to their facts the same page-visibility rule they already apply to their pages. With `include_private` from the local CLI, `delta` and `context_pack` output is unchanged.' },+ // W3 confidence-gated reranking (memory proof wave 2). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.+ { since: '0.60.152.0', text: '`gbrain search stats --json` and the `search_stats` tool now always include a `rerank_gate` section, all zeros until you set `search.reranker.gate` to `shadow`; search results and ranking are unchanged. The search cache key now includes `search.evidence_cosine_floor` and the new gate keys (the result cache stays disabled).' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/config.ts b/src/core/config.tsindex 4ca31ef91c..6433c6d46c 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1322,6 +1322,9 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = ['search.reranker.top_n_in','search.reranker.top_n_out','search.reranker.timeout_ms',+ // W3: confidence-gated reranking (mode.ts reads; `off` | `shadow`, and δ in [0, 1]).+ 'search.reranker.gate',+ 'search.reranker.gate_min_gap','search.floor_ratio','search.title_boost','search.evidence_cosine_floor',diff --git a/src/core/ops/search.ts b/src/core/ops/search.tsindex ead57490df..462d002b6f 100644--- a/src/core/ops/search.ts+++ b/src/core/ops/search.ts@@ -468,6 +468,7 @@ async function buildRetrievalResponseMeta(...(m.rerank ? { rerank: m.rerank } : {}),...(m.answerability ? { answerability: m.answerability } : {}),...(m.relational_plan ? { relational_plan: m.relational_plan } : {}),+ ...(m.rerank_gate ? { rerank_gate: m.rerank_gate } : {}),} : {}),...((m?.degraded !== undefined || degraded.length > 0) ? { degraded } : {}),projection_readiness: readiness,@@ -1261,6 +1262,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)',},},};diff --git a/src/core/search/alias-hop.ts b/src/core/search/alias-hop.tsindex a854f9616f..b3d6b1c2bc 100644--- a/src/core/search/alias-hop.ts+++ b/src/core/search/alias-hop.ts@@ -60,37 +60,72 @@ export function isExcludedIdentity(slug: string, opts: Pick<IdentityTierOpts, 'ereturn opts.excludeSlugPrefixes?.some((p) => slug.startsWith(p)) ?? false;}-export async function applyAliasHop(+/**+ * A54 — the immutable half of the alias hop: the alias table read for the+ * normalized query (plus its tokens under `tokenHop`). It never touches a+ * result list, so the rerank gate can read it before reranking and the apply+ * step reuses it after, and the alias table is read once per search.+ * `null` means the hop is a no-op for this query (empty, too long, or the+ * table is missing / the read failed — fail-open, D9).+ */+export interface AliasHopLookup {+ qNorm: string;+ tokens: string[];+ aliasMap: Map<string, Array<{ slug: string; source_id: string }>>;+}++export async function lookupAliasHop(engine: import('../engine.ts').BrainEngine,- results: SearchResult[],query: string,opts: IdentityTierOpts & { tokenHop?: boolean },-): Promise<SearchResult[]> {- if (!query) return results;+): Promise<AliasHopLookup | null> {+ if (!query) return null;const qNorm = normalizeAlias(query);- if (!qNorm || qNorm.split(' ').length > MAX_ALIAS_QUERY_TOKENS) return results;+ if (!qNorm || qNorm.split(' ').length > MAX_ALIAS_QUERY_TOKENS) return null;const tokens = opts.tokenHop? [...new Set(qNorm.split(' '))].filter((t) => t.length >= 2 && t !== qNorm): [];-- let aliasMap: Map<string, Array<{ slug: string; source_id: string }>>;try {- aliasMap = await engine.resolveAliases([qNorm, ...tokens], opts);+ return { qNorm, tokens, aliasMap: await engine.resolveAliases([qNorm, ...tokens], opts) };} catch {- return results; // pre-v110 table-missing OR transient error -> fail-open+ return null; // pre-v110 table-missing OR transient error -> fail-open}- const refs = aliasMap.get(qNorm);+}++/** The full-query alias canonicals the hop would boost or inject: excludes applied, deterministic order, capped. */+export function aliasHopCanonicals(lookup: AliasHopLookup, opts: IdentityTierOpts): Array<{ slug: string; source_id: string }> {+ return [...(lookup.aliasMap.get(lookup.qNorm) ?? [])]+ .filter(ref => !isExcludedIdentity(ref.slug, opts))+ .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);+}++export async function applyAliasHop(+ engine: import('../engine.ts').BrainEngine,+ results: SearchResult[],+ query: string,+ opts: IdentityTierOpts & { tokenHop?: boolean },+): Promise<SearchResult[]> {+ return applyAliasHopLookup(engine, results, await lookupAliasHop(engine, query, opts), opts);+}++/** The apply half of the alias hop: boost or inject the looked-up canonicals into `results`. */+export async function applyAliasHopLookup(+ engine: import('../engine.ts').BrainEngine,+ results: SearchResult[],+ lookup: AliasHopLookup | null,+ opts: IdentityTierOpts,+): Promise<SearchResult[]> {+ if (!lookup) return results;+ const refs = lookup.aliasMap.get(lookup.qNorm);if (!refs || refs.length === 0) {- return tokens.length > 0 ? applyAliasTokenHop(engine, results, tokens, aliasMap, opts) : results;+ return lookup.tokens.length > 0 ? applyAliasTokenHop(engine, results, lookup.tokens, lookup.aliasMap, opts) : results;}// Deterministic + capped. Source-scoped: each canonical is a (source_id, slug)// 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 => !isExcludedIdentity(ref.slug, opts))- .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 ordered = aliasHopCanonicals(lookup, opts);const out = [...results];let injectScore = topOrganicScore(out);diff --git a/src/core/search/crag.ts b/src/core/search/crag.tsindex f1bd0d7b10..3d1e0b424f 100644--- a/src/core/search/crag.ts+++ b/src/core/search/crag.ts@@ -36,6 +36,9 @@*/import type { SearchResult } from '../types.ts';+import { type TrustTier, admitsTrust, maxTrust } from '../trust/tier.ts';+import { DEFAULT_HIGH_COSINE_FLOOR } from './evidence.ts';+import { normalizeAlias } from './alias-normalize.ts';export type RetrievalConfidence = 'strong' | 'moderate' | 'weak';@@ -267,3 +270,156 @@ export function confidenceRank(level: RetrievalConfidence): number {case 'weak': return 0;}}++// ---------------------------------------------------------------------------+// W3 — confidence-gated reranking: the PRE-rerank grade.+//+// `gradeRetrievalConfidence` grades the final, reranked list. The rerank gate+// needs a grade BEFORE the cross-encoder runs, on the deduped candidates+// (after fusion, cosine re-scoring and dedup). It mirrors the identity tiers+// above, without System One decide evidence (stamped after rerank, opt-in+// paid), and reads only what exists before reranking: the identity lookups+// (exact-lookup hits and alias canonicals, read but not applied), the title+// boost and the stamped raw cosine.+// ---------------------------------------------------------------------------++/** `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']);++export const DEFAULT_RERANK_GATE: RerankGateMode = 'off';++/** Default `search.reranker.gate_min_gap` (δ): cosine margin rank-1 needs over the best other page. */+export const DEFAULT_RERANK_GATE_MIN_GAP = 0.05;++/**+ * The lowest page trust tier a gate-strong rank-1 may carry. An+ * `external_untrusted` page that echoes a common question cannot skip the+ * cross-encoder; a caller's own `min_trust` raises the floor (`maxTrust`).+ */+export const RERANK_GATE_TRUST_FLOOR: TrustTier = 'unknown';++/**+ * Strong reasons a skip would apply to (`would_skip`). Title and alias (and+ * the exact-lookup tier, which is slug or full-title identity) stay+ * shadow-only until a corpus with titles and aliases shows them+ * non-inferior: the counted benchmark has neither (A57).+ */+export const RERANK_GATE_SKIP_REASONS: ReadonlySet<PreRerankStrongReason> = new Set<PreRerankStrongReason>(['high_vector_match']);++/** The one parse contract for the gate key and the per-call override: a `RERANK_GATE_MODES` literal (any case), else unset. */+export function normalizeRerankGate(v: unknown): RerankGateMode | undefined {+ if (typeof v !== 'string') return undefined;+ const s = v.trim().toLowerCase();+ return (RERANK_GATE_MODES as ReadonlyArray<string>).includes(s) ? (s as RerankGateMode) : undefined;+}++/** δ parse contract: a finite number (or numeric string) in [0, 1], else unset. */+export function normalizeRerankGateMinGap(v: unknown): number | undefined {+ const n = typeof v === 'number' ? v : typeof v === 'string' && v.trim() !== '' ? Number(v) : NaN;+ return Number.isFinite(n) && n >= 0 && n <= 1 ? n : undefined;+}++export type PreRerankStrongReason = 'exact_lookup' | 'alias_hit' | 'exact_title_match' | 'high_vector_match';++export type PreRerankNotStrongReason =+ | 'no_candidates'+ /** More than one exact-lookup or alias page, or a single-token alias hop would move rank 1. */+ | 'identity_ambiguous'+ /** Image modality or unified multimodal routing: never strong. */+ | 'multimodal'+ | 'no_cosine'+ | 'cosine_below_floor'+ /** Rank-1's cosine does not lead the best other page by δ. */+ | 'gap_below_min'+ | 'below_trust_floor';++export interface PreRerankGrade {+ strong: boolean;+ reason: PreRerankStrongReason | PreRerankNotStrongReason;+ /** Rank-1's stamped raw cosine, when finite. */+ top_cosine?: number;+ /** Rank-1's cosine minus the best cosine of a different page in the same space (rank-1's own cosine when no other page). */+ gap?: number;+ /** The page a strong grade vouches for: the identity page, or the fused rank-1. */+ top?: { slug: string; source_id: string; page_id?: number };+}++export interface PreRerankGradeInput {+ /** The deduped candidates in fused order (the reranker's input). Read only. */+ candidates: readonly SearchResult[];+ query: string;+ /** Hits the exact-lookup tier would apply (one per page). */+ exactLookupHits: readonly SearchResult[];+ /** Full-query alias canonicals the alias hop would apply. */+ aliasCanonicals: ReadonlyArray<{ slug: string; source_id: string }>;+ /** True when the opt-in single-token alias hop has a candidate to move. */+ aliasTokenHop?: boolean;+ /** Image modality or unified multimodal routing. */+ multimodal: boolean;+ /** `search.evidence_cosine_floor` (default 0.8). */+ cosineFloor?: number;+ /** `search.reranker.gate_min_gap` (δ). */+ minGap?: number;+}++const pageKey = (r: { slug: string; source_id?: string }): string => `${r.source_id ?? 'default'}::${r.slug}`;++/**+ * Pure pre-rerank grade. Strong when, in this order:+ * - the exact-lookup tier finds exactly one page;+ * - else the alias hop finds exactly one page;+ * - else rank-1 is a FULL-title identity (title boost and normalized+ * title equals the normalized query; a phrase inside a longer title is+ * not identity);+ * - else rank-1 is `high_vector_match` (cosine at or above the floor) AND+ * leads the best candidate from a different page in the same embedding+ * space by at least δ. Candidates are not in cosine order and dedup keeps+ * several chunks per page, so the gap is computed over pages.+ * Multimodal queries and image rows are never strong. The trust floor is+ * applied afterwards (`applyRerankGateTrust`): it needs the page's tier.+ */+export function gradePreRerank(input: PreRerankGradeInput): PreRerankGrade {+ const { candidates } = input;+ if (input.exactLookupHits.length > 1) return { strong: false, reason: 'identity_ambiguous' };+ if (input.exactLookupHits.length === 1) {+ const h = input.exactLookupHits[0];+ return { strong: true, reason: 'exact_lookup', top: { slug: h.slug, source_id: h.source_id ?? 'default', ...(typeof h.page_id === 'number' && h.page_id > 0 ? { page_id: h.page_id } : {}) } };+ }+ if (input.aliasCanonicals.length > 1 || (input.aliasCanonicals.length === 0 && input.aliasTokenHop)) {+ return { strong: false, reason: 'identity_ambiguous' };+ }+ if (input.aliasCanonicals.length === 1) {+ const a = input.aliasCanonicals[0];+ return { strong: true, reason: 'alias_hit', top: { slug: a.slug, source_id: a.source_id } };+ }+ const top = candidates[0];+ if (!top) return { strong: false, reason: 'no_candidates' };+ if (input.multimodal || top.modality === 'image') return { strong: false, reason: 'multimodal' };+ const topRef = { slug: top.slug, source_id: top.source_id ?? 'default', ...(typeof top.page_id === 'number' ? { page_id: top.page_id } : {}) };+ const qNorm = normalizeAlias(input.query);+ if ((top.title_match_boost ?? 1) > 1 && qNorm !== '' && normalizeAlias(top.title ?? '') === qNorm) {+ return { strong: true, reason: 'exact_title_match', top: topRef };+ }+ const cosine = top.cosine;+ if (typeof cosine !== 'number' || !Number.isFinite(cosine)) return { strong: false, reason: 'no_cosine' };+ const floor = input.cosineFloor ?? DEFAULT_HIGH_COSINE_FLOOR;+ if (cosine < floor) return { strong: false, reason: 'cosine_below_floor', top_cosine: cosine };+ const own = pageKey(top);+ let other = 0;+ for (const r of candidates) {+ if (r.modality === 'image' || pageKey(r) === own) continue;+ if (typeof r.cosine === 'number' && Number.isFinite(r.cosine) && r.cosine > other) other = r.cosine;+ }+ const gap = cosine - other;+ if (gap < (input.minGap ?? DEFAULT_RERANK_GATE_MIN_GAP)) return { strong: false, reason: 'gap_below_min', top_cosine: cosine, gap };+ return { strong: true, reason: 'high_vector_match', top_cosine: cosine, gap, top: topRef };+}++/** A strong grade whose page tier is below `max(callerFloor, RERANK_GATE_TRUST_FLOOR)` is not strong. Unknown tier reads as `unknown`. */+export function applyRerankGateTrust(grade: PreRerankGrade, tier: TrustTier | undefined, callerFloor?: TrustTier): PreRerankGrade {+ if (!grade.strong) return grade;+ const floor = callerFloor ? maxTrust(callerFloor, RERANK_GATE_TRUST_FLOOR) : RERANK_GATE_TRUST_FLOOR;+ return admitsTrust(tier ?? 'unknown', floor) ? grade : { ...grade, strong: false, reason: 'below_trust_floor' };+}diff --git a/src/core/search/exact-lookup.ts b/src/core/search/exact-lookup.tsindex 1d23732add..c76defe84f 100644--- a/src/core/search/exact-lookup.ts+++ b/src/core/search/exact-lookup.ts@@ -191,6 +191,16 @@ export async function applyExactLookupTier(} catch {return results;}+ return applyExactLookupHits(results, hits);+}++/**+ * A54 — the apply half of the tier, for hits `structuralExactLookup` already+ * returned (the rerank gate looks them up before reranking; this applies them+ * at the tier's post-rerank position without a second probe). Hit rows are+ * copied before injection, so one hit list can be applied once per search.+ */+export function applyExactLookupHits(results: SearchResult[], hits: readonly SearchResult[]): SearchResult[] {if (hits.length === 0) return results;const out = [...results];diff --git a/src/core/search/explain-formatter.ts b/src/core/search/explain-formatter.tsindex b103b33c66..71112b4fd2 100644--- a/src/core/search/explain-formatter.ts+++ b/src/core/search/explain-formatter.ts@@ -149,6 +149,22 @@ export function formatDegradedSummary(degraded: HybridSearchMeta['degraded'] | ureturn `degraded: ${degraded.map((d) => (d.reason ? `${d.stage} (${d.reason})` : d.stage)).join(', ')}`;}+/**+ * W3 — one-line rerank gate summary for `--explain` (null when the gate is+ * off, so gate-off explain output is byte-identical).+ */+export function formatRerankGateSummary(gate: HybridSearchMeta['rerank_gate'] | undefined): string | null {+ if (!gate) return null;+ 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,+ gate.gap !== undefined ? `gap ${fmt(gate.gap)}` : null,+ `${gate.candidates} candidates`,+ ].filter(Boolean).join(', ');+ const verdict = gate.would_skip ? 'would skip' : gate.skip_blocked ? `would rerank (${gate.skip_blocked})` : 'would rerank';+ return `rerank gate (${gate.mode}): ${gate.grade} ${gate.reason} — ${verdict} (${signal})`;+}+/** One-line evidence-delivery summary for `--explain` (null when the stage did not run). */export function formatDeliverySummary(delivery: DeliveryMeta | undefined): string | null {if (!delivery) return null;@@ -191,7 +207,7 @@ export function formatResultsExplain(const body = results.map((r, i) => formatResultExplain(r, i + 1)).join('\n\n') + '\n';// v0.42.3.0 — prepend the autocut summary when meta carries a decision;// v0.48.2 — and the degraded summary when any stage was skipped.- const head = [formatAutocutSummary(meta?.autocut), formatDegradedSummary(meta?.degraded), formatDeliverySummary(meta?.delivery), formatDecideSummary(meta?.decide)]+ const head = [formatAutocutSummary(meta?.autocut), formatDegradedSummary(meta?.degraded), formatRerankGateSummary(meta?.rerank_gate), formatDeliverySummary(meta?.delivery), formatDecideSummary(meta?.decide)].filter((l): l is string => l !== null);return head.length > 0 ? `${head.join('\n')}\n\n${body}` : body;}diff --git a/src/core/search/hybrid.ts b/src/core/search/hybrid.tsindex 9cd1655900..fdc6cf7d2c 100644--- a/src/core/search/hybrid.ts+++ b/src/core/search/hybrid.ts@@ -903,6 +903,13 @@ export interface HybridSearchOpts extends SearchOpts {* resolver (knobs hash `mbg=`); eval A/B runs drive it here.*/metadataBoostGate?: MetadataBoostGate;+ /**+ * Per-call override for `search.reranker.gate` (crag.ts `gradePreRerank`):+ * `shadow` grades before the cross-encoder and still reranks. `undefined` → config/bundle; anything else is unset via+ * the ONE contract `normalizeRerankGate`. Threaded through resolveSearchMode+ * in BOTH the inner search and the cache resolver (knobs hash `rrg=`).+ */+ rerankGate?: import('./crag.ts').RerankGateMode;/*** explain_target (explain-target.ts): when set, each pipeline stage records* whether the target page was present and at what rank. Observation only —@@ -1155,15 +1162,17 @@ export async function hybridSearch(return hybridSearch(engine, query, { ...opts, detail: 'high' });}- const { rerankPinned, relationalRerankPin } = await rerankAndPin(req, deduped, relationalList, effectiveModality);+ const { rerankPinned, relationalRerankPin, rerankGate, identityLookups } = await rerankAndPin(req, deduped, relationalList, effectiveModality, {+ exactLookupOpts: lexical.exactLookupOpts, multimodal: effectiveModality !== 'text' || unifiedDone,+ });opts?.explainTarget?.observe('reranked', rerankPinned);const { returnPool, adaptiveDecision, autocutDecision, relationalSlotDecision } = await sizeReturnPool(req, {- rerankPinned, deduped, exactLookupOpts: lexical.exactLookupOpts, relationalList, effectiveModality,+ rerankPinned, deduped, exactLookupOpts: lexical.exactLookupOpts, relationalList, effectiveModality, identityLookups,});opts?.explainTarget?.observe('return_pool', returnPool);return finalizeHybridResults(req, returnPool, {relaxedDropped, adaptiveDecision, autocutDecision, relationalSlotDecision,- relationalRerankPin, keywordArmConfidence, metadataBoostGate,+ relationalRerankPin, keywordArmConfidence, metadataBoostGate, rerankGate,});}diff --git a/src/core/search/hybrid/cache-stages.ts b/src/core/search/hybrid/cache-stages.tsindex ccd2ce7f97..a4e5ab25a8 100644--- a/src/core/search/hybrid/cache-stages.ts+++ b/src/core/search/hybrid/cache-stages.ts@@ -19,6 +19,7 @@ import { loadConfigWithEngine } from '../../config.ts';import { normalizeExpansionVariantBudget } from '../fusion-lists.ts';import { normalizeKeywordArmConfidenceFloor } from '../arm-confidence.ts';import { normalizeMetadataBoostGate } from '../metadata-boost-gate.ts';+import { normalizeRerankGate } from '../crag.ts';import { normalizeRelationalRerankPin } from '../relational-rerank-pin.ts';import { recordSearchTelemetry } from '../telemetry.ts';import { resolveEffectiveRecency, resolveEffectiveSalience } from './effective-modes.ts';@@ -90,6 +91,8 @@ export async function resolveCacheSearchMode(engine: BrainEngine, opts: HybridSekeyword_arm_confidence_floor: normalizeKeywordArmConfidenceFloor(opts?.keywordArmConfidenceFloor),// Ranker wave (Phase E3) — threaded here too so knobsHash's `mbg=` part reflects the per-call gate.metadata_boost_gate: normalizeMetadataBoostGate(opts?.metadataBoostGate),+ // W3 — rerank gate per-call thread-through (eval A/B; knobsHash `rrg=`).+ reranker_gate: normalizeRerankGate(opts?.rerankGate),},});return { modeInputForCache, resolvedForCache, knobsHash };diff --git a/src/core/search/hybrid/rank.ts b/src/core/search/hybrid/rank.tsindex 4d7cd37111..08131a58ed 100644--- a/src/core/search/hybrid/rank.ts+++ b/src/core/search/hybrid/rank.ts@@ -6,7 +6,7 @@import type { ModalityMode } from '../query-intent.ts';import { type AdaptiveReturnDecision, adaptiveReturnFromConfig, applyAdaptiveReturn, resolveAdaptiveReturn } from '../return-policy.ts';import { type AutocutDecision, applyAutocut } from '../autocut.ts';-import { type ExactLookupOpts, applyExactLookupTier } from '../exact-lookup.ts';+import { type ExactLookupOpts, applyExactLookupHits, applyExactLookupTier } from '../exact-lookup.ts';import { type FusionListEntry, type VectorArm, composeFusionLists } from '../fusion-lists.ts';import { type HybridRequest, applyIdentityBoosts, emitHybridMeta } from './request.ts';import type { KeywordArmConfidenceDecision } from '../arm-confidence.ts';@@ -20,7 +20,8 @@ import type { RerankMeta } from '../../ai/gateway.ts';import { applyEvidenceGate, recordRerankReceipts, startRerankShadow } from '../decide-stage.ts';import { rerankEgressDenied } from '../decide-retrieval.ts';import type { SearchResult } from '../../types.ts';-import { applyAliasHop } from '../alias-hop.ts';+import { applyAliasHop, applyAliasHopLookup } from '../alias-hop.ts';+import { type IdentityLookups, type RerankGateMeta, prepareRerankGate } from './rerank-gate.ts';import { effectiveRrfK } from '../intent-weights.ts';import { enforceTokenBudget } from '../token-budget.ts';import { expandAnchors, hydrateChunks } from '../two-pass.ts';@@ -244,12 +245,13 @@ export async function expandStructuralNeighbors(req: HybridRequest, fused: Searcreturn dedupOpts;}-/** Cross-encoder rerank (fail-open), then the relational-row pin. */+/** Cross-encoder rerank (fail-open), then the relational-row pin; the W3 rerank gate grades the same candidates. */export async function rerankAndPin(req: HybridRequest,deduped: SearchResult[],relationalList: SearchResult[],effectiveModality: ModalityMode,+ { exactLookupOpts, multimodal }: { exactLookupOpts: ExactLookupOpts; multimodal: boolean },) {const { engine, query, opts, resolvedMode, degraded } = req;// v0.35.0.0+: cross-encoder reranker. Slots between dedup and slice so the@@ -284,6 +286,10 @@ export async function rerankAndPin(// decide.egress.deny_sources; such a query keeps fused order (egress_denied).const egressDenied = rerankerOpts.enabled && rerankEgressDenied(req.modeInput.decide, rerankerOpts.model ?? resolvedMode.reranker_model, deduped.slice(0, rerankerOpts.topNIn));if (egressDenied) { s1Failure = 'egress_denied'; pushDegraded(degraded, 'reranker_skipped', 'egress_denied'); }+ // 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.+ const gatePending = prepareRerankGate(req, { deduped, rerankerOpts, egressDenied, exactLookupOpts, multimodal });const reranked = rerankerOpts.enabled && !egressDenied? await applyReranker(query, deduped, {...(rerankerOpts as any),@@ -298,6 +304,10 @@ export async function rerankAndPin(onMeta: (m: RerankMeta) => { s1Meta = m; req.rerankMeta = { model_resolved: m.model_resolved }; },}): deduped;+ const gate = await gatePending;+ const rerankGate: RerankGateMeta | undefined = gate.meta?.eligible+ ? { ...gate.meta, provider_called: s1Failure !== 'no_key' }+ : gate.meta;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: reranked !== deduped });@@ -312,22 +322,26 @@ export async function rerankAndPin(const rerankPinned = reranked !== deduped && effectiveModality !== 'image'? pinRelationalRows(ordered, relationalList, { max: resolvedMode.relational_rerank_pin, fusedOrder: deduped, onPin: (d) => { relationalRerankPin = d; } }): ordered;- return { rerankPinned, relationalRerankPin };+ return { rerankPinned, relationalRerankPin, rerankGate, identityLookups: gate.lookups };}/** Alias hop + exact-lookup tier, evidence stamp, adaptive return, autocut and the relational evidence slot. */export async function sizeReturnPool(req: HybridRequest,- { rerankPinned, deduped, exactLookupOpts, relationalList, effectiveModality }: {+ { rerankPinned, deduped, exactLookupOpts, relationalList, effectiveModality, identityLookups }: {rerankPinned: SearchResult[]; deduped: SearchResult[]; exactLookupOpts: ExactLookupOpts;relationalList: SearchResult[]; effectiveModality: ModalityMode;+ /** Lookups the rerank gate already read (gate not `off`): applied here, never re-read. */+ identityLookups?: IdentityLookups;},) {const { engine, query, opts, resolvedMode, cfgForColumn, limit, offset, suggestions, aliasHopOpts } = req;// T3 — free-text alias hop. Runs AFTER rerank so a query that is a page's// declared chosen name reliably surfaces that page regardless of how the// reranker scored body chunks. Fail-open on pre-v110 brains.- const preExact = await applyAliasHop(engine, rerankPinned, query, aliasHopOpts);+ const preExact = identityLookups+ ? await applyAliasHopLookup(engine, rerankPinned, identityLookups.alias, aliasHopOpts)+ : await applyAliasHop(engine, rerankPinned, query, aliasHopOpts);// #1663 — structural exact-lookup tier: a query that IS a page identity// (slug / exact normalized title) gets that page at rank-1 regardless of@@ -335,7 +349,9 @@ export async function sizeReturnPool(// the already-fetched title arm (no extra queries); pure no-op for// non-lookup-shaped queries. Runs after the alias hop so all three// identity surfaces (alias, slug, title) share the same injection shape.- const aliasHopped = await applyExactLookupTier(engine, preExact, query, exactLookupOpts);+ const aliasHopped = identityLookups+ ? applyExactLookupHits(preExact, identityLookups.exactHits)+ : await applyExactLookupTier(engine, preExact, query, exactLookupOpts);// T4 — stamp evidence + create_safety so the agent's don't-duplicate// decision keys off WHY a page matched, not a raw blended score. Stamp on@@ -441,7 +457,7 @@ export async function sizeReturnPool(export async function finalizeHybridResults(req: HybridRequest,returnPool: SearchResult[],- { relaxedDropped, adaptiveDecision, autocutDecision, relationalSlotDecision, relationalRerankPin, keywordArmConfidence, metadataBoostGate }: {+ { relaxedDropped, adaptiveDecision, autocutDecision, relationalSlotDecision, relationalRerankPin, keywordArmConfidence, metadataBoostGate, rerankGate }: {relaxedDropped: number;adaptiveDecision: AdaptiveReturnDecision | undefined;autocutDecision: AutocutDecision | undefined;@@ -449,6 +465,7 @@ export async function finalizeHybridResults(relationalRerankPin: RelationalRerankPinDecision | undefined;keywordArmConfidence: KeywordArmConfidenceDecision | undefined;metadataBoostGate: MetadataBoostGateDecision;+ rerankGate: RerankGateMeta | undefined;},): Promise<SearchResult[]> {const { engine, opts, resolvedMode, resolvedCol, limit, offset, suggestions, detailResolved, degraded } = req;@@ -484,6 +501,7 @@ export async function finalizeHybridResults(...(relationalRerankPin ? { relational_rerank_pin: relationalRerankPin } : {}),...(keywordArmConfidence ? { keyword_arm_confidence: keywordArmConfidence } : {}),metadata_boost_gate: metadataBoostGate,+ ...(rerankGate ? { rerank_gate: rerankGate } : {}),});return budgeted;}diff --git a/src/core/search/hybrid/request.ts b/src/core/search/hybrid/request.tsindex e54549478b..bfeb342d9f 100644--- a/src/core/search/hybrid/request.ts+++ b/src/core/search/hybrid/request.ts@@ -16,6 +16,7 @@ import type { ResolveSearchModeInput, ResolvedSearchKnobs } from '../mode.ts';import { normalizeExpansionVariantBudget } from '../fusion-lists.ts';import { normalizeKeywordArmConfidenceFloor } from '../arm-confidence.ts';import { normalizeMetadataBoostGate } from '../metadata-boost-gate.ts';+import { normalizeRerankGate } from '../crag.ts';import { normalizeRelationalRerankPin } from '../relational-rerank-pin.ts';import { isRelationalQuery } from '../relational-plan.ts';import { pushDegraded } from './degraded.ts';@@ -139,6 +140,8 @@ export async function resolveHybridRequest(keyword_arm_confidence_floor: normalizeKeywordArmConfidenceFloor(opts?.keywordArmConfidenceFloor),// Ranker wave (Phase E3) — metadata boost gate per-call thread-through (eval A/B).metadata_boost_gate: normalizeMetadataBoostGate(opts?.metadataBoostGate),+ // W3 — rerank gate per-call thread-through (eval A/B; knobsHash `rrg=`).+ reranker_gate: normalizeRerankGate(opts?.rerankGate),},});diff --git a/src/core/search/hybrid/rerank-gate.ts b/src/core/search/hybrid/rerank-gate.tsnew file mode 100644index 0000000000..b8beeb4be3--- /dev/null+++ b/src/core/search/hybrid/rerank-gate.ts@@ -0,0 +1,126 @@+/**+ * hybridSearch pipeline stage (W3): the confidence gate in front of the+ * cross-encoder. Runs on the deduped candidates, before `rerankAndPin` calls+ * the reranker, only when `search.reranker.gate` is not `off`.+ *+ * It reads the identity tiers without applying them: the alias table read+ * (`lookupAliasHop`) and the structural exact lookup (`structuralExactLookup`)+ * return what the post-rerank tiers would apply, the grade reads them plus a+ * detached view of the candidates (`gradePreRerank`, pure), and+ * `sizeReturnPool` applies the same lookups at today's post-rerank position,+ * so each lookup runs once and the reranker's input is unchanged. `off`+ * returns nothing and the pipeline is untouched.+ */+import type { SearchResult } from '../../types.ts';+import type { HybridRequest } from './request.ts';+import type { RerankerOpts } from '../rerank.ts';+import { type AliasHopLookup, aliasHopCanonicals, isExcludedIdentity, lookupAliasHop } from '../alias-hop.ts';+import { type ExactLookupOpts, structuralExactLookup } from '../exact-lookup.ts';+import {+ type PreRerankNotStrongReason,+ type PreRerankStrongReason,+ type RerankGateMode,+ RERANK_GATE_SKIP_REASONS,+ applyRerankGateTrust,+ gradePreRerank,+} from '../crag.ts';+import type { TrustTier } from '../../trust/tier.ts';+import { stampPageTrust } from '../../eligibility/stamp.ts';++/** `meta.rerank_gate`: what the gate decided for this request (present only when the gate is not `off`). */+export interface RerankGateMeta {+ mode: Exclude<RerankGateMode, 'off'>;+ /** False when the reranker would not have run anyway (reranker off, egress denied, no candidates). */+ eligible: boolean;+ ineligible_reason?: 'reranker_off' | 'egress_denied' | 'no_candidates';+ grade?: 'strong' | 'not_strong';+ reason?: PreRerankStrongReason | PreRerankNotStrongReason;+ top_cosine?: number;+ gap?: number;+ /** Deduped candidates the grade read. */+ candidates: number;+ /** A strong grade for a skip reason, with nothing blocking a skip. */+ 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';+ /** A reranker provider call was made for this request. */+ provider_called: boolean;+}++/** Identity lookups read before reranking and applied after it (`sizeReturnPool`). */+export interface IdentityLookups {+ alias: AliasHopLookup | null;+ exactHits: SearchResult[];+}++/** True when the opt-in single-token alias hop has a candidate it would move (full-query alias absent). */+function tokenHopWouldFire(lookup: AliasHopLookup, opts: HybridRequest['aliasHopOpts']): boolean {+ if ((lookup.aliasMap.get(lookup.qNorm)?.length ?? 0) > 0) return false;+ return lookup.tokens.some((t) => (lookup.aliasMap.get(t) ?? []).filter((ref) => !isExcludedIdentity(ref.slug, opts)).length === 1);+}++async function pageTrust(req: HybridRequest, top: { slug: string; source_id: string; page_id?: number }, candidates: readonly SearchResult[]): Promise<TrustTier | undefined> {+ const row = candidates.find((r) => r.slug === top.slug && (r.source_id ?? 'default') === top.source_id);+ const probe: { slug: string; source_id?: string; page_id?: number; chunk_text?: string; trust_tier?: string } = row ? { ...row } : { ...top, chunk_text: '' };+ try {+ const [stamped] = await stampPageTrust(req.engine, [probe]);+ return stamped?.trust_tier as TrustTier | undefined;+ } catch {+ return undefined;+ }+}++/**+ * Grade the deduped candidates before reranking. Returns `{}` under `off`.+ * Never mutates `deduped` or its rows.+ */+export async function prepareRerankGate(+ req: HybridRequest,+ { deduped, rerankerOpts, egressDenied, exactLookupOpts, multimodal }: {+ deduped: readonly SearchResult[]; rerankerOpts: Pick<RerankerOpts, 'enabled' | 'topNIn'>; egressDenied: boolean;+ exactLookupOpts: ExactLookupOpts; multimodal: boolean;+ },+): Promise<{ meta?: RerankGateMeta; lookups?: IdentityLookups }> {+ const mode = req.resolvedMode.reranker_gate;+ if (mode === 'off') return {};+ const base = { mode, candidates: deduped.length, would_skip: false, provider_called: false } as const;+ if (!rerankerOpts.enabled || rerankerOpts.topNIn <= 0) return { meta: { ...base, eligible: false, ineligible_reason: 'reranker_off' } };+ if (egressDenied) return { meta: { ...base, eligible: false, ineligible_reason: 'egress_denied' } };+ if (deduped.length === 0) return { meta: { ...base, eligible: false, ineligible_reason: 'no_candidates' } };++ const { engine, query, aliasHopOpts, resolvedMode } = req;+ const [alias, exactHits] = await Promise.all([+ lookupAliasHop(engine, query, aliasHopOpts),+ structuralExactLookup(engine, query, exactLookupOpts).catch(() => [] as SearchResult[]),+ ]);+ let grade = gradePreRerank({+ candidates: deduped,+ query,+ exactLookupHits: exactHits,+ aliasCanonicals: alias ? aliasHopCanonicals(alias, aliasHopOpts) : [],+ aliasTokenHop: alias ? tokenHopWouldFire(alias, aliasHopOpts) : false,+ multimodal,+ cosineFloor: resolvedMode.evidence_cosine_floor,+ minGap: resolvedMode.reranker_gate_min_gap,+ });+ if (grade.strong && grade.top) {+ grade = applyRerankGateTrust(grade, await pageTrust(req, grade.top, deduped), req.opts?.minTrust);+ }+ const s1 = req.decide?.policies.rerank;+ const skipReason = grade.strong && RERANK_GATE_SKIP_REASONS.has(grade.reason as PreRerankStrongReason);+ const blocked = !grade.strong ? undefined+ : !skipReason ? 'shadow_only_reason' as const+ : s1 && s1.effective !== 'off' ? 'decide_rerank_slot' as const+ : undefined;+ const meta: RerankGateMeta = {+ ...base,+ eligible: true,+ grade: grade.strong ? 'strong' : 'not_strong',+ reason: grade.reason,+ ...(grade.top_cosine !== undefined ? { top_cosine: grade.top_cosine } : {}),+ ...(grade.gap !== undefined ? { gap: grade.gap } : {}),+ would_skip: grade.strong && blocked === undefined,+ ...(blocked ? { skip_blocked: blocked } : {}),+ };+ return { meta, lookups: { alias, exactHits } };+}diff --git a/src/core/search/mode.ts b/src/core/search/mode.tsindex 3f326e6187..83d231457a 100644--- a/src/core/search/mode.ts+++ b/src/core/search/mode.ts@@ -42,6 +42,14 @@ import {normalizeMetadataBoostGate,type MetadataBoostGate,} from './metadata-boost-gate.ts';+import {+ DEFAULT_RERANK_GATE,+ DEFAULT_RERANK_GATE_MIN_GAP,+ normalizeRerankGate,+ normalizeRerankGateMinGap,+ type RerankGateMode,+} from './crag.ts';+import { DEFAULT_HIGH_COSINE_FLOOR } from './evidence.ts';/*** Look up the `reranker.default_timeout_ms` declared by the resolved@@ -199,11 +207,24 @@ export interface ModeBundle {/*** v0.46.15 — cosine floor for evidence's `high_vector_match` (see* evidence.ts DEFAULT_HIGH_COSINE_FLOOR). Config `search.evidence_cosine_floor`.- * Deliberately EXCLUDED from knobsHash: it shapes the evidence LABEL, not- * the result set — a floor change serves TTL-bounded stale labels on cached- * rows, which is acceptable for an operator tuning knob.+ * Labels results and decides the rerank gate's `high_vector_match` grade+ * (`reranker_gate`), so it is part of knobsHash (`ecf=`, v=31).*/evidence_cosine_floor: number | undefined;+ /**+ * 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`).+ * `off` in every bundle. Override: per-call HybridSearchOpts.rerankGate →+ * `search.reranker.gate` → bundle. knobsHash part `rrg=`.+ */+ reranker_gate: RerankGateMode;+ /**+ * W3 — δ: the cosine margin a `high_vector_match` rank-1 needs over the best+ * candidate from a different page before the gate calls it strong. [0, 1].+ * Override: `search.reranker.gate_min_gap` → bundle. knobsHash part `rrgg=`.+ */+ reranker_gate_min_gap: number;// v0.36 cross-modal wave knobs (D2 + D3 + D6 + D8 + D13 + LLM-intent).// All three mode bundles default these to the same values — cross-modal@@ -455,6 +476,8 @@ export const MODE_BUNDLES: Readonly<Record<SearchMode, Readonly<ModeBundle>>> =// T2 — title-phrase boost ON by default (correctness fix, cheap + gated).title_boost: 1.25,evidence_cosine_floor: 0.8,+ reranker_gate: DEFAULT_RERANK_GATE,+ reranker_gate_min_gap: DEFAULT_RERANK_GATE_MIN_GAP,// v0.36 cross-modal defaults (same across all modes — opt-in)cross_modal_both_text_weight: 0.6,cross_modal_both_image_weight: 0.4,@@ -516,6 +539,8 @@ export const MODE_BUNDLES: Readonly<Record<SearchMode, Readonly<ModeBundle>>> =// T2 — title-phrase boost ON by default (correctness fix, cheap + gated).title_boost: 1.25,evidence_cosine_floor: 0.8,+ reranker_gate: DEFAULT_RERANK_GATE,+ reranker_gate_min_gap: DEFAULT_RERANK_GATE_MIN_GAP,// v0.36 cross-modal defaults (same across all modes — opt-in)cross_modal_both_text_weight: 0.6,cross_modal_both_image_weight: 0.4,@@ -587,6 +612,8 @@ export const MODE_BUNDLES: Readonly<Record<SearchMode, Readonly<ModeBundle>>> =// T2 — title-phrase boost ON by default (correctness fix, cheap + gated).title_boost: 1.25,evidence_cosine_floor: 0.8,+ reranker_gate: DEFAULT_RERANK_GATE,+ reranker_gate_min_gap: DEFAULT_RERANK_GATE_MIN_GAP,// v0.36 cross-modal defaults (same across all modes — opt-in)cross_modal_both_text_weight: 0.6,cross_modal_both_image_weight: 0.4,@@ -659,8 +686,11 @@ export interface SearchKeyOverrides {floor_ratio?: number;// T2 — title-phrase boost override.title_boost?: number;- // v0.46.15 — evidence cosine-floor override (label-only; not in knobsHash).+ // v0.46.15 — evidence cosine-floor override (knobsHash `ecf=` since v=31).evidence_cosine_floor?: number;+ // W3 — confidence-gated reranking overrides.+ reranker_gate?: RerankGateMode;+ reranker_gate_min_gap?: number;// v0.36 cross-modal overridescross_modal_both_text_weight?: number;cross_modal_both_image_weight?: number;@@ -721,6 +751,9 @@ export interface SearchPerCallOpts {title_boost?: number;// v0.46.15 — evidence cosine-floor per-call override.evidence_cosine_floor?: number;+ // W3 — confidence-gated reranking per-call override (RERANK_GATE_MODES).+ reranker_gate?: RerankGateMode;+ reranker_gate_min_gap?: number;// v0.36 cross-modal per-call overridescross_modal_both_text_weight?: number;cross_modal_both_image_weight?: number;@@ -833,6 +866,8 @@ export function resolveSearchMode(input: ResolveSearchModeInput): ResolvedSearchfloor_ratio: pick('floor_ratio'),title_boost: pick('title_boost'),evidence_cosine_floor: pick('evidence_cosine_floor'),+ reranker_gate: pick('reranker_gate'),+ reranker_gate_min_gap: pick('reranker_gate_min_gap'),// v0.36 cross-modal knobscross_modal_both_text_weight: pick('cross_modal_both_text_weight'),cross_modal_both_image_weight: pick('cross_modal_both_image_weight'),@@ -908,7 +943,7 @@ export function attributeKnob<K extends keyof ModeBundle>(* reorder or add a knob without bumping a constant — a hash collision would* mean stale cache rows silently reading the wrong shape.*/-export const KNOBS_HASH_VERSION = 30;+export const KNOBS_HASH_VERSION = 31;/*** v0.36 (D8 / CDX-2) — second-arg context for the cache key. The@@ -1196,6 +1231,15 @@ export function knobsHash(// re-orders the fused page, so a `lexical` write must never serve an// `always` lookup. A partial-knobs literal hashes as `always` — the deliberate pre-wave hash identity, NOT the bundle default (`lexical`).`mbg=${knobs.metadata_boost_gate ?? DEFAULT_METADATA_BOOST_GATE}`,+ // v=31 additions (W3 confidence-gated reranking, append-only): the gate,+ // its δ and the evidence cosine floor. The gate's grade rides the stored+ // meta, and δ and the floor decide that grade, so rows written under one+ // setting must not serve another. The floor was label-only before this+ // block and stayed out of the hash.+ // Partial-knobs literals hash as the bundle defaults.+ `rrg=${knobs.reranker_gate ?? DEFAULT_RERANK_GATE}`,+ `rrgg=${(knobs.reranker_gate_min_gap ?? DEFAULT_RERANK_GATE_MIN_GAP).toFixed(3)}`,+ `ecf=${(knobs.evidence_cosine_floor ?? DEFAULT_HIGH_COSINE_FLOOR).toFixed(3)}`,// System One (append-only, emitted only when a decide slot is not off, so// the all-off key is unchanged and needs no version bump)....(ctx?.decide ? [`dec=${ctx.decide}`] : []),@@ -1326,14 +1370,21 @@ export function loadOverridesFromConfig(if (Number.isFinite(n) && n >= 1.0 && n <= 5.0) out.title_boost = n;}- // v0.46.15 — evidence cosine floor (label-only knob; deliberately not in- // knobsHash). [0, 1] sanity-bounded.+ // v0.46.15 — evidence cosine floor. [0, 1] sanity-bounded. Part of+ // knobsHash since v=31: it also decides the rerank gate's grade.const ecf = get('search.evidence_cosine_floor');if (ecf !== undefined) {const n = parseFloat(ecf);if (Number.isFinite(n) && n >= 0 && n <= 1) out.evidence_cosine_floor = n;}+ // W3 — confidence-gated reranking. One parse contract each (crag.ts);+ // anything unrecognized falls through to the bundle.+ const rrg = normalizeRerankGate(get('search.reranker.gate'));+ if (rrg !== undefined) out.reranker_gate = rrg;+ const rrgg = normalizeRerankGateMinGap(get('search.reranker.gate_min_gap'));+ if (rrgg !== undefined) out.reranker_gate_min_gap = rrgg;+// v0.36 cross-modal overrides (D3 registry)const cmbt = get('search.cross_modal.both_mode_text_weight');if (cmbt !== undefined) {@@ -1486,6 +1537,8 @@ export const KNOB_CONFIG_KEY: Readonly<Record<keyof ModeBundle, string>> = Objecfloor_ratio: 'search.floor_ratio',title_boost: 'search.title_boost',evidence_cosine_floor: 'search.evidence_cosine_floor',+ reranker_gate: 'search.reranker.gate',+ reranker_gate_min_gap: 'search.reranker.gate_min_gap',cross_modal_both_text_weight: 'search.cross_modal.both_mode_text_weight',cross_modal_both_image_weight: 'search.cross_modal.both_mode_image_weight',image_query_text_refinement_weight: 'search.image_query.text_refinement_weight',diff --git a/src/core/search/modes-report.ts b/src/core/search/modes-report.tsindex bb7ebbfa2e..f654e22d61 100644--- a/src/core/search/modes-report.ts+++ b/src/core/search/modes-report.ts@@ -37,7 +37,10 @@ export const KNOB_DESCRIPTIONS: Record<keyof ModeBundle, string> = {floor_ratio: 'Floor-ratio gate for metadata boosts (0..1, undefined = off)',title_boost: 'Title-phrase boost multiplier (query is a title token-run; 1.0 = off)',// v0.46.15 retrieval wave knobs- evidence_cosine_floor: 'Cosine floor for evidence high_vector_match (label-only; 0..1)',+ evidence_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, 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)cross_modal_both_text_weight: "D6 'both'-mode RRF weight for text branch (0.6 default)",diff --git a/src/core/search/telemetry.ts b/src/core/search/telemetry.tsindex 55ff9c53ca..12c89e6452 100644--- a/src/core/search/telemetry.ts+++ b/src/core/search/telemetry.ts@@ -76,6 +76,25 @@ export const EMPTY_RESULT_MODE = 'empty_result';export type EmptyResultCause = 'vector_disabled' | 'budget_dropped_all' | 'keyword_zero';+/**+ * W3 — reserved `mode` value for the rerank gate counters, on the same+ * (date, mode, intent) PK with zero new DDL: the intent slot names the+ * counter (`eligible`, `graded`, `would_skip`, `provider_calls`,+ * `reason:<grade reason>`, `ineligible:<why>`), `count` carries it.+ * readSearchStats diverts these rows out of the call/intent/mode aggregates.+ * Written only when `search.reranker.gate` is not `off`.+ */+export const RERANK_GATE_TELEMETRY_MODE = 'rerank_gate';++/** The rerank gate counter rows one search contributes (intent slot of the reserved rows). */+export function rerankGateCounters(gate: NonNullable<HybridSearchMeta['rerank_gate']>): string[] {+ if (!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.provider_called) out.push('provider_calls');+ return out;+}+/*** WP2/T3 — why did this search return zero results? Precedence: a budget* that dropped everything (only reachable with GBRAIN_SEARCH_SALVAGE=off;@@ -175,7 +194,12 @@ class TelemetryWriter {// WP2/T3 — empty-result cause rollup. Cache HITS are excluded: an empty// hit slice is an offset-past-end artifact, not a retrieval failure.if (opts.results_count === 0 && meta.cache?.status !== 'hit') {- this.recordEmptyResult(date, classifyEmptyResultCause(meta));+ this.bumpReserved(date, EMPTY_RESULT_MODE, classifyEmptyResultCause(meta));+ }+ // W3 — rerank gate counters (reserved rows). Cache hits replay a stored+ // decision, not a new one, so they are excluded.+ if (meta.rerank_gate && meta.cache?.status !== 'hit') {+ for (const counter of rerankGateCounters(meta.rerank_gate)) this.bumpReserved(date, RERANK_GATE_TELEMETRY_MODE, counter);}this.pendingCount += 1;@@ -185,18 +209,18 @@ class TelemetryWriter {}/**- * Bump the reserved (date, EMPTY_RESULT_MODE, cause) bucket. Only `count`- * carries signal on these rows — every other column stays 0 and the flush- * SQL is unchanged (zero new DDL).+ * Bump a reserved (date, mode, intent) counter bucket (EMPTY_RESULT_MODE,+ * RERANK_GATE_TELEMETRY_MODE). Only `count` carries signal on these rows —+ * every other column stays 0 and the flush SQL is unchanged (zero new DDL).*/- private recordEmptyResult(date: string, cause: EmptyResultCause): void {- const key = `${date}::${EMPTY_RESULT_MODE}::${cause}`;+ private bumpReserved(date: string, mode: string, intent: string): void {+ const key = `${date}::${mode}::${intent}`;let b = this.buckets.get(key);if (!b) {b = {date,- mode: EMPTY_RESULT_MODE,- intent: cause,+ mode,+ intent,count: 0,sum_results: 0,sum_tokens: 0,@@ -461,6 +485,40 @@ export interface StatsWindow {// EMPTY_RESULT_MODE rows; never counted in total_calls or the// intent/mode distributions.empty_results: { total: number; by_cause: Record<string, number> };+ // W3 — rerank gate counters, diverted from the reserved+ // RERANK_GATE_TELEMETRY_MODE rows (never counted in total_calls).+ rerank_gate: RerankGateStats;+}++export interface RerankGateStats {+ /** Searches where the reranker would have run and the gate was consulted. */+ eligible: number;+ graded: number;+ would_skip: number;+ /** would_skip / graded (0 when nothing was graded). */+ would_skip_rate: number;+ provider_calls: number;+ /** Graded searches by grade reason (strong and not-strong reasons). */+ by_reason: Record<string, number>;+ /** Searches the gate saw but did not grade, by why (reranker off, egress denied, no candidates). */+ ineligible: Record<string, number>;+}++function emptyRerankGateStats(): RerankGateStats {+ 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. */+function addRerankGateRow(stats: RerankGateStats, counter: string, count: number): void {+ if (counter.startsWith('reason:')) {+ const k = counter.slice('reason:'.length);+ stats.by_reason[k] = (stats.by_reason[k] ?? 0) + count;+ } 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 === 'provider_calls') {+ stats[counter] += count;+ }}export async function readSearchStats(@@ -525,6 +583,7 @@ export async function readSearchStats(let r1_high = 0;let empty_total = 0;const empty_by_cause: Record<string, number> = {};+ const rerank_gate = emptyRerankGateStats();for (const r of rows) {// WP2/T3 — reserved empty-result rows carry cause in the intent slot;@@ -534,6 +593,10 @@ export async function readSearchStats(empty_by_cause[r.intent] = (empty_by_cause[r.intent] ?? 0) + r.count;continue;}+ if (r.mode === RERANK_GATE_TELEMETRY_MODE) {+ addRerankGateRow(rerank_gate, r.intent, r.count);+ continue;+ }total_calls += r.count;cache_hits += r.cache_hit;cache_misses += r.cache_miss;@@ -569,6 +632,7 @@ export async function readSearchStats(rank1_count: count_rank1,rank1_distribution: { lt_solid: r1_lt, solid: r1_solid, high: r1_high },empty_results: { total: empty_total, by_cause: empty_by_cause },+ rerank_gate: { ...rerank_gate, would_skip_rate: rerank_gate.graded > 0 ? rerank_gate.would_skip / rerank_gate.graded : 0 },};} catch {// Best-effort by design: a pre-v0.32.3 brain WITHOUT the search_telemetry@@ -594,6 +658,7 @@ export async function readSearchStats(rank1_count: 0,rank1_distribution: { lt_solid: 0, solid: 0, high: 0 },empty_results: { total: 0, by_cause: {} },+ rerank_gate: emptyRerankGateStats(),};}}diff --git a/src/core/types.ts b/src/core/types.tsindex e4a6870523..b3b84de80a 100644--- a/src/core/types.ts+++ b/src/core/types.ts@@ -2169,6 +2169,14 @@ export interface HybridSearchMeta {* recall there; the gate is never consulted).*/metadata_boost_gate?: import('./search/metadata-boost-gate.ts').MetadataBoostGateDecision;+ /**+ * W3 — the confidence gate in front of the cross-encoder (search/hybrid/rerank-gate.ts):+ * eligibility, the pre-rerank grade and reason, rank-1 cosine and its gap+ * over the best other page, the candidate count, `would_skip` and whether a+ * reranker provider call was made. Present only on the main RRF path and+ * only when `search.reranker.gate` is not `off`.+ */+ rerank_gate?: import('./search/hybrid/rerank-gate.ts').RerankGateMeta;/*** v0.32.x (search-lite): token budget enforcement metadata. Omitted when* no budget was applied (backward-compatible with pre-search-litediff --git a/test/cross-modal-phase1.test.ts b/test/cross-modal-phase1.test.tsindex 7ae5cda0dd..ddc95c189d 100644--- a/test/cross-modal-phase1.test.ts+++ b/test/cross-modal-phase1.test.ts@@ -179,7 +179,7 @@ describe('D2 — knobsHash differs across cross-modal knob values', () => {return resolveSearchMode({ mode: 'balanced' });}- test('KNOBS_HASH_VERSION is 30 (cross-modal still appended; …; 25→26 salience/recency + intent_patterns fold #4415; 26→27 adaptive-return gate + intent fold E5b/F11; 27→28 compiledTruthBoost synthetic-row suppression #4256; 28→29 evb= expansion variant budget fold; 29→30 exact-title order #5889)', () => {+ test('KNOBS_HASH_VERSION is 31 (cross-modal still appended; …; 25→26 salience/recency + intent_patterns fold #4415; 26→27 adaptive-return gate + intent fold E5b/F11; 27→28 compiledTruthBoost synthetic-row suppression #4256; 28→29 evb= expansion variant budget fold; 29→30 exact-title order #5889; 30→31 rrg=/rrgg=/ecf= rerank gate fold W3)', () => {// v0.35 ladder: 1→2 reranker, 2→3 floor_ratio. v0.36 piggybacks on v=3// with 7 cross-modal knobs + column/provider context. v0.40.4 (salem) +// v0.39 T21 (master) bump to v=4 for graph_signals + schema-pack fields.@@ -217,7 +217,7 @@ describe('D2 — knobsHash differs across cross-modal knob values', () => {// confidence floor, Phase E2 / Cat 13) — same unshipped epoch, no extra bump.// 29→30 (#5889): exact-title-first title-arm order + weight-A remote// title predicate reorder rows for identical knobs; version-only.- expect(KNOBS_HASH_VERSION).toBe(30);+ expect(KNOBS_HASH_VERSION).toBe(31);});test('flipping unified_multimodal changes the hash', () => {diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex ae8b3077a6..b7a70d0672 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -734,6 +734,7 @@"relational_rerank_pin?: RelationalRerankPinDecision | undefined","relaxed_dropped?: number | undefined","rerank?: { model_resolved: string; } | undefined",+ "rerank_gate?: RerankGateMeta | undefined","retrieved_count?: number | undefined","token_budget?: { budget: number; used: number; kept: number; dropped: number; truncated?: boolean; } | undefined","vector_enabled: boolean",@@ -7298,6 +7299,7 @@"relationalRetrieval?: boolean | undefined","relationalRetrievalDepth?: number | undefined","requireSafeChunks?: boolean | undefined",+ "rerankGate?: RerankGateMode | undefined","reranker?: { enabled: boolean; topNIn: number; topNOut: number | null; model?: string; timeoutMs?: number; rerankerFn?: (input: { query: string; documents: string[]; topN?: number; model?: string; signal?: AbortSignal; timeoutMs?: number; }) => Promise<{ index: number; relevanceScore: number; }[]>; } | undefined","rrfK?: number | undefined","salience?: \"on\" | \"off\" | \"strong\" | undefined",@@ -8369,6 +8371,7 @@"relational_rerank_pin?: RelationalRerankPinDecision | undefined","relaxed_dropped?: number | undefined","rerank?: { model_resolved: string; } | undefined",+ "rerank_gate?: RerankGateMeta | undefined","retrieved_count?: number | undefined","token_budget?: { budget: number; used: number; kept: number; dropped: number; truncated?: boolean; } | undefined","vector_enabled: boolean",diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex d69bb896dc..d733aae402 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -105,6 +105,8 @@ test/repair-failed-writes-drift-w411.test.tstest/repair-fences.test.tstest/repair-frontmatter.test.tstest/scripts/test-stress-postgres.test.ts+test/search/rerank-gate-hybrid.test.ts+test/search/rerank-gate-telemetry.test.tstest/shared-content-freshness.test.tstest/shared-skills-catalog.test.tstest/shared-skills-retention-capacity.test.tsdiff --git a/test/search-alias-resolved-boost.test.ts b/test/search-alias-resolved-boost.test.tsindex ec5e5e4244..f6c99b1e70 100644--- a/test/search-alias-resolved-boost.test.ts+++ b/test/search-alias-resolved-boost.test.ts@@ -81,7 +81,7 @@ describe('alias_resolved boost stage', () => {});describe('KNOBS_HASH_VERSION', () => {- it('is 30 (…; 25→26 salience/recency + intent_patterns fold #4415; 26→27 adaptive-return gate + intent fold E5b/F11; 27→28 compiledTruthBoost synthetic-row suppression #4256; 28→29 evb= expansion variant budget fold; 29→30 exact-title order #5889)', () => {+ it('is 31 (…; 25→26 salience/recency + intent_patterns fold #4415; 26→27 adaptive-return gate + intent fold E5b/F11; 27→28 compiledTruthBoost synthetic-row suppression #4256; 28→29 evb= expansion variant budget fold; 29→30 exact-title order #5889; 30→31 rrg=/rrgg=/ecf= rerank gate fold W3)', () => {// mw2: 21→22 result-stamp/injection epoch (#1663 #3995 #3783 #4220).// #4352 follow-up: 22→23 private-visibility posture fold (xp=).// #4358 residual: 23→24 negative-offset cache-skip gap.@@ -96,6 +96,6 @@ describe('KNOBS_HASH_VERSION', () => {// variant fusion reorders rows for identical knobs; null hashes as legacy.// 29→30 (#5889): exact-title-first title-arm order + weight-A remote// title predicate reorder rows for identical knobs; version-only.- expect(KNOBS_HASH_VERSION).toBe(30);+ expect(KNOBS_HASH_VERSION).toBe(31);});});diff --git a/test/search-mode.test.ts b/test/search-mode.test.tsindex 63fed5035f..c727b000c0 100644--- a/test/search-mode.test.ts+++ b/test/search-mode.test.ts@@ -74,6 +74,8 @@ describe('SEARCH_MODES + MODE_BUNDLES canonical shape', () => {floor_ratio: undefined,title_boost: 1.25,evidence_cosine_floor: 0.8,+ reranker_gate: 'off',+ reranker_gate_min_gap: 0.05,...CROSS_MODAL_DEFAULTS,graph_signals: false,...CR_DISABLED_DEFAULT,@@ -120,6 +122,8 @@ describe('SEARCH_MODES + MODE_BUNDLES canonical shape', () => {floor_ratio: undefined,title_boost: 1.25,evidence_cosine_floor: 0.8,+ reranker_gate: 'off',+ reranker_gate_min_gap: 0.05,...CROSS_MODAL_DEFAULTS,graph_signals: true,...CR_DISABLED_DEFAULT,@@ -164,6 +168,8 @@ describe('SEARCH_MODES + MODE_BUNDLES canonical shape', () => {floor_ratio: undefined,title_boost: 1.25,evidence_cosine_floor: 0.8,+ reranker_gate: 'off',+ reranker_gate_min_gap: 0.05,...CROSS_MODAL_DEFAULTS,graph_signals: true,...CR_DISABLED_DEFAULT,@@ -505,7 +511,7 @@ describe('knobsHash determinism + cross-mode separation (CDX-4)', () => {// Cat 13) — same unshipped epoch; a partial literal hashes as always.// 29→30 (#5889): exact-title-first title-arm order + weight-A remote// title predicate reorder rows for identical knobs; version-only.- expect(KNOBS_HASH_VERSION).toBe(30);+ expect(KNOBS_HASH_VERSION).toBe(31);});test('#3515: detail set vs unset produces DIFFERENT hashes (cache contamination prevention)', () => {@@ -543,7 +549,7 @@ describe('knobsHash determinism + cross-mode separation (CDX-4)', () => {// Phase E2 / Cat 13) — same unshipped epoch; null hashes as off.// v=29 ALSO carries mbg= (metadata boost gate, ranker wave Phase E3 /// Cat 13) — same unshipped epoch; a partial literal hashes as always.- expect(KNOBS_HASH_VERSION).toBe(30);+ expect(KNOBS_HASH_VERSION).toBe(31);});test('#4352 follow-up: excludePrivate true vs false produces DIFFERENT hashes (cache contamination prevention)', () => {@@ -759,7 +765,7 @@ describe('v0.40.4 — graph_signals knob', () => {});describe('v0.42.3.0 — autocut knobs', () => {- test('KNOBS_HASH_VERSION is 30 (…; 25→26 salience/recency + intent_patterns fold #4415; 26→27 adaptive-return gate + intent fold E5b/F11; 27→28 compiledTruthBoost synthetic-row suppression #4256; 28→29 evb= expansion variant budget fold)', () => {+ test('KNOBS_HASH_VERSION is 31 (…; 25→26 salience/recency + intent_patterns fold #4415; 26→27 adaptive-return gate + intent fold E5b/F11; 27→28 compiledTruthBoost synthetic-row suppression #4256; 28→29 evb= expansion variant budget fold; 30→31 rrg=/rrgg=/ecf= rerank gate fold W3)', () => {// 28→29: evb= expansion variant budget fold (ranker wave) — budget-weighted// variant fusion reorders rows for identical knobs; null hashes as legacy.// v=29 ALSO carries rrp= (relational rerank pin, ranker wave R1) — same@@ -768,7 +774,7 @@ describe('v0.42.3.0 — autocut knobs', () => {// Phase E2 / Cat 13) — same unshipped epoch; null hashes as off.// v=29 ALSO carries mbg= (metadata boost gate, ranker wave Phase E3 /// Cat 13) — same unshipped epoch; a partial literal hashes as always.- expect(KNOBS_HASH_VERSION).toBe(30);+ expect(KNOBS_HASH_VERSION).toBe(31);});test('bundle defaults: autocut off in every bundle (ranker wave rule R2), jump 0.20 kept for operators who re-enable it', () => {@@ -948,13 +954,15 @@ describe('v0.46.15 — retrieval-wave knobs (evidence_cosine_floor + autocut_minexpect(base).not.toBe(tuned);});- test('evidence_cosine_floor is label-only — deliberately NOT in knobsHash', () => {- // The floor relabels evidence strings on already-fetched results; it never- // changes WHICH rows come back, so folding it into the cache key would- // fragment the cache for zero isolation benefit.+ test('evidence_cosine_floor folds into knobsHash (ecf=, v=31): it decides the rerank gate grade', () => {+ // Label-only until W3: the floor now decides whether a high_vector_match+ // rank-1 is gate-strong, so a row written under one floor must not serve+ // a lookup under another. An explicit bundle-default floor hashes as the default.const base = knobsHash(resolveSearchMode({ mode: 'balanced' }));const relabeled = knobsHash(resolveSearchMode({ mode: 'balanced', overrides: { evidence_cosine_floor: 0.5 } }));- expect(relabeled).toBe(base);+ const same = knobsHash(resolveSearchMode({ mode: 'balanced', overrides: { evidence_cosine_floor: 0.8 } }));+ expect(relabeled).not.toBe(base);+ expect(same).toBe(base);});});@@ -1102,7 +1110,7 @@ describe('ranker wave (R1) — relational_rerank_pin knob (relational rows bypasexpect(one).not.toBe(dflt);expect(one).not.toBe(off);// The pin rides KNOBS_HASH_VERSION 29 together with evb= — no separate bump.- expect(KNOBS_HASH_VERSION).toBe(30);+ expect(KNOBS_HASH_VERSION).toBe(31);});});diff --git a/test/search/knobs-hash-reranker.test.ts b/test/search/knobs-hash-reranker.test.tsindex 4f5414749d..50cc6a3af7 100644--- a/test/search/knobs-hash-reranker.test.ts+++ b/test/search/knobs-hash-reranker.test.ts@@ -45,7 +45,7 @@ function baseKnobs(): ResolvedSearchKnobs {}describe('KNOBS_HASH_VERSION + version invariants', () => {- test('version is 30 (…; 24→25 keywordOrFallback knob kof= #3617; 25→26 salience/recency + intent_patterns fold #4415; 26→27 adaptive-return gate + intent fold E5b/F11; 27→28 compiledTruthBoost synthetic-row suppression #4256/#3695; 28→29 evb= expansion variant budget fold; 29→30 exact-title order #5889)', () => {+ test('version is 31 (…; 24→25 keywordOrFallback knob kof= #3617; 25→26 salience/recency + intent_patterns fold #4415; 26→27 adaptive-return gate + intent fold E5b/F11; 27→28 compiledTruthBoost synthetic-row suppression #4256/#3695; 28→29 evb= expansion variant budget fold; 29→30 exact-title order #5889; 30→31 rrg=/rrgg=/ecf= rerank gate fold W3)', () => {// v0.35.0.0: 1→2 to fold reranker fields. v0.35.6.0: 2→3 to fold// floor_ratio. v0.36 wave: piggybacks on v=3 with 7 cross-modal knobs// (D2) PLUS column + provider context (D8/CDX-2 cross-column isolation).@@ -102,7 +102,7 @@ describe('KNOBS_HASH_VERSION + version invariants', () => {// Cat 13) — same unshipped epoch; a partial literal hashes as always.// 29→30 (#5889): exact-title-first title-arm order + weight-A remote// title predicate reorder rows for identical knobs; version-only.- expect(KNOBS_HASH_VERSION).toBe(30);+ expect(KNOBS_HASH_VERSION).toBe(31);});test('hash is 16 hex chars regardless of reranker config', () => {diff --git a/test/search/rerank-gate-grade.test.ts b/test/search/rerank-gate-grade.test.tsnew file mode 100644index 0000000000..cf300ba94b--- /dev/null+++ b/test/search/rerank-gate-grade.test.ts@@ -0,0 +1,158 @@+/**+ * W3 — the pre-rerank grade (crag.ts `gradePreRerank`, `applyRerankGateTrust`).+ *+ * Protects: which deduped candidate sets the rerank gate calls strong, and+ * why. Every strong reason, every not-strong reason, the δ gap measured+ * against a DIFFERENT page (several chunks of rank-1's page do not count),+ * candidates out of cosine order, multimodal, the full-title rule and the+ * trust floor.+ * Fails when: a phrase inside a longer title counts as identity, the gap is+ * taken against rank-1's own chunks or against the next row instead of the+ * best other page, an image row or multimodal query grades strong, an+ * external_untrusted page passes the floor, or ambiguous identity grades strong.+ * Seams: none (pure).+ */+import { describe, expect, test } from 'bun:test';+import {+ DEFAULT_RERANK_GATE_MIN_GAP,+ applyRerankGateTrust,+ gradePreRerank,+ normalizeRerankGate,+ normalizeRerankGateMinGap,+ type PreRerankGradeInput,+} from '../../src/core/search/crag.ts';+import type { SearchResult } from '../../src/core/types.ts';++const row = (slug: string, cosine: number | undefined, extra: Partial<SearchResult> = {}): SearchResult => ({+ slug, page_id: slug.length, title: slug, type: 'note', source_id: 'default', chunk_id: Math.round((cosine ?? 0) * 1000),+ chunk_index: 0, chunk_text: slug, chunk_source: 'compiled_truth', score: 1, stale: false,+ ...(cosine === undefined ? {} : { cosine }), ...extra,+} as SearchResult);++const grade = (candidates: SearchResult[], over: Partial<PreRerankGradeInput> = {}) => gradePreRerank({+ candidates, query: 'what is the orbital period', exactLookupHits: [], aliasCanonicals: [], multimodal: false, ...over,+});++describe('gradePreRerank — strong reasons', () => {+ test('exactly one exact-lookup page is strong exact_lookup, and vouches for that page', () => {+ const hit = row('people/alice-example', undefined, { page_id: 7, exact_lookup: 'slug' });+ const g = grade([row('notes/a', 0.2)], { exactLookupHits: [hit] });+ expect(g).toMatchObject({ strong: true, reason: 'exact_lookup', top: { slug: 'people/alice-example', source_id: 'default', page_id: 7 } });+ });++ test('exactly one alias page is strong alias_hit', () => {+ const g = grade([row('notes/a', 0.2)], { aliasCanonicals: [{ slug: 'projects/mingtang', source_id: 'default' }] });+ expect(g).toMatchObject({ strong: true, reason: 'alias_hit', top: { slug: 'projects/mingtang' } });+ });++ test('a full-title identity at rank 1 is strong exact_title_match', () => {+ const g = grade([row('companies/acme', 0.1, { title: 'Acme Widget', title_match_boost: 1.25 })], { query: ' acme WIDGET ' });+ expect(g).toMatchObject({ strong: true, reason: 'exact_title_match' });+ });++ test('a high cosine leading the best other page by δ is strong high_vector_match', () => {+ const g = grade([row('notes/gold', 0.92), row('notes/b', 0.85), row('notes/c', 0.5)]);+ expect(g.strong).toBe(true);+ expect(g.reason).toBe('high_vector_match');+ expect(g.top_cosine).toBeCloseTo(0.92, 10);+ expect(g.gap).toBeCloseTo(0.07, 10);+ });++ test('a single page among the candidates leads by its own cosine', () => {+ const g = grade([row('notes/gold', 0.9), row('notes/gold', 0.88, { chunk_id: 5 })]);+ expect(g).toMatchObject({ strong: true, reason: 'high_vector_match' });+ expect(g.gap).toBeCloseTo(0.9, 10);+ });+});++describe('gradePreRerank — not strong', () => {+ test('two exact-lookup pages or two alias pages are ambiguous identity', () => {+ const hits = [row('a/one', undefined), row('a/two', undefined)];+ expect(grade([row('notes/a', 0.99)], { exactLookupHits: hits }).reason).toBe('identity_ambiguous');+ const two = [{ slug: 'p/hall', source_id: 'default' }, { slug: 'p/other-hall', source_id: 'default' }];+ expect(grade([row('notes/a', 0.99)], { aliasCanonicals: two })).toMatchObject({ strong: false, reason: 'identity_ambiguous' });+ });++ test('a single-token alias hop that would move rank 1 is ambiguous identity', () => {+ expect(grade([row('notes/a', 0.99)], { aliasTokenHop: true })).toMatchObject({ strong: false, reason: 'identity_ambiguous' });+ });++ test('exact lookup wins over alias ambiguity (it is applied last, so it is rank 1)', () => {+ const two = [{ slug: 'p/hall', source_id: 'default' }, { slug: 'p/other-hall', source_id: 'default' }];+ expect(grade([], { exactLookupHits: [row('p/hall', undefined)], aliasCanonicals: two }).reason).toBe('exact_lookup');+ });++ test('a phrase inside a longer title is not identity; the cosine rule still decides', () => {+ const partial = row('companies/acme', 0.3, { title: 'Acme Widget Holdings', title_match_boost: 1.25 });+ expect(grade([partial], { query: 'acme widget' })).toMatchObject({ strong: false, reason: 'cosine_below_floor' });+ const partialHigh = row('companies/acme', 0.95, { title: 'Acme Widget Holdings', title_match_boost: 1.25 });+ expect(grade([partialHigh], { query: 'acme widget' }).reason).toBe('high_vector_match');+ });++ test('no candidates, no cosine, cosine below the floor', () => {+ expect(grade([]).reason).toBe('no_candidates');+ expect(grade([row('notes/a', undefined)]).reason).toBe('no_cosine');+ expect(grade([row('notes/a', 0.79)])).toMatchObject({ strong: false, reason: 'cosine_below_floor', top_cosine: 0.79 });+ expect(grade([row('notes/a', 0.79)], { cosineFloor: 0.7 }).strong).toBe(true);+ });++ test('the gap is against the best OTHER page, not rank-1 own chunks and not the next row', () => {+ // Out of cosine order: the best other page sits at index 3.+ const candidates = [row('notes/gold', 0.9), row('notes/gold', 0.89, { chunk_id: 2 }), row('notes/b', 0.7), row('notes/c', 0.87)];+ const g = grade(candidates);+ expect(g).toMatchObject({ strong: false, reason: 'gap_below_min' });+ expect(g.gap).toBeCloseTo(0.03, 10);+ expect(grade(candidates, { minGap: 0 }).strong).toBe(true);+ });++ test('a rank-1 that is not the cosine leader fails at δ = 0', () => {+ const g = grade([row('notes/a', 0.85), row('notes/b', 0.9), row('notes/c', 0.4)], { minGap: 0 });+ expect(g.reason).toBe('gap_below_min');+ expect(g.gap).toBeCloseTo(-0.05, 10);+ });++ test('multimodal queries and image rows are never strong, even with identity-like signals on rank 1', () => {+ expect(grade([row('notes/a', 0.99)], { multimodal: true }).reason).toBe('multimodal');+ expect(grade([row('img/a', 0.99, { modality: 'image' })]).reason).toBe('multimodal');+ const titled = row('companies/acme', 0.99, { title: 'Acme', title_match_boost: 1.25, modality: 'image' });+ expect(grade([titled], { query: 'acme' }).strong).toBe(false);+ });++ test('image rows do not set the gap for a text rank-1', () => {+ const g = grade([row('notes/gold', 0.9), row('img/b', 0.89, { modality: 'image' }), row('notes/c', 0.5)]);+ expect(g.reason).toBe('high_vector_match');+ expect(g.gap).toBeCloseTo(0.4, 10);+ });+});++describe('applyRerankGateTrust', () => {+ const strong = grade([row('notes/gold', 0.95)]);+ test('external_untrusted rank-1 cannot skip; unknown and higher tiers pass', () => {+ expect(applyRerankGateTrust(strong, 'external_untrusted')).toMatchObject({ strong: false, reason: 'below_trust_floor' });+ expect(applyRerankGateTrust(strong, 'unknown').strong).toBe(true);+ expect(applyRerankGateTrust(strong, undefined).strong).toBe(true);+ expect(applyRerankGateTrust(strong, 'agent_written').strong).toBe(true);+ });+ test('a stricter caller floor raises it', () => {+ expect(applyRerankGateTrust(strong, 'agent_written', 'tool_observed').reason).toBe('below_trust_floor');+ expect(applyRerankGateTrust(strong, 'operator_curated', 'tool_observed').strong).toBe(true);+ });+ test('a not-strong grade passes through unchanged', () => {+ const weak = grade([row('notes/a', 0.1)]);+ expect(applyRerankGateTrust(weak, 'external_untrusted')).toBe(weak);+ });+});++describe('parse contracts', () => {+ test('gate literals only, any case; everything else is unset', () => {+ expect(normalizeRerankGate(' Shadow ')).toBe('shadow');+ expect(normalizeRerankGate('off')).toBe('off');+ for (const v of ['', 'true', 'yes', 1, null, undefined, {}]) expect(normalizeRerankGate(v)).toBeUndefined();+ });+ test('δ is a number in [0, 1]', () => {+ expect(normalizeRerankGateMinGap('0')).toBe(0);+ expect(normalizeRerankGateMinGap(0.05)).toBe(0.05);+ for (const v of ['-0.1', '1.5', 'abc', '', NaN, null]) expect(normalizeRerankGateMinGap(v)).toBeUndefined();+ expect(DEFAULT_RERANK_GATE_MIN_GAP).toBe(0.05);+ });+});diff --git a/test/search/rerank-gate-hybrid.test.ts b/test/search/rerank-gate-hybrid.test.tsnew file mode 100644index 0000000000..0ccecde314--- /dev/null+++ b/test/search/rerank-gate-hybrid.test.ts@@ -0,0 +1,211 @@+/**+ * W3 — `search.reranker.gate: shadow` through hybridSearch: the gate grades+ * the deduped candidates before the cross-encoder and stamps+ * `meta.rerank_gate`, and nothing else changes.+ *+ * Protects: shadow results are byte-identical to off (rows, scores, order),+ * the reranker receives identical payloads, and the identity tiers are read+ * once (the gate's lookups are reused at the post-rerank position) — across+ * a strong vector match, a δ miss with several chunks of rank-1's page, a+ * full-title identity page with two chunks, an alias collision, a single+ * alias, a slug lookup and an external_untrusted rank-1.+ * 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`; 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, 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, SearchResult } from '../../src/core/types.ts';+import { installFixtureChunks } from '../helpers/page-projection.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.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;+ 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)) {+ test(`${query}: shadow is identical to off and grades ${EXPECTED[query].reason}`, async () => {+ const off = await run(engine, query, 'off');+ const shadow = await run(engine, query, 'shadow');+ expect(off.results.length).toBeGreaterThan(1);+ expect(off.payloads).toHaveLength(1);+ expect(shadow.payloads).toEqual(off.payloads);+ expect(JSON.stringify(shadow.results)).toBe(JSON.stringify(off.results));+ expect(shadow.aliasReads).toBe(off.aliasReads);+ expect(shadow.pageReads).toBe(off.pageReads);+ expect(off.meta.rerank_gate).toBeUndefined();+ expect(shadow.meta.rerank_gate).toMatchObject({+ mode: 'shadow', eligible: true, provider_called: true, candidates: expect.any(Number), ...EXPECTED[query],+ });+ if (!EXPECTED[query].skip_blocked) expect(shadow.meta.rerank_gate?.skip_blocked).toBeUndefined();+ });+ }++ test('several chunks of the identity page collapse identically under both settings', async () => {+ const shadow = await run(engine, 'Acme Widget', 'shadow');+ expect(shadow.results[0].slug).toBe('companies/acme-widget');+ expect(shadow.results.filter((r) => r.slug === 'companies/acme-widget')).toHaveLength(1);+ });++ test('the strong vector grade reports rank-1 cosine and its gap over the best other page', async () => {+ const gate = (await run(engine, 'orbital period of the gold probe', 'shadow')).meta.rerank_gate!;+ expect(gate.top_cosine).toBeCloseTo(1, 5);+ expect(gate.gap).toBeCloseTo(0.4, 5);+ const twins = (await run(engine, 'tidal locking near twins', 'shadow')).meta.rerank_gate!;+ expect(twins.gap).toBeCloseTo(0.02, 5);+ });++ test('a disabled reranker is not eligible and is not graded', async () => {+ let meta: HybridSearchMeta | undefined;+ await hybridSearch(engine, 'orbital period of the gold probe', {+ limit: 10, rerankGate: 'shadow', queryEmbedFn: () => basisEmbedding(12, DIM), onMeta: (m) => { meta = m; },+ reranker: { enabled: false, topNIn: 30, topNOut: null },+ });+ expect(meta!.rerank_gate).toEqual({ mode: 'shadow', eligible: false, ineligible_reason: 'reranker_off', candidates: expect.any(Number), would_skip: false, provider_called: false });+ });++ test('the config key turns shadow on without a per-call override', async () => {+ await engine.setConfig('search.reranker.gate', 'shadow');+ try {+ let meta: HybridSearchMeta | undefined;+ await hybridSearch(engine, 'orbital period of the gold probe', {+ limit: 10, queryEmbedFn: () => basisEmbedding(12, DIM), onMeta: (m) => { meta = m; },+ reranker: { enabled: true, topNIn: 30, topNOut: null, rerankerFn: async (i: RerankInput) => i.documents.map((_, index) => ({ index, relevanceScore: 1 })) },+ });+ expect(meta!.rerank_gate?.reason).toBe('high_vector_match');+ meta = undefined;+ await hybridSearch(engine, 'orbital period of the gold probe', {+ limit: 10, rerankGate: 'off', queryEmbedFn: () => basisEmbedding(12, DIM), onMeta: (m) => { meta = m; },+ reranker: { enabled: true, topNIn: 30, topNOut: null, rerankerFn: async (i: RerankInput) => i.documents.map((_, index) => ({ index, relevanceScore: 1 })) },+ });+ expect(meta!.rerank_gate).toBeUndefined();+ } finally {+ await engine.unsetConfig?.('search.reranker.gate');+ await engine.setConfig('search.reranker.gate', 'off');+ }+ });+ });+}diff --git a/test/search/rerank-gate-knobs.test.ts b/test/search/rerank-gate-knobs.test.tsnew file mode 100644index 0000000000..e121dea72c--- /dev/null+++ b/test/search/rerank-gate-knobs.test.ts@@ -0,0 +1,74 @@+/**+ * W3 — `search.reranker.gate` and `search.reranker.gate_min_gap` as search+ * knobs, plus the `--explain` line.+ *+ * Protects: the per-call → config → bundle ladder for the gate, the config+ * parse of both keys, every bundle defaulting to `off`, the cache key+ * changing with the gate, δ and the evidence cosine floor (so a row written+ * under one gate setting can never serve another), and the explain summary+ * staying absent when the gate is off.+ * Fails when: a knob is dropped from resolveSearchMode or knobsHash, a bad+ * config value leaks through instead of falling back, or explain output+ * changes for gate-off searches.+ * Seams: none (pure).+ */+import { describe, expect, test } from 'bun:test';+import {+ KNOB_CONFIG_KEY,+ MODE_BUNDLES,+ knobsHash,+ loadOverridesFromConfig,+ resolveSearchMode,+} from '../../src/core/search/mode.ts';+import { formatRerankGateSummary, formatResultsExplain } from '../../src/core/search/explain-formatter.ts';+import type { SearchResult } from '../../src/core/types.ts';++describe('rerank gate knobs', () => {+ test('every bundle ships the gate off with δ 0.05', () => {+ for (const bundle of Object.values(MODE_BUNDLES)) {+ expect(bundle.reranker_gate).toBe('off');+ expect(bundle.reranker_gate_min_gap).toBe(0.05);+ }+ expect(KNOB_CONFIG_KEY.reranker_gate).toBe('search.reranker.gate');+ expect(KNOB_CONFIG_KEY.reranker_gate_min_gap).toBe('search.reranker.gate_min_gap');+ });++ 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': '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();+ });++ test('per-call beats config beats bundle', () => {+ expect(resolveSearchMode({ mode: 'balanced' }).reranker_gate).toBe('off');+ expect(resolveSearchMode({ mode: 'balanced', overrides: { reranker_gate: 'shadow' } }).reranker_gate).toBe('shadow');+ expect(resolveSearchMode({ mode: 'balanced', overrides: { reranker_gate: 'shadow' }, perCall: { reranker_gate: 'off' } }).reranker_gate).toBe('off');+ expect(resolveSearchMode({ mode: 'tokenmax', overrides: { reranker_gate_min_gap: 0 } }).reranker_gate_min_gap).toBe(0);+ });++ 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 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, 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);+ });+});++describe('rerank gate --explain line', () => {+ const rows = [{ slug: 'notes/a', score: 1, chunk_text: 'a', title: 'a' } as SearchResult];+ test('absent when the gate is off', () => {+ expect(formatRerankGateSummary(undefined)).toBeNull();+ expect(formatResultsExplain(rows, { vector_enabled: true, detail_resolved: null, expansion_applied: false })).not.toContain('rerank gate');+ });+ test('names the grade, the verdict and the signal', () => {+ expect(formatRerankGateSummary({ mode: 'shadow', eligible: true, grade: 'strong', reason: 'high_vector_match', top_cosine: 0.91, gap: 0.12, candidates: 9, would_skip: true, provider_called: true }))+ .toBe('rerank gate (shadow): strong high_vector_match — would skip (cosine 0.91, gap 0.12, 9 candidates)');+ expect(formatRerankGateSummary({ mode: 'shadow', eligible: true, grade: 'strong', reason: 'alias_hit', candidates: 3, would_skip: false, skip_blocked: 'shadow_only_reason', provider_called: true }))+ .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)');+ });+});diff --git a/test/search/rerank-gate-telemetry.test.ts b/test/search/rerank-gate-telemetry.test.tsnew file mode 100644index 0000000000..9cb2e127a6--- /dev/null+++ b/test/search/rerank-gate-telemetry.test.ts@@ -0,0 +1,96 @@+/**+ * W3 — rerank gate counters in search_telemetry (reserved rows) and the+ * `rerank_gate` section of `search stats` / `search_stats`.+ *+ * Protects: the gate's eligible, graded, would-skip, provider-call and+ * per-reason counts survive a flush and accumulate across writer processes+ * (two writers flushing the same day add up), ineligible searches are counted+ * by why and not as graded, cache hits add nothing, and the reserved rows+ * never inflate total_calls or the mode/intent distributions.+ * Fails when: the writer drops the counters, the reader folds reserved rows+ * into the search totals, or would_skip_rate is computed over the wrong base.+ * Seams: `_resetTelemetryWriterForTest` stands in for a second process;+ * PGLite always, Postgres when DATABASE_URL is set.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../../src/core/engine.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import {+ _resetTelemetryWriterForTest,+ getTelemetryWriter,+ readSearchStats,+ recordSearchTelemetry,+} from '../../src/core/search/telemetry.ts';+import type { HybridSearchMeta } from '../../src/core/types.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { testBackends } from '../helpers/test-backends.ts';++type Gate = NonNullable<HybridSearchMeta['rerank_gate']>;+const meta = (rerank_gate?: Gate, extra: Partial<HybridSearchMeta> = {}): HybridSearchMeta => ({+ vector_enabled: true, detail_resolved: null, expansion_applied: false, intent: 'general', mode: 'balanced',+ ...(rerank_gate ? { rerank_gate } : {}), ...extra,+});+const strongVector: Gate = { mode: 'shadow', eligible: true, grade: 'strong', reason: 'high_vector_match', top_cosine: 0.93, gap: 0.2, candidates: 12, would_skip: true, provider_called: true };+const gapMiss: Gate = { mode: 'shadow', eligible: true, grade: 'not_strong', reason: 'gap_below_min', top_cosine: 0.9, gap: 0.01, candidates: 12, would_skip: false, provider_called: true };+const 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 };++async function flushFrom(engine: BrainEngine, metas: HybridSearchMeta[]): Promise<void> {+ _resetTelemetryWriterForTest();+ for (const m of metas) recordSearchTelemetry(engine, m, { results_count: 3 });+ await getTelemetryWriter().flush();+}++for (const backend of testBackends()) {+ describe(`${backend}: rerank gate telemetry`, () => {+ let engine: BrainEngine;+ let close: () => Promise<void> = async () => {};+ beforeAll(async () => {+ 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;+ }+ }, 120_000);+ afterAll(async () => { _resetTelemetryWriterForTest(); await close(); });+ beforeEach(async () => { _resetTelemetryWriterForTest(); await engine.executeRaw('DELETE FROM search_telemetry'); });++ test('two writers accumulate gate counters; search totals count searches only', async () => {+ await flushFrom(engine, [meta(strongVector), meta(gapMiss), meta(titleOnly), meta()]);+ await flushFrom(engine, [meta(strongVector), meta(noKey), meta(off)]);+ const stats = await readSearchStats(engine, { days: 1 });+ expect(stats.total_calls).toBe(7);+ expect(stats.mode_distribution).toEqual({ balanced: 7 });+ expect(stats.intent_distribution).toEqual({ general: 7 });+ expect(stats.rerank_gate).toEqual({+ eligible: 5,+ graded: 5,+ would_skip: 3,+ would_skip_rate: 3 / 5,+ provider_calls: 4,+ by_reason: { high_vector_match: 3, gap_below_min: 1, exact_lookup: 1 },+ ineligible: { reranker_off: 1 },+ });+ });++ test('cache hits replay a stored decision and add no gate counts', async () => {+ await flushFrom(engine, [meta(strongVector, { cache: { status: 'hit', similarity: 0.99 } })]);+ const stats = await readSearchStats(engine, { days: 1 });+ expect(stats.total_calls).toBe(1);+ expect(stats.rerank_gate.graded).toBe(0);+ });++ 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, provider_calls: 0, by_reason: {}, ineligible: {} });+ });+ });+}