Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
57.4 KB
Raw Blame

Key files: Core Search (1/2)

Subsystem index. Read only the entries relevant to your change. Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.

  • 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 = 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), the opt-in qualified hop (qualifiedAliasCandidates, applyQualifiedAliasHop) 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/qualified-alias-visibility.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).

  • src/core/search/autocut.ts (OFF in every bundle since rule R2; search.autocut true re-enables it where the reranker runs) — Weaviate-style autocut: score-discontinuity result-sizing on the cross-encoder rerank separatrix. applyAutocut(results, scoreOf, cfg) normalizes the reranker scores, finds the largest consecutive gap, and cuts there when it clears jumpRatio (default 0.20); robust to unsorted provider output (cuts on a sorted copy, keeps items in INPUT order via a score threshold), guards top<=0/non-finite, never returns empty, and no-ops when <2 results carry a finite rerank_score (covers the reranker fail-open path). WHY rerank_score and NOT RRF/cosine: gbrain measured (see return-policy.ts) that the RRF rank1→rank2 gap is ~flat whether rank-1 is right or wrong — not a separatrix; the cross-encoder score IS. So autocut, when enabled, runs ONLY where the reranker ran (balanced+tokenmax; conservative is a documented no-op). Weak-top floor: when the top rerank score is below minTopScore (default 0.35; config search.autocut_min_top; scale-calibrated to the default reranker; a default-reranker change must re-tune it), cliff trimming is skipped entirely so a low-confidence list returns the full cluster instead of collapsing to one result. Exports AutocutConfig, DEFAULT_AUTOCUT (frozen: enabled=true, jumpRatio=0.20, minKeep=1, minTopScore=0.35), AutocutDecision ({applied, signal:'rerank'|'none', cut, kept, total, gapRatio}), AutocutInput, autocutFromConfig, resolveAutocut, applyAutocut. Cache-key integration (clean path, not the adaptive-return cache-skip hack): enable+sensitivity flow through ModeBundle → ResolvedSearchKnobs → knobsHash exactly like graph_signals. mode.ts adds autocut/autocut_jump/autocut_min_keep (autocut false in every bundle since rule R2 — the LongMemEval replay from the captured post-rerank pool found no floor that beat autocut off; jump 0.20 stays the sensitivity when re-enabled; floor 1 in every mode — search.autocut_min_keep sets the minimum result count a cut may leave, resolved through the same bundle → config → per-call chain) AND sets reranker_top_n_in = searchLimit for reranked modes (so the reranker scores the full returned set; there is no un-scored tail for autocut to wrongly drop). Autocut folds into knobsHash as its own parts entry (mode.ts:KNOBS_HASH_VERSION is the single source of truth for the current hash version; every bump is a one-time global cache cold-miss on upgrade). Wired into hybridSearch AFTER adaptive-return, BEFORE the limit slice, first page only; emits HybridSearchMeta.autocut. BOTH the cache-miss finalMeta and cache-HIT cachedMeta rebuilds carry autocut+adaptive_return+mode+embedding_column. Preserves alias-hop exact matches: applyAutocut takes an optional preserve predicate; hybrid passes r => r.alias_hit === true || r.exact_lookup !== undefined || r.relational_pinned === true so a canonical page injected by applyAliasHop after reranking (no rerank_score), an exact-lookup tier hit, or a relational row re-pinned by pinRelationalRows (low cross-encoder score by construction; ALSO excluded from the cliff computation through scoreOf, so text-row autocut is unchanged by the pin) is never cut. Agent surface: query op autocut boolean (ceiling override — false forces full top-K); SearchOpts.autocut; --explain shows per-result rerank_score, formatAutocutSummary renders the decision when search meta is threaded; gbrain search modes attribution; metric glossary autocut.signal/autocut.gap_ratio. Config: search.autocut, search.autocut_jump, search.autocut_min_keep. The DEFAULT_AUTOCUT module constant is unchanged (enabled=true) for operators who re-enable it; the cliff logic is backed by an in-repo eval gate — test/search/autocut-eval.test.ts (also bun run eval:autocut) measures precision-lift-without-recall-regression over labeled qrels fixtures with modeled cross-encoder distributions (no API key, no sibling repo; runs in CI): mean precision 0.33→0.94, recall 1.00→0.95, ZERO recall loss on enumeration queries. Env-overridable floors. Pinned by test/search/autocut.test.ts (pure-fn), test/search/query-op-autocut.test.ts (agent surface), test/search/autocut-integration.serial.test.ts (IRON-RULE behavioral via rerankerFn DI seam: cliff trims, flat doesn't, no-reranker no-ops, autocut:false ceiling, composes with adaptive-return), test/search/autocut-eval.test.ts (the precision/recall gate), and the knobsHash assertions in test/search-mode.test.ts.

  • src/core/search/by-image.ts — searchByImage(engine, input, opts). Always runs the image branch (embedQueryMultimodalImage + searchVector(embedding_image)). Hybrid intersect: when the caller provides an optional query, runs a parallel text branch via embedQueryMultimodal(query) and merges via rrfFusionWeighted with effectiveRrfK(baseRrfK, weight) from the resolved mode's refinement weights. Widens to the unified column when search.unified_multimodal=true (transparently upgrades retrieval quality post-reindex).

  • src/core/search/date-bounds.ts — shared public since/until normalization for text and image query paths; hybrid.ts preserves both existing exports. Exact timestamps keep their precision, a date-only public since starts at that day's UTC midnight, date-only upper bounds use exclusive next midnight, and invalid calendar dates fail before embedding. Direct legacy afterDate/beforeDate comparisons remain strict by default.

  • src/core/search/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 both survive), (3) no page type exceeds 60% of results — only when the candidates span several page types; a homogeneous set passes unchanged, since dropping one of three distinct LongMemEval note sessions only loses multi-session recall (pinned in test/dedup.test.ts), (4) max 2 chunks per page (default; hybrid.ts's two-pass structural expansion widens it; with regions (segmentRegions: one query, only when a page has over 2 results; passed by hybrid.ts and both keyword-only paths) a segmented page applies (1) and (4) per occurrence cluster (gaps over 1 MiB split) and keeps at most MAX_PER_SEGMENTED_PAGE 6), (5) at least 1 compiled_truth chunk per page — the best one is APPENDED (never swapped over a kept chunk, so matching evidence survives) and the output re-sorted by score, which slice / token budget / evidence consumers assume. Every layer keys pages by pageKey() (source_id, slug), 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): at depth 100 on BEAM-1M dev (voyage-4, balanced reranker) strict recall at 10 rose 76 → 83 of 198 (+3.5 points, 95% interval [0, +6.6]) and at 5 was flat (55 → 56), with search p50 latency 340 → 455 ms and about 4x the rerank tokens per query; the preregistered flip rule needed an interval above zero, so every bundle keeps 0. 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.

  • src/core/search/eval.ts — Retrieval eval harness: P@k, R@k, MRR, nDCG@k metrics + runEval() orchestrator. The vector strategy runs the production query path: embedQuery (query-side input_type on asymmetric providers) in the resolved embedding column's model, searched on that column — embed() is the document side and would handicap the vector baseline.

  • src/core/search/evidence.ts — the agent-facing why-it-matched contract (so one blended score never reads as "safe to create"). classifyEvidence(r, opts?) names the strongest signal (precedence: alias_hit > exact_title_match > high_vector_match (real query↔chunk cosine SearchResult.cosine ≥ DEFAULT_HIGH_COSINE_FLOOR=0.8, overridable via EvidenceOpts.cosineFloor / config search.evidence_cosine_floor; never the blended score, so a keyword+boost pile-up can't earn it; legacy HIGH_MATCH_FLOOR=0.85 is exported for back-compat only) > keyword_exact (base ≥ SOLID_MATCH_FLOOR=0.6; GBRA-449: any strict row under EvidenceOpts.keywordMode, which only search match: "keyword" sets, except a matched_alias row) > weak_semantic). createSafetyFor(evidence) derives the don't-duplicate hint (exists/probable/unknown) agents key off instead of a raw threshold. stampEvidence(results, opts?) stamps evidence + create_safety in place once at pipeline end (after the alias hop, before slice); idempotent; create_safety ignores keywordMode, so a relabelled row keeps unknown. keyword_relaxed rows never earn keyword_exact; CRAG grades a relaxed top weak (A4-2).

  • src/core/search/expansion.ts — Multi-query expansion via Haiku. Exports sanitizeQueryForPrompt + sanitizeExpansionOutput (prompt-injection defense-in-depth). Sanitized query is only used for the LLM channel; the original query still drives search. expandQuery returns the original first plus 2-3 variants; hybridSearch re-enforces queries[0] = the caller's query and dedupes repeats, then fuses each variant's vector list as a role variant arm through src/core/search/fusion-lists.ts (see that entry), where the variant arms share search.expansion_variant_budget as total RRF weight — null (every bundle's default) is legacy equal weight, the configuration under which the LongMemEval receipt shows expansion halving strict recall_all@5 (93.19% plain hybrid vs 54.89% with expansion, paired +3 / -183; docs/architecture/RETRIEVAL.md "Multi-query expansion"). The harness records expansion_variants per row and --expansion-replay serves them back so a budget sweep changes only the budget.

  • src/core/search/explain-formatter.ts — renders SearchResult[] as a multi-line per-result breakdown for gbrain search --explain. Reads every boost-stamping field (title_mention_boost renders as title-mention); also prints the raw query↔chunk cosine (SearchResult.cosine, the calibrated signal evidence keys off) next to the blended score when present — absent on keyword-only / no-embedding paths. Handles the "no boosts applied" empty path. 4-decimal precision with trailing-zero strip. formatResultsExplain(results, meta?) prepends header lines from the captured retrieval meta when present — formatAutocutSummary (the autocut decision) and formatDegradedSummary(meta.degraded), which renders the closed degraded[] vocabulary as degraded: reranker_skipped (no_key) (null when the run was clean); cli.ts:formatResult threads lastRetrievalMeta into it, so a silently skipped reranker is visible from the CLI. Pinned by test/search/explain-formatter.test.ts + test/cli-explain-degraded-render.test.ts. formatDecideSummary prints one decide <slot>: line per slot that ran (all-off: none), including the slot's answer summary (S2 label, S4 probability and verdict). formatTimingsSummary (stage-timings.ts) adds the timings: line.

  • src/core/search/fusion-lists.ts — the ONE composition point for hybridSearch's RRF inputs. Every vector recall list is a ROLE-tagged arm (VectorArm {list, role: 'original'|'variant'|'clause'|'image'}, appended only via pushVectorList) — never a parallel index-aligned array, since the allSettled salvage path drops failed arms and the both-mode image branch fails open, so positional rules mis-tag lists. composeFusionLists({arms, keywordFusionList, titleFusionList, relationalList, includeRelational, ks, knobs}) returns the complete weighted list set (FusionListEntry {list, k, weight?}) in the fixed order vector arms → keyword (keywordK) → title (keywordK, only if non-empty) → relational (baseRrfK, only if non-empty and not image modality): text arms fuse at textRrfK and the image arm at imageRrfK only when BOTH kinds are present, otherwise every arm at vectorK (text, image-only, unified, and a both-mode whose image branch fell open). variant/clause arms share expansionVariantBudget as total RRF weight — weight_i = b / n_voting_arms over the NON-EMPTY expansion arms (an empty list casts no vote), the original arm always weight 1; a null budget emits no weight key, byte-identical to unweighted fusion; when the original is missing every surviving text arm is a variant sharing the budget. rrfFusionWeighted (hybrid.ts) scores weight / (k + rank) (weighted RRF: a list-level multiplier at every rank). textArmsNonEmpty is the role-based text-arm health gate behind the OR-relaxed keyword demotion (image arms never count). normalizeExpansionVariantBudget is the single range contract for the knob: finite (0, 4] (or a string parsing to one) → number, null/legacy/null-literal → null, anything else → undefined (fall through to config → bundle); shared by mode.ts:loadOverridesFromConfig and both per-call seams in hybrid.ts, so an invalid per-call value never reaches fusion or the cache key. interleaveFusion(arms, key, limit): score-free round-robin (each arm's #1, then #2, deduped by key, cut at limit) for fact supersession candidates (facts.candidate_fusion); hybrid search stays on RRF (test/search/interleave-fusion.test.ts). Pure, no engine/IO. Pinned by test/search/fusion-lists.test.ts (knife-edge arithmetic at budget 1.0, legacy deep-equals the pre-role text mapping, role alignment under rejected arms), test/search/expansion-variant-budget.test.ts (hermetic directional PGLite test), and the both-mode demotion-gate regression in test/keyword-relaxed-fusion.serial.test.ts.

  • src/core/search/graph-signals.ts — per-query graph-signals helper. applyGraphSignals(results, engine, opts) runs as the 4th post-fusion stage (after backlink/salience/recency). Three boosts: ADJACENCY_BOOST=1.05 (page linked from 2+ OTHER top-K results — local hub for THIS query), CROSS_SOURCE_BOOST=1.10 (page linked from 2+ DIFFERENT sources — corroborated across team brains, dormant in single-source brains), SESSION_DEMOTE=0.95 (3+ results from same chat session — keep the highest-scoring at full score, demote the rest). All three inherit the floor-ratio gate preventing weak pages from being boosted past strong ones via popularity. computeScoreDistribution(results) emits min/p25/p50/p75/p95/max + reorder_band_width. sessionPrefix(slug) extracts the chat-session anchor (chat/2026-05-15-...). Pure pairedBootstrapPValue(deltas, resamples, rng) exported for eval gates. Test seam via adjacencyFn DI. Fail-open: any error logs via logGraphSignalsFailure (JSONL audit via audit-writer) and returns the input array unchanged. Pinned by test/search/graph-signals.test.ts (incl. the IRON-RULE floor-gate guard). The atoms/ namespace is excluded from session diversification even when a later segment resembles a date or chat marker; daily, meeting and transcript siblings retain their existing demotion.

  • src/core/search/hybrid.ts — Promise<SearchResult[]> return shape. onMeta?: (m: HybridSearchMeta) => void callback so op-layer capture records what hybridSearch actually did. 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, and bare hybridSearch never touches 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[]) (consumer: gbrain whoknows); AND-applies with the single-value type filter. hybridSearch resolves the embedding column via resolveColumn(loadRegistry(cfg), opts.embedding_column, cfg) from src/core/search/embedding-column.ts, threads the ResolvedColumn descriptor 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 (search/cosine-rescore.ts) scores the active column in SQL with the JS rules (a failure falls back to JS and sets cosine_rescore), 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. 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, floor-ratio-gated; 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. Opt-in search.qualified_aliases: the same alias read probes a 3–14 token query's 3–6 token windows (3+ content tokens, longest then leftmost); the first window with a readable claimant leads its page (qualified_alias_hit: autocut and the remote page cap keep it, evidence and the rerank gate ignore it), two claimants suppress it, and a query over 6 tokens probes only windows. Opt-in search.title_qualified (applyQualifiedTitleBoost, last in applyIdentityBoosts): a person/company title mentioned in the query gets title_boost as title_mention_boost, except forward title matches and rows with exact_match_boost. 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. runPostFusionStages has a 4th stage (graphSignalsEnabled, onGraphMeta, onScoreDistribution). base_score stamped once at function entry, before any boost. 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. 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. Every boost stage stamps its own field, which --explain reads. 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. startVectorSide runs modality, expansion and the vector arms alongside the lexical and relational arms (runLexicalAndRelational) on its own timer branch, degraded list and vectorPoolMetaSink; joinVectorSide merges its stamps and expansionApplied after the lexical ones, so degraded[] keeps the sequential order. Every other stage runs in a fixed order: 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). The orchestrators wrap each stage in req.timer / opts._timings (stage-timings.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/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.

    embedQueryBounded preserves its own expired signal's timeout reason when the gateway wraps transport cancellation, keeping embed_timeout stable regardless of which deadline path wins. Provider failures before that deadline retain their classification. The timeout budget and keyword fallback are unchanged; pinned by test/search/query-embed-deadline.test.ts and the real transport matrix. The shared query-embed deadline (lazyQueryEmbedDeadline, threaded to the vector arm as the _queryEmbedDeadline getter) starts at the first embed request, so lexical work and expansion before the vector arm don't spend it; the cache-lookup and vector-arm embeds still share one budget (test/search/query-embed-deadline-start.test.ts).

  • src/core/search/image-loader.ts — loadImageInput(input, opts) accepts a data: URI or http(s):// URL; a local path or file:// URI only with allowLocalPath (trusted local CLI only), after a regular-file and size check. Magic-byte sniff for PNG/JPEG/WebP. Size cap (default 10 MB, search.image_query.max_bytes). URLs go through fetchWithSSRFGuard (pinned DNS answers, no redirect chains), with a 2 MiB cap on decoded remote bodies. ImageLoadError with discriminated code (INVALID_FORMAT / OVERSIZED / INVALID_URL / FETCH_FAILED / TIMEOUT / SSRF_BLOCKED / NOT_FOUND).

  • src/core/search/keyword-paging.ts — keyword counts and keyword-mode paging for search. parseSearchPaging validates match (hybrid default, keyword), cursor, the 10,000 offset cap (search_offset_over_cap; hybrid offset keeps its ranked-list meaning) and refuses an agent-facing mode (search_mode_local_only) and a cursor outside keyword mode (search_cursor_requires_keyword), each with a fix naming match: "keyword". startKeywordCount / countKeywordMatches run engine.countKeywordPages beside the search until max(2 s, search end + KEYWORD_COUNT_GRACE_MS); the result is keyword_total / keyword_truncated (keyword_total_capped past 10,000) or the keyword_count_unavailable degraded stage, never a guess. readKeywordPage reads limit + 1 rows from engine.searchKeywordPages (so truncated and next never depend on the count) and builds next, a ready-to-send argument object whose cursor is a base64url keyset (score, page_id, rows shown) bound to the query, types and source_id. keepEnumeratedRows keeps every enumerated page after evidence delivery (evidence_omitted: true, empty text, when its text did not fit). searchCountLine renders the one model-visible line src/mcp/dispatch.ts appends after the rows on every search call. Tests: test/search-keyword-paging.test.ts, test/search-keyword-cap.slow.test.ts, test/e2e/search-keyword-paging-parity.test.ts.

  • src/core/search/llm-intent.ts — opt-in LLM modality tie-break. classifyModalityWithLLM(query, fallback) routes through gateway.chat() with a fixed single-word-output system prompt; 1s timeout via AbortController. parseModality(raw, fallback) is the pure parser (tolerates trailing punctuation + casing). Fail-open on every error (gateway unavailable, timeout, parse failure, unrecognized output) — returns the fallback so a misbehaving LLM can never break search. Cost-bounded by isAmbiguousModalityQuery in query-intent.ts so the LLM call fires on only a small fraction of queries when on.

  • src/core/search/metadata-boost-gate.ts — the ONE parse + decision contract for search.metadata_boost_gate (always | lexical; every bundle is lexical, DEFAULT_METADATA_BOOST_GATE stays always so a knobs literal without the field keeps its pre-wave hash identity). lexicalArmsVoted answers "did a strict keyword, title-phrase or relational row fuse?" from the composed fusion lists (relaxed OR-fallback rows do not count — they are already demoted); decideMetadataBoosts({gate, lexicalVoted}) returns {gate, lexical_voted, boosts_applied, reason: 'gate_always'|'lexical_voted'|'vector_only_voter'|'image_modality'}. Image-modality queries are exempt from the gate: hybridSearch never runs the keyword / title arms for an image query and excludes the relational arm, so their lexical arms never vote by construction and lexical would silently disable the boosts for the whole modality — the caller passes modality (from effectiveModality) and an image decision applies the boosts as before (reason image_modality). Under lexical, hybridSearch passes skipMetadataBoosts into runPostFusionStages so the backlink, salience, recency (+chronicle), graph-signal and alias-resolved boosts are skipped when the vector arm was the only voter; supersede downrank, exact-match boost, title-phrase boost, compiled-truth boost, cosine re-score, dedup, reranker and autocut are untouched either way. Receipt (Cat 13 conceptual recall, sibling repo): the E1 localization showed hub pages carrying 1.03–1.12x backlink / graph-adjacency / recency boosts over gold concept pages that carried none whenever both lexical arms were empty; the pre-registered E3 held-out arm moved gbrain from 53.0 to 57.8 nDCG@5 (rule ≥ 57.0) with NamedThingBench, BrainBench, the retrieval canary and the LongMemEval dev slice byte-identical, so the gate flipped to lexical in all three bundles. The decision is surfaced as HybridSearchMeta.metadata_boost_gate (--explain); knobs-hash part mbg=; override chain per-call metadataBoostGate → config → bundle (normalizeMetadataBoostGate is the shared parser, garbage falls through). Pinned by test/search/metadata-boost-gate.test.ts (pure contract, hash participation, resolution chain) and test/search/metadata-boost-gate-hybrid.test.ts (hermetic PGLite hub-vs-gold corpus: always reproduces the hub-first regression, the default yields gold-first, config and per-call planes, unparseable falls through).

  • src/core/search/mode.ts — Named search-mode bundles and retained semantic-cache key machinery; persisted result reuse remains disabled. MODE_BUNDLES (conservative/balanced/tokenmax) and the resolution chain (per-call SearchOpts → per-key search.* config → bundle → balanced fallback) resolve every search knob; knobsHash folds registered search knobs into the query_cache key, and KNOBS_HASH_VERSION (exported from this file — the single source of truth for the current cache-key version) is bumped whenever a new knob shapes results so stale cache rows become unreachable. graph_signals: boolean knob in ModeBundle (defaults: conservative=false, balanced=true, tokenmax=true). KNOBS_HASH_VERSION appends a gs= parts entry per the cache-key contamination convention so a graph-on cache write can't be served to a graph-off lookup. SearchKeyOverrides + SearchPerCallOpts + loadOverridesFromConfig + SEARCH_MODE_CONFIG_KEYS + resolveSearchMode + attributeKnob all carry the field. Opt-out: gbrain config set search.graph_signals false. query_cache rows written under an older hash version hash differently — natural row segregation, cleared within cache.ttl_seconds (3600s default). title_boost: number | undefined knob in ModeBundle (default 1.25 for all three modes; multiplier for the post-fusion title-phrase boost). Override chain: per-call SearchOpts → search.title_boost config (clamped [1.0, 5.0]) → bundle. KNOBS_HASH_VERSION appends a tib= parts entry so a title-boost-on cache write can't be served to a title-boost-off lookup. SEARCH_MODE_CONFIG_KEYS gains search.title_boost. Cross-modal knobs in ModeBundle: cross_modal_both_text_weight/cross_modal_both_image_weight (weighted RRF for 'both' modality, defaults 0.6/0.4), image_query_text_refinement_weight/image_query_image_refinement_weight (hybrid intersect for searchByImage query refinement, defaults 0.4/0.6), unified_multimodal + unified_multimodal_only (unified-column routing flags), cross_modal_llm_intent (opt-in LLM escalation). KNOB_CONFIG_KEY (a Record<keyof ModeBundle, string>, so every knob names the search.* key loadOverridesFromConfig reads it from) is the single knob→key map: SEARCH_MODE_CONFIG_KEYS derives from it, attributeKnob prints it as the override source_detail, and KNOWN_CONFIG_KEYS in config.ts hand-mirrors it (config.ts stays import-light; test/config-search-registry.test.ts pins the two equal), and the modality knobs participate in knobsHash so a cached text-mode result can't be served to an image-mode caller. Retrieval-quality knobs autocut_min_top (default 0.35 in all three bundles; config search.autocut_min_top; folds into knobsHash as an acm= part) and evidence_cosine_floor (default 0.8 in all three bundles; config search.evidence_cosine_floor; labels evidence — result-set-shape-neutral, so not hashed) ride the same bundle → config → per-call chain. keywordOrFallback: boolean knob in ModeBundle (default true in all three bundles; config search.keywordOrFallback): the keyword arm's AND→OR zero-recall retry — corpora the FTS config can't stem (CJK/agglutinative text under 'english') can turn it off because the OR retry has no IDF demotion and its common-token hits read as noise in the RRF blend; folds into knobsHash as a kof= part. KnobsHashContext additionally carries the EFFECTIVE per-call salience/recency boost modes (sal=/rec= — explicit SearchOpts ?? the classifier's auto-suggestion, resolved by the same chain bare hybridSearch uses) and the per-engine search.intent_patterns config fingerprint (ipat=, from query-intent.ts's intentPatternFingerprint; threaded through ctx, never read process-globally, so a multi-engine process can't key one brain's rows under another brain's patterns) — a reordered or reclassified write can never serve a differently-configured lookup. Cache HITS slice the stored page to the same resolved result count as misses (per-call limit → the mode's searchLimit) in hybridSearchCached, so a mode's result-count knob holds on both paths; nonzero offsets (positive OR negative) skip the cache entirely. expansion_variant_budget: number | null knob in ModeBundle (null in all three bundles; config search.expansion_variant_budget accepts legacy/null or a number in (0, 4] through the ONE range contract normalizeExpansionVariantBudget in fusion-lists.ts — out-of-range falls through to the bundle; per-call HybridSearchOpts.expansionVariantBudget, normalized by the same function in both the inner search and the cache resolver): the total RRF weight the NON-EMPTY expansion variant/clause lists share at fusion (weight_i = b / n_voting_arms; the original list always keeps weight 1), null = legacy weight 1 on every list (byte-identical fusion), a no-op when expansion is off. It folds into knobsHash as the last, append-only evb= part (legacy or the budget to 3 decimals) — KNOBS_HASH_VERSION is 29 with that part in — so a budget-weighted write can never serve a legacy lookup. KNOB_NULL_LABELS + formatKnobValue in modes-report.ts render its legitimate null as legacy (null) in gbrain search modes (plain (undefined) stays reserved for genuinely unset knobs). relational_rerank_pin: number knob in ModeBundle (3 in all three bundles — a no-op under conservative, which has no reranker; config search.relational_rerank_pin accepts off/0 or an integer in [0, 10] through the ONE range contract normalizeRelationalRerankPin in relational-rerank-pin.ts, out-of-range falls through to the bundle; per-call SearchOpts.relationalRerankPin, normalized by the same function in both the inner search and the cache resolver): how many relational-arm rows pinRelationalRows re-pins above the reranked text rows after applyReranker. It folds into knobsHash as the append-only rrp= part, riding KNOBS_HASH_VERSION 29 together with evb= (one bump per wave — both parts landed before v29 shipped; a partial-knobs literal without the field hashes as the bundle default), so a pin-3 write can never serve a pin-0 lookup. Pinned by test/search-mode.test.ts (bundle snapshots + hash pins), test/search/knobs-hash-reranker.test.ts (the version comment chain), test/config-adaptive-return-keys.test.ts, test/search/modes-report-coverage.test.ts.

  • src/core/search/mode-advice.ts — the one source of the search-mode recommendation (RECOMMENDED_SEARCH_MODE, MODE_REASONS) and the copy that states it: the downstream-input cost matrix priced from model-pricing.ts (costMatrixLines, costMatrixSentence for init's first-run decision), the picker's [AGENT] banner, the post-upgrade banner and QUERY_EXPANSION_LINE; search.mode_source (auto | operator). INSTALL_FOR_AGENTS.md Step 3.5 carries the matrix verbatim (pinned by test/init-mode-picker.test.ts).

  • src/core/search/modes-report.ts — buildModesReport(engine) → SearchModesReport (schema_version: 2), the read-only dashboard behind gbrain search modes and the search_modes MCP op: active_mode + validity, the per-knob resolved attribution (attributeKnob over KNOB_DESCRIPTIONS, including the five reranker_* knobs), the three frozen bundles, config_keys, and reranker_readiness — {model, enabled, ready, required_key, key_present, self_hosted, fix} from rerankerReadinessForEngine + describeRerankerFix (a thrown readiness check still yields a ready: false verdict whose fix says to run gbrain doctor; the block never vanishes silently). redactReadinessForRemote(report) is what the search_modes op returns when ctx.remote !== false: required_key, key_present and fix are dropped and self_hosted is forced false — which env vars exist on the host is fingerprinting data and the fix names them; ready stays because it is observable anyway (reranked results carry rerank_score). src/commands/search.ts:formatModesText renders the runtime Reranker: line (off (resolved) — … / <model> (enabled) — <KEY> present / <model> (enabled but NOT running) — <fix>) and a per-bundle reranker=… topNIn=… autocut=… line. Pinned by test/modes-report-reranker.test.ts. The CLI dashboard leads with command-specific expansion: query follows the mode's expansion default (off in all modes) unless the call passes expand, while search is off. It discloses provider prerequisites/text flow and distinguishes retained bundle configuration from effective command behavior.

  • src/core/search/private-visibility.ts — shared page-visibility resolver and SQL predicates. Explicit local trust disables page filtering; operator env/config opt-outs keep their semantics; failed config reads enforce privacy. privatePagesFilterFragment authorizes concrete page rows and isPrivatePage is its row-side twin: explicit private hides a page, absent visibility is world for ordinary pages and private for extracted atoms (type = 'atom') and synthesized concepts (type = 'concept' with synthesized_by), because their origin may be a private page or transcript. The page predicate also follows derived origins: an atom whose source_slug page is explicitly private, and a synthesized concept with a private input atom (or an input whose origin is private, including an origin a rename moved after a later rename onto the old slug dropped its alias: slug_rename_history, GST-2687) over concept-provenance edges, are private whatever their own field says, so a later private flip of an origin reaches derived pages before any repair. The concept-input test is the SQL function gbrain_concept_inputs_private(page_id) (migration v311, never inlined, so a read plans one call per page instead of the subplans); a read uses it when its schema version is v311 or later: the one a remote, scope or attested record carries (RemotePolicy.schemaVersion), or for a local read the one its scoped engine recorded at connect or migration (schemaVersionSeen, migrate-pending.ts); otherwise the same test runs inline, so reads keep working before the migration applies. Chronicle events follow event.depth (fail closed). Declared lineage matches derived_from slugs with = ANY(ARRAY(...)), not IN (SELECT ... jsonb_array_elements_text(...)): same rows, but the planner priced the IN form as a 100-row semi-join per page and pushed every read carrying the rule past jit_above_cost (test/e2e/private-visibility-plan-postgres.test.ts, which measures with links and slug_rename_history both unanalyzed and analyzed; test test/concept-rename-history-gst2687.test.ts, both engines). privateSnapshotFilterFragment is the same rule on a row's own frontmatter for page_versions. effectiveVisibility(origin) (transcript or missing origin private, page origin per the read rule) and strictestVisibility are used by both extract_atoms paths, concept synthesis and gbrain repair visibility. Remote publication rechecks (persistence/page-visibility.ts) and the alias-inject recheck in hybrid.ts use the same rule. Tests: test/private-visibility.test.ts, test/derived-page-visibility.test.ts (PGLite and Postgres); link origins and timeline projections use independent ID-based predicates. privateProvenanceFilterFragment hides a fact whose provenance page (source_markdown_slug) is private; the fact-list reads in engine-sql/facts.ts (by entity, since, keyset, session, supersessions, trajectory) apply it behind FactListOpts.excludePrivate / TrajectoryOpts.excludePrivate, which every remote fact surface resolves with resolveExcludePrivatePages (test/remote-fact-list-private-provenance.test.ts, both engines). Remote fact writes apply the same predicate behind an excludePrivate option: forget (guardRemoteForget, the row lock in persistence/memory-mutations.ts, recordFactWithdrawal, similarActiveAfterForget) and remember (decideSingleFact's exact and cosine arms, decideReplacement), so a fact remote reads hide is not_found to a remote write and never matched as its duplicate (test/remote-fact-write-private-provenance.test.ts, both engines). Legacy slug-set helpers only enumerate names; they never authorize another row's data. ops/context.ts:readPolicyOpts combines canonical source precedence, resolved privacy and holder permissions. Both engines filter content/history/graph/identity/analytics before limits or aggregation; current and historical visibility are checked independently while page privacy is enforced. Semantic response caching remains disabled, so visibility-key folding alone never authorizes reuse.

  • src/core/search/projection-readiness.ts — one JIT-off statement probes visible unsealed pages: ready, projection_pending, by_design (only protected/archived unsealed) or unknown; LIMIT 1 arms use the v317 idx_pages_projection_waiting partial index (only pages out of search, so pages still served from their pre-v153 index are not walked; #9192). Cached per scope by DB generation (page clock, pages filenode, archive flags, no open tx); GBRAIN_PROJECTION_READINESS_CACHE=0 disables.

  • src/core/search/projection-statistics.ts — current-projection expression statistics, strict migration postconditions and owner-authorized batch refresh. Migration 160 verifies object identity and populated samples before advancing the ledger, distinguishing empty tables from statistics this role cannot see. Import, sync, reindex and drained recovery refresh outside page locks; failures preserve completed writes and give a maintenance hint. A pass that changed fewer than 50 + 10% of the sampled pages leaves the statistics alone once they exist (the projection statistic and, on Postgres, every SEARCH_STATISTICS_COLUMNS column: missingSearchStatistics), and PGLite then analyzes only the hot tables its row deltas mark stale. On Postgres it also samples the page columns search filters read (SEARCH_PAGE_STATISTICS_SQL) and the chunk SEARCH_STATISTICS_COLUMNS; a vacuum holding a table defers it (analyze-lock.ts). refreshChunkStatistics runs the chunk step after a drain that changed 50 + 10% of chunks (any sans statistics): without them the vector candidate statement sorts every eligible chunk instead of walking the HNSW index (test/e2e/vector-chunk-statistics-postgres.test.ts). Absent search statistics (pg_upgrade, a deleted pg_statistic; 50-60 s searches at 5k pages) get ensureSearchStatistics: PostgresEngine runs it once per engine in the background on its first pool search (never awaited; disconnect waits), and doctor planner_stats_stale plus repair planner-stats report and apply the same refresh (test/search-statistics-guard.test.ts).

  • src/core/search/query-cache.ts — stored semantic-cache data and maintenance remain, but semanticResultCacheAvailable() is false. hybridSearchCached bypasses both result lookup and writes regardless of configuration or useCache, and skips the key/config setup (merged config, cache config, intent-pattern state) so the wrapper adds no engine round-trips; request-local query embeddings still work. Search metadata, cache_stats and the mode dashboard report effective caching as disabled. Historical hit counts and search_telemetry remain intact. Restoration requires complete response-dependency provenance.

  • src/core/search/query-intent.ts — Deterministic query classifiers (pure, no LLM): classifyQuery/classifyQueryIntent (entity/temporal/event/concept/general → auto-selects detail level, salience/recency/modality axes; concept fires on definitional-paraphrase OR landscape/quantifier cues with a proper-noun name-guard — capitalized names, quoted phrases, slugs, and sub-3-word queries never trigger — and ranks vector-lean via the RRF-k tilt in intent-weights.ts), isAmbiguousModalityQuery (LLM-escalation gate), and the concept-shape pair — looksConceptShaped (fuzzy-quantifier/landscape cues minus exact-identifier anti-signals, tuned to favor false-negatives; cues owned by other routers like "who are the"/find_experts and bare "anything"/salience are deliberately excluded) + conceptNudge (full one-line CLI hint string steering a concept-shaped search toward query; consumed by maybePrintConceptNudge in src/cli.ts on BOTH the local-engine and thin-client result paths, stderr-only, --quiet-gated). Pinned by test/query-intent-concept.test.ts + test/cli-concept-nudge.test.ts.

More entries