Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
search: search.diverse_pool_depth session-diverse pool before the reranker (off by default)
garrytaned764bdc07e8
diff --git a/docs/architecture/RETRIEVAL.md b/docs/architecture/RETRIEVAL.mdindex a255d1fc45..1359879e06 100644--- a/docs/architecture/RETRIEVAL.md+++ b/docs/architecture/RETRIEVAL.md@@ -220,10 +220,13 @@ hybrid recall + fusion:graph augment (optional two-pass structural expansion — walkDepth > 0)│▼-deduplication (4-layer: per-page cap, same-page Jaccard, type diversity)+deduplication (4-layer: per-page cap, same-page Jaccard, type diversity;+ with search.diverse_pool_depth N > 0, one row per session — off by default,+ src/core/search/diverse-pool.ts)│▼-reranker (cross-encoder — balanced/tokenmax; fail-open)+reranker (cross-encoder — balanced/tokenmax; fail-open; reads+ reranker.top_n_in rows, at least N with search.diverse_pool_depth)│▼feedback (use-attributed page weights × the ordering score, bounded ±λ;diff --git a/docs/architecture/key-files/core-search-1.md b/docs/architecture/key-files/core-search-1.mdindex a15332a8ed..2d1e2b1064 100644--- a/docs/architecture/key-files/core-search-1.md+++ b/docs/architecture/key-files/core-search-1.md@@ -19,6 +19,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/date-labels.ts` — row-date honesty for `search` / `query`. `effectiveDateLabel(source)` maps `effective_date_source` to a document date (`date`, `published`, `filename`), an event date (`event_date`) or a fallback (`created`, `fallback`: when the page was created or imported); `dateLabelLine(rows)` is the one model-visible `[gbrain dates]` line `src/mcp/dispatch.ts` appends when rows carry dates, naming only the sources present and saying the date is never a contract's effective or validity date. Lean rows (`lean-rows.ts`) keep `effective_date_source` for it. Test: `test/search-date-labels.test.ts`.- `src/core/search/dedup.ts` — 4-layer result dedup + compiled-truth guarantee: (1) top 3 chunks per page by score, (2) drop chunks >0.85 Jaccard-similar to already-kept chunks of the SAME page (cross-page near-dups survive — two legitimately similar pages both return), (3) no page type exceeds 60% of results — applied only when the candidate set actually contains multiple page types; a homogeneous set passes through unchanged because dropping (for example) one of three distinct LongMemEval `note` sessions cannot introduce diversity and destroys multi-session recall (pinned by the homogeneous-set case in `test/dedup.test.ts`), (4) max 2 chunks per page (default; the two-pass structural expansion in `hybrid.ts` widens it), (5) ensure at least 1 compiled_truth chunk per page — the page's best compiled_truth chunk is APPENDED (never swapped over a kept chunk, so matching evidence survives) and the final output is re-sorted by score, because slice / token budget / evidence consumers assume score order. Page identity is the composite `pageKey()` (source_id, slug) — the one canonical key helper every layer uses, so slug collisions across sources can't collapse recall.+- `src/core/search/diverse-pool.ts` — the session-diverse candidate pool before the reranker, `search.diverse_pool_depth` (integer 0..100, `off` = 0; 0 in every bundle, so off by default). With N > 0: every retrieval arm fetches at least N candidates (`hybrid/request.ts` passes `max(PRE_FUSION_POOL_FLOOR, N)` as the `perArmPoolLimit` floor; still capped at `MAX_SEARCH_LIMIT` unless an eval pool depth is set), `capPerSession` keeps the first row of each session in the deduped pool (`hybrid/rank.ts` `capSessionPool`, called on `dedupResults`' output; a session is `sessionPrefix(slug)` from `graph-signals.ts`, else the page, keyed with the source id) and `rerankAndPin` raises the reranker's `topNIn` to at least N. The keyword-only paths have no reranker and are unchanged. `normalizeDiversePoolDepth` is the one range contract (mode.ts config parse and the `gbrain config set` refusal through `search/config-values.ts`); the mode field folds into `knobsHash` as an append-only `dpd=` part only when on. Motivation and measurement: BEAM-1M S1 in gbrain-evals (`docs/benchmarks/2026-10-12-beam-1m-s1-fixes.md`). Tests: `test/search/diverse-pool.test.ts`, `test/search/diverse-pool-hybrid.serial.test.ts`.- `src/core/search/embedding-column.ts` — single source of truth for "which `content_chunks.*` column does this query rank against?" Pure functions, no engine I/O: `loadRegistry(cfg)` walks the `embedding_columns` config (DB plane, JSON map keyed by column name with `{provider, dimensions, type}` entries), seeds the OpenAI `embedding` builtin when unset, validates everything before it lands (column-name regex, type ∈ `vector | halfvec`, dims in [1, 8192], provider format) using `Object.create(null)` + `Object.hasOwn` so a key like `constructor` rejects instead of resolving to `Object.prototype.constructor`. `resolveColumn(registry, override?, cfg)` is the boundary call: returns a frozen `ResolvedColumn` descriptor (`{name, provider, dimensions, type}`) honoring per-call override → `search_embedding_column` config → `'embedding'` default; throws `UnknownEmbeddingColumnError` with the list of registered names on miss. `isCacheSafe(resolved, cfg)` compares the full embedding SPACE (provider + dimensions + name) against cfg's default so a repointed `embedding` builtin doesn't serve OpenAI-shaped cache rows. `validateResolvedColumn(descriptor)` re-validates hand-rolled descriptors that bypass the registry (internal-SDK passthrough) so the SQL-injection escape hatch through the descriptor field is closed. Consumed by `hybridSearch`, `gateway.embedQuery(text, {embeddingModel, dimensions})`, `cosineReScore`, and the `query` MCP op (per-call `embedding_column` param). Engine column routing is covered by `test/e2e/embedding-column-pglite.test.ts`, `test/e2e/embedding-column-postgres.test.ts` and `test/cosine-rescore-column.test.ts`. Write side: `resolveWriteColumnFromConfigRows({searchEmbeddingColumn, embeddingColumnsJson})` resolves upsertChunks's active write target from the raw DB-plane config rows through the same registry/validation chain (legacy `embedding` descriptor when neither row routes elsewhere; `embedding_image` falls back to the legacy text column since image vectors travel in their own INSERT column; malformed registry JSON is forgiven like loadConfigWithEngine; unregistered names throw the paste-ready error), and `vectorCastSuffix(resolved)` is the placeholder-free `'::vector' | '::halfvec(N)'` cast shared by the read fragment builder and the write path so the two casts can't drift. Pinned by `test/e2e/upsert-chunks-registry-column.test.ts`.diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 2e6873a30a..80cb0b9a1e 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -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 1932 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + import; +2 fix wave 11 integration: W1 router help guard import beside the W2 managed-root import; +2 fix wave 13 P4.9 #6399: a header-only Codex rollout ends empty_session, not parser_drift; +3 W14 P4.16 (#5799): banner and SessionStart note read livePushStatuses (predicate in core/workspace-push.ts); +1 W15 P5.7 (#4992): gitChildEnv import for the hook git probes (launches moved onto core/spawn.ts)src/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 1955 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); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +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); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts)+src/core/config.ts 1956 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); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +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); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +1 GBRA-60 S1: search.diverse_pool_depth in the known search keyssrc/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 1616 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); +22 GBRA-60 S1 diverse_pool_depth knob (interface doc, bundles, overrides, pick, config parse, append-only dpd= 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 1523 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); +11 fix wave 15 P2.8 (#5495): extract_health reads the 7-day halt reasons per kind (halt_reasons, top_halt_reason in details and the top reason in the warn line); the read, the unknown bucket and the ranking live in core/extract/rollup-writer.tssrc/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/core/config.ts b/src/core/config.tsindex 32ff08c483..9206f53ed0 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1392,6 +1392,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = ['search.relational_orient_onehop',// Multi-hop chain slots: chain rows leading page 1 when a chain fired (mode.ts reads; 0..10).'search.relational_chain_slots',+ 'search.diverse_pool_depth', // session-diverse pool before the reranker (mode.ts reads; `off` | 0..100; 0 = off)// Ranker wave (Phase E2): keyword-arm confidence floor — weak keyword arm fuses at half weight (mode.ts reads; `off` | (0, 1]).'search.keyword_arm_confidence_floor',// Ranker wave (Phase E3): metadata boost gate — `lexical` skips post-fusion metadata boosts when the vector arm was the only voter (mode.ts reads; `always` | `lexical`).diff --git a/src/core/search/config-values.ts b/src/core/search/config-values.tsindex 476b0c7e0e..d592d594af 100644--- a/src/core/search/config-values.ts+++ b/src/core/search/config-values.ts@@ -6,6 +6,7 @@import { HNSW_ITERATIVE_SCAN_KEY, HNSW_ITERATIVE_SCAN_MODES, hnswIterativeScanValueProblem } from './hnsw-iterative-scan.ts';import { CJK_KEYWORD_DEADLINE_DEFAULT_MS, CJK_KEYWORD_DEADLINE_KEY, cjkKeywordDeadlineValueProblem } from './cjk-keyword-deadline.ts';import { AUTO_PACKING_CONFIG_KEY, DEFAULT_AUTO_PACKING, autoPackingValueProblem } from './evidence-packing.ts';+import { DIVERSE_POOL_DEPTH_KEY, diversePoolDepthValueProblem } from './diverse-pool.ts';interface SearchValueRule {problem: (value: string) => string | null;@@ -17,6 +18,7 @@ export const SEARCH_VALUE_RULES: Readonly<Record<string, SearchValueRule>> = {[HNSW_ITERATIVE_SCAN_KEY]: { problem: hnswIterativeScanValueProblem, example: HNSW_ITERATIVE_SCAN_MODES[0] },[CJK_KEYWORD_DEADLINE_KEY]: { problem: cjkKeywordDeadlineValueProblem, example: String(CJK_KEYWORD_DEADLINE_DEFAULT_MS) },[AUTO_PACKING_CONFIG_KEY]: { problem: autoPackingValueProblem, example: DEFAULT_AUTO_PACKING },+ [DIVERSE_POOL_DEPTH_KEY]: { problem: diversePoolDepthValueProblem, example: '100' },};/** The refusal for an invalid value of a validated `search.*` key, or null. */diff --git a/src/core/search/diverse-pool.ts b/src/core/search/diverse-pool.tsnew file mode 100644index 0000000000..d3ff6e763b--- /dev/null+++ b/src/core/search/diverse-pool.ts@@ -0,0 +1,54 @@+/**+ * Session-diverse candidate pool before the reranker (`search.diverse_pool_depth`,+ * BEAM-1M wave 3 item S1; off in every bundle).+ *+ * On BEAM-1M dev, 30 of the 57 questions with no gold session in the top 5 were+ * semantic drift: other sessions outranked the gold, and the reranker reads only+ * `reranker_top_n_in` rows, where several chunks of one session can take the+ * slots the gold competes for. With depth N > 0, hybridSearch (1) fetches at+ * least N candidates per retrieval arm (hybrid/request.ts, still capped at+ * MAX_SEARCH_LIMIT unless an eval pool depth is set), (2) keeps one row per+ * session in the deduped pool (`capPerSession`, hybrid.ts) and (3) lets the+ * reranker read at least N rows (hybrid/rank.ts). The keyword-only paths have+ * no reranker and are unchanged.+ *+ * A session is the group `sessionPrefix` (graph-signals.ts) derives from a+ * session-shaped slug (`chat/<id>`, `.../session/<id>`, a dated segment);+ * every other page is its own session. Keys include the source id.+ */+import type { SearchResult } from '../types.ts';+import { MAX_SEARCH_LIMIT } from '../engine.ts';+import { sessionPrefix } from './graph-signals.ts';++export const DIVERSE_POOL_DEPTH_KEY = 'search.diverse_pool_depth';++/** Inclusive upper bound of `search.diverse_pool_depth`: the production per-arm cap. */+export const DIVERSE_POOL_DEPTH_MAX = MAX_SEARCH_LIMIT;++/**+ * The ONE range contract for `search.diverse_pool_depth`: an integer in+ * [0, DIVERSE_POOL_DEPTH_MAX] (or a string parsing to one); `off`/`false` is 0;+ * anything else is undefined (falls through to the bundle).+ */+export function normalizeDiversePoolDepth(v: unknown): number | undefined {+ if (v === 'off' || v === false) return 0;+ const n = typeof v === 'number' ? v : typeof v === 'string' && v.trim() !== '' ? Number(v) : NaN;+ return Number.isInteger(n) && n >= 0 && n <= DIVERSE_POOL_DEPTH_MAX ? n : undefined;+}++/** The `gbrain config set` refusal message for an out-of-contract value, or null (search/config-values.ts). */+export function diversePoolDepthValueProblem(value: string): string | null {+ return normalizeDiversePoolDepth(value) === undefined+ ? `${DIVERSE_POOL_DEPTH_KEY} must be an integer from 0 to ${DIVERSE_POOL_DEPTH_MAX} or off (got ${value})` : null;+}++/** Keeps the first row of each session in input order (callers pass a score-ordered pool). */+export function capPerSession(results: SearchResult[]): SearchResult[] {+ const seen = new Set<string>();+ return results.filter((r) => {+ const key = `${r.source_id ?? 'default'}:${sessionPrefix(r.slug) ?? r.slug}`;+ if (seen.has(key)) return false;+ seen.add(key);+ return true;+ });+}diff --git a/src/core/search/hybrid.ts b/src/core/search/hybrid.tsindex 53360ac1c3..369f891011 100644--- a/src/core/search/hybrid.ts+++ b/src/core/search/hybrid.ts@@ -49,7 +49,7 @@ import { prepareSemanticCache, resolveCacheSearchMode, semanticCacheSkipped, serimport { buildPostFusionOpts, buildRelationalList, resolveModalityAndQueries, runLexicalArms, runVectorArms } from './hybrid/arms.ts';import { searchVectorFallback, searchWithoutEmbeddings } from './hybrid/keyword-only.ts';import { factEmbeddingDisabled } from '../embedding-disabled.ts';-import { expandStructuralNeighbors, finalizeHybridResults, fuseArms, rerankAndPin, sizeReturnPool } from './hybrid/rank.ts';+import { capSessionPool, expandStructuralNeighbors, finalizeHybridResults, fuseArms, rerankAndPin, sizeReturnPool } from './hybrid/rank.ts';export const RRF_K = 60;const COMPILED_TRUTH_BOOST = 2.0;@@ -1157,7 +1157,7 @@ export async function hybridSearch(// aliasing in the postFusionOpts resolver near line ~256.// Dedup- const deduped = dedupResults(fused, dedupOpts);+ const deduped = capSessionPool(req, dedupResults(fused, dedupOpts));opts?.explainTarget?.observe('deduped', deduped);// Auto-escalate: if detail=low returned 0, retry with high. The innerdiff --git a/src/core/search/hybrid/rank.ts b/src/core/search/hybrid/rank.tsindex 4d7cd37111..fe25ae4476 100644--- a/src/core/search/hybrid/rank.ts+++ b/src/core/search/hybrid/rank.ts@@ -15,6 +15,7 @@ import { type PostFusionOpts, RRF_K, cosineReScore, resolveWalkDedupCap, rrfFusiimport { type RelationalEvidenceSlotDecision, ensureRelationalEvidenceSlot } from '../relational-recall.ts';import { type RelationalRerankPinDecision, pinRelationalRows } from '../relational-rerank-pin.ts';import { applyFeedbackStage } from '../feedback-boost.ts';+import { capPerSession } from '../diverse-pool.ts';import { type RerankFailedReason, type RerankPassThroughReason, type RerankSkipReason, applyReranker } from '../rerank.ts';import type { RerankMeta } from '../../ai/gateway.ts';import { applyEvidenceGate, recordRerankReceipts, startRerankShadow } from '../decide-stage.ts';@@ -244,6 +245,11 @@ export async function expandStructuralNeighbors(req: HybridRequest, fused: Searcreturn dedupOpts;}+/** Session-diverse pool (`search.diverse_pool_depth` > 0, diverse-pool.ts): one deduped row per session before the reranker. */+export function capSessionPool(req: HybridRequest, deduped: SearchResult[]): SearchResult[] {+ return req.resolvedMode.diverse_pool_depth > 0 ? capPerSession(deduped) : deduped;+}+/** Cross-encoder rerank (fail-open), then the relational-row pin. */export async function rerankAndPin(req: HybridRequest,@@ -260,13 +266,16 @@ export async function rerankAndPin(// from the resolved mode bundle (tokenmax → enabled, others → disabled).// The resolved mode's fields already participate in knobsHash, so cache// rows naturally segregate by reranker config.- const rerankerOpts = opts?.reranker ?? {+ const baseRerankerOpts = opts?.reranker ?? {enabled: resolvedMode.reranker_enabled,topNIn: resolvedMode.reranker_top_n_in,topNOut: resolvedMode.reranker_top_n_out,model: resolvedMode.reranker_model,timeoutMs: resolvedMode.reranker_timeout_ms,};+ // Session-diverse pool (diverse-pool.ts): the reranker reads at least N rows.+ const rerankerOpts = resolvedMode.diverse_pool_depth > baseRerankerOpts.topNIn+ ? { ...baseRerankerOpts, topNIn: resolvedMode.diverse_pool_depth } : baseRerankerOpts;// is stamped `reranker_skipped` (ranking-only — never shortens the cache TTL// or turns an empty result into a degraded miss), and a success-shapeddiff --git a/src/core/search/hybrid/request.ts b/src/core/search/hybrid/request.tsindex 7751ca1383..963295286d 100644--- a/src/core/search/hybrid/request.ts+++ b/src/core/search/hybrid/request.ts@@ -166,7 +166,7 @@ export async function resolveHybridRequest(const limit = opts?.limit || resolvedMode.searchLimit;const offset = opts?.offset || 0;- const innerLimit = perArmPoolLimit(limit, offset, PRE_FUSION_POOL_FLOOR);+ const innerLimit = perArmPoolLimit(limit, offset, Math.max(PRE_FUSION_POOL_FLOOR, resolvedMode.diverse_pool_depth));// v0.32.x search-lite: classify intent once up front. Drives BOTH the// legacy auto-detail / salience / recency suggestions AND the newdiff --git a/src/core/search/mode.ts b/src/core/search/mode.tsindex 3f326e6187..2c673c6ece 100644--- a/src/core/search/mode.ts+++ b/src/core/search/mode.ts@@ -37,6 +37,7 @@ import { DEFAULT_RERANKER_MODEL } from '../ai/defaults.ts';import { normalizeExpansionVariantBudget } from './fusion-lists.ts';import { DEFAULT_RELATIONAL_RERANK_PIN, normalizeRelationalRerankPin } from './relational-rerank-pin.ts';import { normalizeKeywordArmConfidenceFloor } from './arm-confidence.ts';+import { normalizeDiversePoolDepth } from './diverse-pool.ts';import {DEFAULT_METADATA_BOOST_GATE,normalizeMetadataBoostGate,@@ -379,6 +380,16 @@ export interface ModeBundle {* `search.relational_chain_slots` (0..10).*/relational_chain_slots: number;+ /**+ * Session-diverse candidate pool before the reranker (BEAM-1M S1). When N > 0:+ * every retrieval arm fetches at least N candidates (still capped at+ * MAX_SEARCH_LIMIT), the deduped pool keeps one row per session (pages+ * sharing a `sessionPrefix`, otherwise one page), and the reranker reads at+ * least N candidates, so one session's chunks cannot fill the window the+ * gold competes for. 0 = off (every bundle). Override:+ * `search.diverse_pool_depth` (0..100).+ */+ diverse_pool_depth: number;/*** Ranker wave (Phase E2, Cat 13) — arm-confidence-weighted fusion of the* LEXICAL arms (arm-confidence.ts). When the keyword arm's scale-free@@ -483,6 +494,7 @@ export const MODE_BUNDLES: Readonly<Record<SearchMode, Readonly<ModeBundle>>> =relational_planner: false,relational_orient_onehop: false,relational_chain_slots: 10,+ diverse_pool_depth: 0,autocut_jump: 0.2,autocut_min_top: 0.35,autocut_min_keep: 1,@@ -549,6 +561,7 @@ export const MODE_BUNDLES: Readonly<Record<SearchMode, Readonly<ModeBundle>>> =relational_planner: true,relational_orient_onehop: false,relational_chain_slots: 10,+ diverse_pool_depth: 0,autocut_jump: 0.2,autocut_min_top: 0.35,autocut_min_keep: 1,@@ -615,6 +628,7 @@ export const MODE_BUNDLES: Readonly<Record<SearchMode, Readonly<ModeBundle>>> =relational_planner: true,relational_orient_onehop: false,relational_chain_slots: 10,+ diverse_pool_depth: 0,autocut_jump: 0.2,autocut_min_top: 0.35,autocut_min_keep: 1,@@ -683,6 +697,7 @@ export interface SearchKeyOverrides {relational_planner?: boolean;relational_orient_onehop?: boolean | null;relational_chain_slots?: number;+ diverse_pool_depth?: number;// Ranker wave (Phase E2) — keyword-arm confidence floor override (null = off; (0, 1]).keyword_arm_confidence_floor?: number | null;// Ranker wave (Phase E3) — metadata boost gate override (`always` | `lexical`).@@ -750,6 +765,7 @@ export interface SearchPerCallOpts {relational_planner?: boolean;relational_orient_onehop?: boolean | null;relational_chain_slots?: number;+ diverse_pool_depth?: number;// Ranker wave (Phase E2) — keyword-arm confidence floor per-call override (null = off; (0, 1]).keyword_arm_confidence_floor?: number | null;// Ranker wave (Phase E3) — metadata boost gate per-call override (`always` | `lexical`).@@ -858,6 +874,7 @@ export function resolveSearchMode(input: ResolveSearchModeInput): ResolvedSearchrelational_planner: pick('relational_planner'),relational_orient_onehop: pick('relational_orient_onehop'),relational_chain_slots: pick('relational_chain_slots'),+ diverse_pool_depth: pick('diverse_pool_depth'),keyword_arm_confidence_floor: pick('keyword_arm_confidence_floor'),metadata_boost_gate: pick('metadata_boost_gate'),resolved_mode,@@ -1204,6 +1221,8 @@ export function knobsHash(...(knobs.relational_planner ? ['rp=1'] : []),...(knobs.relational_orient_onehop ?? knobs.relational_planner ? ['ro=1'] : []),...(knobs.relational_planner && knobs.relational_chain_slots ? [`rcs=${knobs.relational_chain_slots}`] : []),+ // Session-diverse pool (append-only, emitted only when on, so every off key is unchanged).+ ...(knobs.diverse_pool_depth ? [`dpd=${knobs.diverse_pool_depth}`] : []),];// #5691 (append-only, no version bump): only a non-empty query prefix adds// a part, so every row written without one keeps its key.@@ -1437,6 +1456,8 @@ export function loadOverridesFromConfig(if (roh !== undefined) out.relational_orient_onehop = roh;const rcs = normalizeChainSlots(get('search.relational_chain_slots'));if (rcs !== undefined) out.relational_chain_slots = rcs;+ const dpd = normalizeDiversePoolDepth(get('search.diverse_pool_depth'));+ if (dpd !== undefined) out.diverse_pool_depth = dpd;// Ranker wave (Phase E2) — keyword-arm confidence floor: the literal// `off`/`null` pins the knob off (null); a number in (0, 1] is the floor;// anything else falls through to the bundle. ONE range contract with the@@ -1508,6 +1529,7 @@ export const KNOB_CONFIG_KEY: Readonly<Record<keyof ModeBundle, string>> = Objecrelational_planner: 'search.relational_planner',relational_orient_onehop: 'search.relational_orient_onehop',relational_chain_slots: 'search.relational_chain_slots',+ diverse_pool_depth: 'search.diverse_pool_depth',keyword_arm_confidence_floor: 'search.keyword_arm_confidence_floor',metadata_boost_gate: 'search.metadata_boost_gate',});diff --git a/src/core/search/modes-report.ts b/src/core/search/modes-report.tsindex bb7ebbfa2e..e64a51e408 100644--- a/src/core/search/modes-report.ts+++ b/src/core/search/modes-report.ts@@ -63,6 +63,7 @@ export const KNOB_DESCRIPTIONS: Record<keyof ModeBundle, string> = {relational_planner: 'Multi-hop planner: questions chaining 2-3 typed relations walk typed hop chains with evidence (also keyless recall)',relational_orient_onehop: 'Typed one-hop walks read edges written on either page by the relation type signature (opt-in; null = follow relational_planner)',relational_chain_slots: 'When a multi-hop chain fired, up to this many chain rows (answers, then evidence pages) lead page 1 (0..10; 0 = single evidence slot)',+ diverse_pool_depth: 'Session-diverse pool before the reranker: each arm fetches at least N candidates, one row per session, the reranker reads at least N (0..100; 0 = off)',// Ranker wave (Phase E2) arm-confidence fusionkeyword_arm_confidence_floor: 'Keyword-arm confidence floor: below this margin ratio the keyword + title lists fuse at half weight (null = off; (0, 1])',// Ranker wave (Phase E3) metadata boost gatediff --git a/test/search-mode.test.ts b/test/search-mode.test.tsindex 63fed5035f..41b6be111f 100644--- a/test/search-mode.test.ts+++ b/test/search-mode.test.ts@@ -91,6 +91,7 @@ describe('SEARCH_MODES + MODE_BUNDLES canonical shape', () => {relational_planner: false,relational_orient_onehop: false,relational_chain_slots: 10,+ diverse_pool_depth: 0,// ranker wave (Phase E2) — keyword-arm confidence floor OFF in every bundle until the Cat 13 receipt.keyword_arm_confidence_floor: null,// ranker wave (Phase E3) — metadata boost gate `lexical` in every bundle since the Cat 13 held-out receipt (`always` = pre-wave pipeline).@@ -137,6 +138,7 @@ describe('SEARCH_MODES + MODE_BUNDLES canonical shape', () => {relational_planner: true,relational_orient_onehop: false,relational_chain_slots: 10,+ diverse_pool_depth: 0,// ranker wave (Phase E2) — keyword-arm confidence floor OFF in every bundle until the Cat 13 receipt.keyword_arm_confidence_floor: null,// ranker wave (Phase E3) — metadata boost gate `lexical` in every bundle since the Cat 13 held-out receipt (`always` = pre-wave pipeline).@@ -181,6 +183,7 @@ describe('SEARCH_MODES + MODE_BUNDLES canonical shape', () => {relational_planner: true,relational_orient_onehop: false,relational_chain_slots: 10,+ diverse_pool_depth: 0,// ranker wave (Phase E2) — keyword-arm confidence floor OFF in every bundle until the Cat 13 receipt.keyword_arm_confidence_floor: null,// ranker wave (Phase E3) — metadata boost gate `lexical` in every bundle since the Cat 13 held-out receipt (`always` = pre-wave pipeline).diff --git a/test/search/diverse-pool-hybrid.serial.test.ts b/test/search/diverse-pool-hybrid.serial.test.tsnew file mode 100644index 0000000000..265a43e3e0--- /dev/null+++ b/test/search/diverse-pool-hybrid.serial.test.ts@@ -0,0 +1,102 @@+/**+ * `search.diverse_pool_depth` through bare hybridSearch on PGLite (GBRA-60 S1):+ * with the knob set, the deduped pool holds one row per session, the reranker+ * reads at least N rows and every arm fetches at least N candidates; with it+ * off (every bundle) the pipeline is unchanged. Serial: it isolates+ * GBRAIN_HOME and stubs the process-wide gateway, as+ * hybrid-reranker-integration.serial.test.ts does.+ */+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { installFixtureChunks } from '../helpers/page-projection.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { hybridSearch } from '../../src/core/search/hybrid.ts';+import { resolveHybridRequest } from '../../src/core/search/hybrid/request.ts';+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../../src/core/ai/gateway.ts';+import type { RerankInput, RerankResult } from '../../src/core/ai/gateway.ts';+import type { SearchOpts } from '../../src/core/types.ts';++const DIMS = 1536;+const FAKE_EMB = Array.from({ length: DIMS }, (_, j) => (j === 0 ? 1 : 0.01));+const SESSION = 'media/chat/2026-05-20-standup';+let engine: PGLiteEngine;+let prevGbrainHome: string | undefined;+let isolatedHome: string;++function rerankOpts(topNIn: number, seen: { docs: number }): SearchOpts {+ return {+ limit: 10,+ reranker: {+ enabled: true, topNIn, topNOut: null,+ rerankerFn: async (input: RerankInput): Promise<RerankResult[]> => {+ seen.docs = input.documents.length;+ return input.documents.map((_, i) => ({ index: i, relevanceScore: 1 - i * 0.01 }));+ },+ },+ };+}++beforeAll(async () => {+ prevGbrainHome = process.env.GBRAIN_HOME;+ isolatedHome = mkdtempSync(join(tmpdir(), 'gbrain-diverse-pool-home-'));+ process.env.GBRAIN_HOME = isolatedHome;+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ const pages: Array<[string, string[]]> = [+ [`${SESSION}/part-1`, ['zephyr budget review opening remarks', 'zephyr budget review travel line items', 'zephyr budget review hiring plan numbers']],+ [`${SESSION}/part-2`, ['zephyr budget review closing decisions and owners']],+ ['notes/zephyr-gold', ['zephyr budget review final approved figure']],+ ['notes/zephyr-other', ['zephyr budget review vendor shortlist']],+ ];+ for (const [slug, chunks] of pages) {+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: chunks.join('\n\n') });+ await installFixtureChunks(engine, slug, chunks.map((chunk_text, chunk_index) => ({ chunk_index, chunk_text, chunk_source: 'compiled_truth' as const })));+ }+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: DIMS, env: { OPENAI_API_KEY: 'sk-test' } });+ __setEmbedTransportForTests(async (args: any) => ({ embeddings: args.values.map(() => FAKE_EMB) }) as any);+});++afterEach(async () => {+ await engine.setConfig('search.diverse_pool_depth', '0');+});++afterAll(async () => {+ __setEmbedTransportForTests(null);+ resetGateway();+ await engine.disconnect();+ if (prevGbrainHome === undefined) delete process.env.GBRAIN_HOME;+ else process.env.GBRAIN_HOME = prevGbrainHome;+ rmSync(isolatedHome, { recursive: true, force: true });+});++describe('search.diverse_pool_depth off (every bundle)', () => {+ test('a session keeps several rows and the reranker reads top_n_in rows', async () => {+ const seen = { docs: 0 };+ const out = await hybridSearch(engine, 'zephyr budget review', rerankOpts(2, seen));+ expect(seen.docs).toBe(2);+ expect(out.filter(r => r.slug.startsWith(`${SESSION}/`)).length).toBeGreaterThan(1);+ const req = await resolveHybridRequest(engine, 'zephyr budget review', { limit: 10 });+ expect(req.searchOpts.limit).toBe(50);+ });+});++describe('search.diverse_pool_depth on', () => {+ test('one row per session reaches the reranker, which reads at least N rows', async () => {+ await engine.setConfig('search.diverse_pool_depth', '10');+ const seen = { docs: 0 };+ const out = await hybridSearch(engine, 'zephyr budget review', rerankOpts(2, seen));+ expect(out.filter(r => r.slug.startsWith(`${SESSION}/`))).toHaveLength(1);+ expect(out.filter(r => !r.slug.startsWith(`${SESSION}/`)).map(r => r.slug).sort()).toEqual(['notes/zephyr-gold', 'notes/zephyr-other']);+ expect(seen.docs).toBe(3);+ });++ test('every arm fetches at least N candidates, still capped at MAX_SEARCH_LIMIT', async () => {+ await engine.setConfig('search.diverse_pool_depth', '80');+ expect((await resolveHybridRequest(engine, 'zephyr budget review', { limit: 10 })).searchOpts.limit).toBe(80);+ await engine.setConfig('search.diverse_pool_depth', '100');+ expect((await resolveHybridRequest(engine, 'zephyr budget review', { limit: 60 })).searchOpts.limit).toBe(100);+ });+});diff --git a/test/search/diverse-pool.test.ts b/test/search/diverse-pool.test.tsnew file mode 100644index 0000000000..6198b6253f--- /dev/null+++ b/test/search/diverse-pool.test.ts@@ -0,0 +1,76 @@+/**+ * `search.diverse_pool_depth` (GBRA-60 S1): range contract, config parse,+ * set-time refusal, bundle defaults, cache-key segregation and the+ * one-row-per-session cap. The hybridSearch wiring is pinned by+ * diverse-pool-hybrid.serial.test.ts.+ */+import { describe, expect, test } from 'bun:test';+import { DIVERSE_POOL_DEPTH_MAX, capPerSession, normalizeDiversePoolDepth } from '../../src/core/search/diverse-pool.ts';+import { MODE_BUNDLES, knobsHash, loadOverridesFromConfig, resolveSearchMode } from '../../src/core/search/mode.ts';+import { searchConfigValueRefusal } from '../../src/core/search/config-values.ts';+import type { SearchResult } from '../../src/core/types.ts';++const row = (slug: string, score: number, source_id = 'default', chunk_id = Math.round(score * 1000)): SearchResult =>+ ({ slug, score, source_id, chunk_id, page_id: 1, title: slug, type: 'note', chunk_text: slug, chunk_source: 'compiled_truth', stale: false } as SearchResult);++describe('normalizeDiversePoolDepth', () => {+ test('integers 0..100 and off; everything else falls through', () => {+ expect(normalizeDiversePoolDepth('0')).toBe(0);+ expect(normalizeDiversePoolDepth('100')).toBe(100);+ expect(normalizeDiversePoolDepth(40)).toBe(40);+ expect(normalizeDiversePoolDepth('off')).toBe(0);+ expect(normalizeDiversePoolDepth(false)).toBe(0);+ expect(DIVERSE_POOL_DEPTH_MAX).toBe(100);+ for (const bad of ['101', '-1', '2.5', '', 'many', null, undefined, true]) expect(normalizeDiversePoolDepth(bad)).toBeUndefined();+ });++ test('gbrain config set refuses an out-of-contract value and names a valid one', () => {+ expect(searchConfigValueRefusal('search.diverse_pool_depth', '100')).toBeNull();+ expect(searchConfigValueRefusal('search.diverse_pool_depth', 'off')).toBeNull();+ const refusal = searchConfigValueRefusal('search.diverse_pool_depth', '500');+ expect(refusal?.message).toContain('integer from 0 to 100');+ expect(refusal?.example).toBe('100');+ });+});++describe('diverse_pool_depth mode knob', () => {+ test('off in every bundle', () => {+ for (const m of ['conservative', 'balanced', 'tokenmax'] as const) expect(MODE_BUNDLES[m].diverse_pool_depth).toBe(0);+ });++ test('config parses into the override; garbage falls through to the bundle', () => {+ expect(loadOverridesFromConfig({ 'search.diverse_pool_depth': '100' }).diverse_pool_depth).toBe(100);+ expect(loadOverridesFromConfig({ 'search.diverse_pool_depth': 'off' }).diverse_pool_depth).toBe(0);+ expect(loadOverridesFromConfig({ 'search.diverse_pool_depth': '101' }).diverse_pool_depth).toBeUndefined();+ expect(resolveSearchMode({ mode: 'balanced', overrides: { diverse_pool_depth: 60 } }).diverse_pool_depth).toBe(60);+ });++ test('knobsHash: off keeps every existing key; a depth segregates the cache', () => {+ const dflt = knobsHash(resolveSearchMode({ mode: 'balanced' }));+ const explicitOff = knobsHash(resolveSearchMode({ mode: 'balanced', overrides: { diverse_pool_depth: 0 } }));+ const on = knobsHash(resolveSearchMode({ mode: 'balanced', overrides: { diverse_pool_depth: 100 } }));+ const on60 = knobsHash(resolveSearchMode({ mode: 'balanced', overrides: { diverse_pool_depth: 60 } }));+ expect(explicitOff).toBe(dflt);+ expect(new Set([dflt, on, on60]).size).toBe(3);+ });+});++describe('capPerSession', () => {+ test('keeps the first row per page when slugs are not session-shaped', () => {+ const out = capPerSession([row('notes/a', 0.9, 'default', 1), row('notes/a', 0.8, 'default', 2), row('notes/b', 0.7), row('notes/a', 0.6, 'default', 3)]);+ expect(out.map(r => [r.slug, r.chunk_id])).toEqual([['notes/a', 1], ['notes/b', 700]]);+ });++ test('pages of one recorded session share one slot; other sessions and sources keep theirs', () => {+ const out = capPerSession([+ row('media/chat/2026-05-20-standup/part-1', 0.9),+ row('media/chat/2026-05-20-standup/part-2', 0.85),+ row('chat/1m-3-s7', 0.8),+ row('chat/1m-3-s8', 0.75),+ row('media/chat/2026-05-20-standup/part-1', 0.7, 'work'),+ ]);+ expect(out.map(r => `${r.source_id}:${r.slug}`)).toEqual([+ 'default:media/chat/2026-05-20-standup/part-1', 'default:chat/1m-3-s7', 'default:chat/1m-3-s8', 'work:media/chat/2026-05-20-standup/part-1',+ ]);+ });+});