Garry's Opinionated OpenClaw/Hermes Agent Brain
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/searchVectorapply source-aware ranking at the SQL layer (curated content likeoriginals/,concepts/,writing/outranks bulk content like<fork>/chat/,daily/,media/x/).searchVectoruses 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 honordetail !== '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, thenapplyAliasHopLookup;aliasHopCanonicalsis the filtered, ordered, capped canonical list both apply and the rerank gate read; re-exported byhybrid.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.tsimports it). Behavior is documented under thehybrid.tsentry. Pinned bytest/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 frontmatteraliases:intopage_aliases) and the READ path (search matches query againstpage_aliases), so stored aliases can't silently fail to match queries via divergent normalization (same single-source posture ascjk.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 thereindex --aliasesbackfill.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 rawscorecolumn into a scale-free statistic (top,second,margin_ratio; TypeScript-side — engines still return rawts_rank × sourceFactor, no SQL change);decideKeywordArmWeight({keywordList, floor, vectorArmVoted, relationalQuery})down-weights the keyword AND title fusion entries toKEYWORD_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, andmargin_ratio < floor; otherwise it emits no weight (byte-identical fusion). It is called fromcomposeFusionLists(fusion-lists.ts) so the weight lands through the same per-listweightprimitive as the expansion budget, never a k change.normalizeKeywordArmConfidenceFlooris the ONE range contract (number in(0, 1]or a string parsing to one;null/false/off→null; anything else →undefined= fall through), shared bymode.ts:loadOverridesFromConfigand both per-call seams inhybrid.ts. The decision ({top, second, margin_ratio, downweighted}) is surfaced asHybridSearchMeta.keyword_arm_confidenceeven with the floor off, so a calibration run can pick a floor from per-probe receipts; knobs-hash partkacf=. Pinned bytest/search/arm-confidence.test.ts(pure contract) andtest/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 truere-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 clearsjumpRatio(default 0.20); robust to unsorted provider output (cuts on a sorted copy, keeps items in INPUT order via a score threshold), guardstop<=0/non-finite, never returns empty, and no-ops when <2 results carry a finitererank_score(covers the reranker fail-open path). WHY rerank_score and NOT RRF/cosine: gbrain measured (seereturn-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;conservativeis a documented no-op). Weak-top floor: when the top rerank score is belowminTopScore(default 0.35; configsearch.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. ExportsAutocutConfig,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 throughModeBundle→ResolvedSearchKnobs→knobsHashexactly likegraph_signals.mode.tsaddsautocut/autocut_jump/autocut_min_keep(autocutfalse 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_keepsets the minimum result count a cut may leave, resolved through the same bundle → config → per-call chain) AND setsreranker_top_n_in = searchLimitfor reranked modes (so the reranker scores the full returned set; there is no un-scored tail for autocut to wrongly drop). Autocut folds intoknobsHashas its own parts entry (mode.ts:KNOBS_HASH_VERSIONis the single source of truth for the current hash version; every bump is a one-time global cache cold-miss on upgrade). Wired intohybridSearchAFTER adaptive-return, BEFORE the limit slice, first page only; emitsHybridSearchMeta.autocut. BOTH the cache-missfinalMetaand cache-HITcachedMetarebuilds carryautocut+adaptive_return+mode+embedding_column. Preserves alias-hop exact matches:applyAutocuttakes an optionalpreservepredicate; hybrid passesr => r.alias_hit === true || r.exact_lookup !== undefined || r.relational_pinned === trueso a canonical page injected byapplyAliasHopafter reranking (norerank_score), an exact-lookup tier hit, or a relational row re-pinned bypinRelationalRows(low cross-encoder score by construction; ALSO excluded from the cliff computation throughscoreOf, so text-row autocut is unchanged by the pin) is never cut. Agent surface:queryopautocutboolean (ceiling override —falseforces full top-K);SearchOpts.autocut;--explainshows per-resultrerank_score,formatAutocutSummaryrenders the decision when search meta is threaded;gbrain search modesattribution; metric glossaryautocut.signal/autocut.gap_ratio. Config:search.autocut,search.autocut_jump,search.autocut_min_keep. TheDEFAULT_AUTOCUTmodule 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(alsobun 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 bytest/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 viarerankerFnDI seam: cliff trims, flat doesn't, no-reranker no-ops,autocut:falseceiling, composes with adaptive-return),test/search/autocut-eval.test.ts(the precision/recall gate), and the knobsHash assertions intest/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 optionalquery, runs a parallel text branch viaembedQueryMultimodal(query)and merges viarrfFusionWeightedwitheffectiveRrfK(baseRrfK, weight)from the resolved mode's refinement weights. Widens to the unified column whensearch.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 publicsincestarts 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 forsearch/query.effectiveDateLabel(source)mapseffective_date_sourceto 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]linesrc/mcp/dispatch.tsappends 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) keepeffective_date_sourcefor 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 LongMemEvalnotesessions only loses multi-session recall (pinned intest/dedup.test.ts), (4) max 2 chunks per page (default;hybrid.ts's two-pass structural expansion widens it; withregions(segmentRegions: one query, only when a page has over 2 results; passed byhybrid.tsand both keyword-only paths) a segmented page applies (1) and (4) per occurrence cluster (gaps over 1 MiB split) and keeps at mostMAX_PER_SEGMENTED_PAGE6), (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 bypageKey()(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.tspassesmax(PRE_FUSION_POOL_FLOOR, N)as theperArmPoolLimitfloor; still capped atMAX_SEARCH_LIMITunless an eval pool depth is set),capPerSessionkeeps the first row of each session in the deduped pool (hybrid/rank.tscapSessionPool, called ondedupResults' output; a session issessionPrefix(slug)fromgraph-signals.ts, else the page, keyed with the source id) andrerankAndPinraises the reranker'stopNInto at least N. The keyword-only paths have no reranker and are unchanged.normalizeDiversePoolDepthis the one range contract (mode.ts config parse and thegbrain config setrefusal throughsearch/config-values.ts); the mode field folds intoknobsHashas an append-onlydpd=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 "whichcontent_chunks.*column does this query rank against?" Pure functions, no engine I/O:loadRegistry(cfg)walks theembedding_columnsconfig (DB plane, JSON map keyed by column name with{provider, dimensions, type}entries), seeds the OpenAIembeddingbuiltin when unset, validates everything before it lands (column-name regex, type ∈vector | halfvec, dims in [1, 8192], provider format) usingObject.create(null)+Object.hasOwnso a key likeconstructorrejects instead of resolving toObject.prototype.constructor.resolveColumn(registry, override?, cfg)is the boundary call: returns a frozenResolvedColumndescriptor ({name, provider, dimensions, type}) honoring per-call override →search_embedding_columnconfig →'embedding'default; throwsUnknownEmbeddingColumnErrorwith the list of registered names on miss.isCacheSafe(resolved, cfg)compares the full embedding SPACE (provider + dimensions + name) against cfg's default so a repointedembeddingbuiltin 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 byhybridSearch,gateway.embedQuery(text, {embeddingModel, dimensions}),cosineReScore, and thequeryMCP op (per-callembedding_columnparam). Engine column routing is covered bytest/e2e/embedding-column-pglite.test.ts,test/e2e/embedding-column-postgres.test.tsandtest/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 (legacyembeddingdescriptor when neither row routes elsewhere;embedding_imagefalls 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), andvectorCastSuffix(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 bytest/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. Thevectorstrategy runs the production query path:embedQuery(query-sideinput_typeon 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 cosineSearchResult.cosine≥DEFAULT_HIGH_COSINE_FLOOR=0.8, overridable viaEvidenceOpts.cosineFloor/ configsearch.evidence_cosine_floor; never the blended score, so a keyword+boost pile-up can't earn it; legacyHIGH_MATCH_FLOOR=0.85is exported for back-compat only) >keyword_exact(base ≥SOLID_MATCH_FLOOR=0.6; GBRA-449: any strict row underEvidenceOpts.keywordMode, which only searchmatch: "keyword"sets, except amatched_aliasrow) >weak_semantic).createSafetyFor(evidence)derives the don't-duplicate hint (exists/probable/unknown) agents key off instead of a raw threshold.stampEvidence(results, opts?)stampsevidence+create_safetyin place once at pipeline end (after the alias hop, before slice); idempotent;create_safetyignoreskeywordMode, so a relabelled row keepsunknown.keyword_relaxedrows never earnkeyword_exact; CRAG grades a relaxed topweak(A4-2).src/core/search/expansion.ts— Multi-query expansion via Haiku. ExportssanitizeQueryForPrompt+sanitizeExpansionOutput(prompt-injection defense-in-depth). Sanitized query is only used for the LLM channel; the original query still drives search.expandQueryreturns the original first plus 2-3 variants;hybridSearchre-enforcesqueries[0]= the caller's query and dedupes repeats, then fuses each variant's vector list as a rolevariantarm throughsrc/core/search/fusion-lists.ts(see that entry), where the variant arms sharesearch.expansion_variant_budgetas total RRF weight —null(every bundle's default) is legacy equal weight, the configuration under which the LongMemEval receipt shows expansion halving strictrecall_all@5(93.19% plain hybrid vs 54.89% with expansion, paired +3 / -183;docs/architecture/RETRIEVAL.md"Multi-query expansion"). The harness recordsexpansion_variantsper row and--expansion-replayserves them back so a budget sweep changes only the budget.src/core/search/explain-formatter.ts— rendersSearchResult[]as a multi-line per-result breakdown forgbrain search --explain. Reads every boost-stamping field (title_mention_boostrenders astitle-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) andformatDegradedSummary(meta.degraded), which renders the closeddegraded[]vocabulary asdegraded: reranker_skipped (no_key)(null when the run was clean);cli.ts:formatResultthreadslastRetrievalMetainto it, so a silently skipped reranker is visible from the CLI. Pinned bytest/search/explain-formatter.test.ts+test/cli-explain-degraded-render.test.ts.formatDecideSummaryprints onedecide <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 thetimings:line.src/core/search/fusion-lists.ts— the ONE composition point forhybridSearch's RRF inputs. Every vector recall list is a ROLE-tagged arm (VectorArm {list, role: 'original'|'variant'|'clause'|'image'}, appended only viapushVectorList) — never a parallel index-aligned array, since theallSettledsalvage 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 attextRrfKand the image arm atimageRrfKonly when BOTH kinds are present, otherwise every arm atvectorK(text, image-only, unified, and a both-mode whose image branch fell open).variant/clausearms shareexpansionVariantBudgetas total RRF weight —weight_i = b / n_voting_armsover the NON-EMPTY expansion arms (an empty list casts no vote), theoriginalarm always weight 1; anullbudget emits noweightkey, byte-identical to unweighted fusion; when the original is missing every surviving text arm is avariantsharing the budget.rrfFusionWeighted(hybrid.ts) scoresweight / (k + rank)(weighted RRF: a list-level multiplier at every rank).textArmsNonEmptyis the role-based text-arm health gate behind the OR-relaxed keyword demotion (image arms never count).normalizeExpansionVariantBudgetis 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 bymode.ts:loadOverridesFromConfigand both per-call seams inhybrid.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 atlimit) for fact supersession candidates (facts.candidate_fusion); hybrid search stays on RRF (test/search/interleave-fusion.test.ts). Pure, no engine/IO. Pinned bytest/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 intest/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-...). PurepairedBootstrapPValue(deltas, resamples, rng)exported for eval gates. Test seam viaadjacencyFnDI. Fail-open: any error logs vialogGraphSignalsFailure(JSONL audit viaaudit-writer) and returns the input array unchanged. Pinned bytest/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) => voidcallback 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 barehybridSearchnever touchesquery_cache.HybridSearchOpts.types?: PageType[](onSearchOpts) threads a multi-type filter into per-enginesearchKeyword+searchVector+searchKeywordChunksasAND p.type = ANY($N::text[])(consumer:gbrain whoknows); AND-applies with the single-valuetypefilter.hybridSearchresolves the embedding column viaresolveColumn(loadRegistry(cfg), opts.embedding_column, cfg)fromsrc/core/search/embedding-column.ts, threads theResolvedColumndescriptor into per-enginesearchVector, and usesisCacheSafe(resolved, cfg)for the cache-skip decision so a repointedembeddingbuiltin 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 setscosine_rescore), and hydrates each result's raw query↔chunkcosineontoSearchResult(the calibrated signal evidence and--explainconsume).SearchOpts.onVectorPoolMetareports 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. ThequeryMCP op acceptsembedding_columnfor 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 resolvedtitle_boostwhenisTitlePhraseMatchfires, stampstitle_match_boost, floor-ratio-gated;applyAliasHop(engine, results, query, opts)normalizes the query, callsengine.resolveAliases, and on exact normalized-alias match surfaces that page at top-of-organic + epsilon withalias_hit=true. Both identity injections (alias hop and exact-lookup tier) take oneIdentityTierOptsbuilt once per request and skip any slugisExcludedIdentityrejects: callerexclude_slugsplus the resolved prefix excludes (resolveHardExcludes: defaults,GBRAIN_SEARCH_EXCLUDE, per-call prefixes, minusinclude_slug_prefixes), on all three return paths. Opt-in single-token hop (#5428; per-callaliasTokenHopor brain configsearch.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-insearch.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-insearch.title_qualified(applyQualifiedTitleBoost, last inapplyIdentityBoosts): a person/company title mentioned in the query getstitle_boostastitle_mention_boost, except forward title matches and rows withexact_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 byscore, 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--explainread the sameevidence+create_safetycontract.runPostFusionStageshas a 4th stage (graphSignalsEnabled,onGraphMeta,onScoreDistribution).base_scorestamped 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) stampsreranker_deltaas a rank delta (positive = improved).applyExactMatchBoostinsrc/core/search/intent-weights.tsstampsexact_match_boostwhen fired — on an exact slug/title match OR a title / slug tail mentioned inside the query (isTitleMentionedInQuery), andapplyAliasMentionBoostgives the same bounded boost to a present row whose declared alias occurs in the query (one batchedresolveAliasesover 1–5-token query n-grams, fail-open). Fusion is page-grain:rrfFusion/rrfFusionWeightedsum 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 EXPLICITdetail: 'low'hard-filters every arm to compiled truth (with the 2x boost and the zero-result escalation); an auto-detectedlow(entity intent) passes no SQL filter and appliesAUTO_LOW_COMPILED_TRUTH_TILT(1.2x) viacompiledTruthFusionBoost. The engine opts rebuild forwardsexclude_slugs,exclude_slug_prefixesandinclude_slug_prefixesto every arm. A rejected keyword or title arm fails open and stampskeyword_arm_failed/title_arm_failed(reasontimeout | provider_error) inmeta.degraded, so MCP callers can tell a partial read from a clean miss. InbothmodalitycosineReScorerescores 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 oneapplyIdentityBoostsclosure on the fused path and both keyword-only paths. Under unified multimodal routing the cosine rescore hydratesembedding_multimodal(the space the query was embedded in), andcosineSimilarityreturns 0 for vectors of different lengths. Every boost stage stamps its own field, which--explainreads. withsrc/core/search/sql-ranking.ts+src/core/operations.ts+src/core/types.ts: agent-warning channel.SearchResult.content_flag?: {reason, detail}(optional field intypes.ts) is stamped post-fusion bystampContentFlags(thestampEvidenceprecedent) inhybridSearchAND in the keyword-onlysearchMCP op so both retrieval paths surface the marker.get_pagereturns a top-levelcontent_flagparallel field viagetContentFlag(page.frontmatter).buildVisibilityClause(sql-ranking.ts) ANDs inQUARANTINE_FILTER_FRAGMENTso quarantined pages are excluded from all six search call sites (alongside soft-delete + archived-source filters). Pinned bytest/sql-ranking.test.ts+test/e2e/quarantine-search-exclusion.test.ts. Cross-modal routing at the embed step:effectiveModalityresolves per-callopts.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 viarrfFusionWeightedwitheffectiveRrfK(baseRrfK, weight)from the configured cross-modal weights. Unified routing fires whensearch.unified_multimodalis true — bypasses dual-column branching, runsembedQueryMultimodal+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'ANDsearch.cross_modal.llm_intentis on ANDisAmbiguousModalityQueryfires; fail-open on every error.compiledTruthBoost(result, applyBoost)is exported for direct predicate tests: a synthetic chunkless title row (chunk_id === 0AND blankchunk_text) never receives the 2x compiled-truth boost (test/search/compiled-truth-boost.test.ts). The reranker pass-through callback is typed withRerankPassThroughReasonimported fromrerank.ts— one union, not a re-declaration. RRF inputs are assembled by ONEcomposeFusionListscall (next entry) over role-taggedvectorArmsbuilt withpushVectorListat every assembly site (unified, image-only, text/both, and theallSettledsalvage path — where theoriginalrole additionally requires the original'ssearchVectorto have succeeded); afterexpandFn,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 beforeapplyAutocutwith the exact pre-autocutreturnPool— 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 afterapplyReranker— 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 byresolvedMode.relational_rerank_pin, stampsrelational_pinned, and emitsHybridSearchMeta.relational_rerank_pin;ensureRelationalEvidenceSlotstill 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 -pon that file).hybridSearchandhybridSearchCachedare short orchestrators over the named stages insrc/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.startVectorSideruns modality, expansion and the vector arms alongside the lexical and relational arms (runLexicalAndRelational) on its own timer branch,degradedlist andvectorPoolMetaSink;joinVectorSidemerges its stamps andexpansionAppliedafter the lexical ones, sodegraded[]keeps the sequential order. Every other stage runs in a fixed order:request.ts(resolveHybridRequestbuilds aHybridRequestonce: mode, embedding column, limits (per-arm pool fromperArmPoolLimitinsrc/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 accumulatorsvectorPoolUnderfill/expansionApplied/lastResultsCount/lastRank1Scorethat stages write only asreq.<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 thecrag.tsentry in Core Search 2/2). The orchestrators wrap each stage inreq.timer/opts._timings(stage-timings.ts). Stages import public helpers back fromhybrid.tsat call time only (theexact-lookup.tspattern);hybrid.tsexports nothing new. Pinned bytest/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; onlygbrain eval longmemeval --eval-pool-depthcalls it) raisessearchLimitCap()(the per-arm cap both engines' keyword/vector arms clamp to, defaultMAX_SEARCH_LIMIT100) and makes every arm fetch N (perArmPoolLimit, used byhybrid/request.ts). Production depth is unchanged. Tests:test/eval-pool-depth.test.ts.embedQueryBoundedpreserves its own expired signal's timeout reason when the gateway wraps transport cancellation, keepingembed_timeoutstable regardless of which deadline path wins. Provider failures before that deadline retain their classification. The timeout budget and keyword fallback are unchanged; pinned bytest/search/query-embed-deadline.test.tsand the real transport matrix. The shared query-embed deadline (lazyQueryEmbedDeadline, threaded to the vector arm as the_queryEmbedDeadlinegetter) 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 adata:URI orhttp(s)://URL; a local path orfile://URI only withallowLocalPath(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 throughfetchWithSSRFGuard(pinned DNS answers, no redirect chains), with a 2 MiB cap on decoded remote bodies.ImageLoadErrorwith discriminatedcode(INVALID_FORMAT / OVERSIZED / INVALID_URL / FETCH_FAILED / TIMEOUT / SSRF_BLOCKED / NOT_FOUND).src/core/search/keyword-paging.ts— keyword counts and keyword-mode paging forsearch.parseSearchPagingvalidatesmatch(hybriddefault,keyword),cursor, the 10,000 offset cap (search_offset_over_cap; hybridoffsetkeeps its ranked-list meaning) and refuses an agent-facingmode(search_mode_local_only) and a cursor outside keyword mode (search_cursor_requires_keyword), each with a fix namingmatch: "keyword".startKeywordCount/countKeywordMatchesrunengine.countKeywordPagesbeside the search until max(2 s, search end +KEYWORD_COUNT_GRACE_MS); the result iskeyword_total/keyword_truncated(keyword_total_cappedpast 10,000) or thekeyword_count_unavailabledegraded stage, never a guess.readKeywordPagereadslimit + 1rows fromengine.searchKeywordPages(sotruncatedandnextnever depend on the count) and buildsnext, a ready-to-send argument object whosecursoris a base64url keyset(score, page_id, rows shown)bound to the query,typesandsource_id.keepEnumeratedRowskeeps every enumerated page after evidence delivery (evidence_omitted: true, empty text, when its text did not fit).searchCountLinerenders the one model-visible linesrc/mcp/dispatch.tsappends 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 throughgateway.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 byisAmbiguousModalityQueryinquery-intent.tsso 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 forsearch.metadata_boost_gate(always|lexical; every bundle islexical,DEFAULT_METADATA_BOOST_GATEstaysalwaysso a knobs literal without the field keeps its pre-wave hash identity).lexicalArmsVotedanswers "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:hybridSearchnever runs the keyword / title arms for an image query and excludes the relational arm, so their lexical arms never vote by construction andlexicalwould silently disable the boosts for the whole modality — the caller passesmodality(fromeffectiveModality) and an image decision applies the boosts as before (reasonimage_modality). Underlexical,hybridSearchpassesskipMetadataBoostsintorunPostFusionStagesso 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 tolexicalin all three bundles. The decision is surfaced asHybridSearchMeta.metadata_boost_gate(--explain); knobs-hash partmbg=; override chain per-callmetadataBoostGate→ config → bundle (normalizeMetadataBoostGateis the shared parser, garbage falls through). Pinned bytest/search/metadata-boost-gate.test.ts(pure contract, hash participation, resolution chain) andtest/search/metadata-boost-gate-hybrid.test.ts(hermetic PGLite hub-vs-gold corpus:alwaysreproduces 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-callSearchOpts→ per-keysearch.*config → bundle → balanced fallback) resolve every search knob;knobsHashfolds registered search knobs into thequery_cachekey, andKNOBS_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: booleanknob inModeBundle(defaults:conservative=false,balanced=true,tokenmax=true).KNOBS_HASH_VERSIONappends ags=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+attributeKnoball carry the field. Opt-out:gbrain config set search.graph_signals false.query_cacherows written under an older hash version hash differently — natural row segregation, cleared withincache.ttl_seconds(3600s default).title_boost: number | undefinedknob inModeBundle(default1.25for all three modes; multiplier for the post-fusion title-phrase boost). Override chain: per-callSearchOpts→search.title_boostconfig (clamped[1.0, 5.0]) → bundle.KNOBS_HASH_VERSIONappends atib=parts entry so a title-boost-on cache write can't be served to a title-boost-off lookup.SEARCH_MODE_CONFIG_KEYSgainssearch.title_boost. Cross-modal knobs inModeBundle: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 forsearchByImagequery 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(aRecord<keyof ModeBundle, string>, so every knob names thesearch.*keyloadOverridesFromConfigreads it from) is the single knob→key map:SEARCH_MODE_CONFIG_KEYSderives from it,attributeKnobprints it as the overridesource_detail, andKNOWN_CONFIG_KEYSinconfig.tshand-mirrors it (config.ts stays import-light;test/config-search-registry.test.tspins the two equal), and the modality knobs participate inknobsHashso a cached text-mode result can't be served to an image-mode caller. Retrieval-quality knobsautocut_min_top(default 0.35 in all three bundles; configsearch.autocut_min_top; folds intoknobsHashas anacm=part) andevidence_cosine_floor(default 0.8 in all three bundles; configsearch.evidence_cosine_floor; labels evidence — result-set-shape-neutral, so not hashed) ride the same bundle → config → per-call chain.keywordOrFallback: booleanknob inModeBundle(default true in all three bundles; configsearch.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 intoknobsHashas akof=part.KnobsHashContextadditionally carries the EFFECTIVE per-call salience/recency boost modes (sal=/rec=— explicitSearchOpts?? the classifier's auto-suggestion, resolved by the same chain barehybridSearchuses) and the per-enginesearch.intent_patternsconfig fingerprint (ipat=, fromquery-intent.ts'sintentPatternFingerprint; 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-calllimit→ the mode'ssearchLimit) inhybridSearchCached, so a mode's result-count knob holds on both paths; nonzero offsets (positive OR negative) skip the cache entirely.expansion_variant_budget: number | nullknob inModeBundle(nullin all three bundles; configsearch.expansion_variant_budgetacceptslegacy/nullor a number in (0, 4] through the ONE range contractnormalizeExpansionVariantBudgetinfusion-lists.ts— out-of-range falls through to the bundle; per-callHybridSearchOpts.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 whenexpansionis off. It folds intoknobsHashas the last, append-onlyevb=part (legacyor the budget to 3 decimals) —KNOBS_HASH_VERSIONis 29 with that part in — so a budget-weighted write can never serve a legacy lookup.KNOB_NULL_LABELS+formatKnobValueinmodes-report.tsrender its legitimate null aslegacy (null)ingbrain search modes(plain(undefined)stays reserved for genuinely unset knobs).relational_rerank_pin: numberknob inModeBundle(3 in all three bundles — a no-op underconservative, which has no reranker; configsearch.relational_rerank_pinacceptsoff/0or an integer in [0, 10] through the ONE range contractnormalizeRelationalRerankPininrelational-rerank-pin.ts, out-of-range falls through to the bundle; per-callSearchOpts.relationalRerankPin, normalized by the same function in both the inner search and the cache resolver): how many relational-arm rowspinRelationalRowsre-pins above the reranked text rows afterapplyReranker. It folds intoknobsHashas the append-onlyrrp=part, ridingKNOBS_HASH_VERSION29 together withevb=(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 bytest/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 frommodel-pricing.ts(costMatrixLines,costMatrixSentencefor init's first-run decision), the picker's[AGENT]banner, the post-upgrade banner andQUERY_EXPANSION_LINE;search.mode_source(auto|operator).INSTALL_FOR_AGENTS.mdStep 3.5 carries the matrix verbatim (pinned bytest/init-mode-picker.test.ts).src/core/search/modes-report.ts—buildModesReport(engine)→SearchModesReport(schema_version: 2), the read-only dashboard behindgbrain search modesand thesearch_modesMCP op:active_mode+ validity, the per-knobresolvedattribution (attributeKnoboverKNOB_DESCRIPTIONS, including the fivereranker_*knobs), the three frozenbundles,config_keys, andreranker_readiness—{model, enabled, ready, required_key, key_present, self_hosted, fix}fromrerankerReadinessForEngine+describeRerankerFix(a thrown readiness check still yields aready: falseverdict whosefixsays to rungbrain doctor; the block never vanishes silently).redactReadinessForRemote(report)is what thesearch_modesop returns whenctx.remote !== false:required_key,key_presentandfixare dropped andself_hostedis forced false — which env vars exist on the host is fingerprinting data and the fix names them;readystays because it is observable anyway (reranked results carryrerank_score).src/commands/search.ts:formatModesTextrenders the runtimeReranker:line (off (resolved) — …/<model> (enabled) — <KEY> present/<model> (enabled but NOT running) — <fix>) and a per-bundlereranker=… topNIn=… autocut=…line. Pinned bytest/modes-report-reranker.test.ts. The CLI dashboard leads with command-specific expansion:queryfollows the mode's expansion default (off in all modes) unless the call passesexpand, whilesearchis 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.privatePagesFilterFragmentauthorizes concrete page rows andisPrivatePageis its row-side twin: explicitprivatehides a page, absent visibility is world for ordinary pages and private for extracted atoms (type = 'atom') and synthesized concepts (type = 'concept'withsynthesized_by), because their origin may be a private page or transcript. The page predicate also follows derived origins: an atom whosesource_slugpage 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) overconcept-provenanceedges, 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 functiongbrain_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 followevent.depth(fail closed). Declared lineage matchesderived_fromslugs with= ANY(ARRAY(...)), notIN (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 pastjit_above_cost(test/e2e/private-visibility-plan-postgres.test.ts, which measures withlinksandslug_rename_historyboth unanalyzed and analyzed; testtest/concept-rename-history-gst2687.test.ts, both engines).privateSnapshotFilterFragmentis the same rule on a row's own frontmatter forpage_versions.effectiveVisibility(origin)(transcript or missing origin private, page origin per the read rule) andstrictestVisibilityare used by bothextract_atomspaths, concept synthesis andgbrain repair visibility. Remote publication rechecks (persistence/page-visibility.ts) and the alias-inject recheck inhybrid.tsuse 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.privateProvenanceFilterFragmenthides a fact whose provenance page (source_markdown_slug) is private; the fact-list reads inengine-sql/facts.ts(by entity, since, keyset, session, supersessions, trajectory) apply it behindFactListOpts.excludePrivate/TrajectoryOpts.excludePrivate, which every remote fact surface resolves withresolveExcludePrivatePages(test/remote-fact-list-private-provenance.test.ts, both engines). Remote fact writes apply the same predicate behind anexcludePrivateoption:forget(guardRemoteForget, the row lock inpersistence/memory-mutations.ts,recordFactWithdrawal,similarActiveAfterForget) andremember(decideSingleFact's exact and cosine arms,decideReplacement), so a fact remote reads hide isnot_foundto 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:readPolicyOptscombines 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 v317idx_pages_projection_waitingpartial 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=0disables.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, everySEARCH_STATISTICS_COLUMNScolumn: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 chunkSEARCH_STATISTICS_COLUMNS; a vacuum holding a table defers it (analyze-lock.ts).refreshChunkStatisticsruns 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) getensureSearchStatistics: PostgresEngine runs it once per engine in the background on its first pool search (never awaited; disconnect waits), and doctorplanner_stats_staleplusrepair planner-statsreport and apply the same refresh (test/search-statistics-guard.test.ts).src/core/search/query-cache.ts— stored semantic-cache data and maintenance remain, butsemanticResultCacheAvailable()is false.hybridSearchCachedbypasses both result lookup and writes regardless of configuration oruseCache, 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;conceptfires 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 inintent-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-shapedsearchtowardquery; consumed bymaybePrintConceptNudgeinsrc/cli.tson BOTH the local-engine and thin-client result paths, stderr-only,--quiet-gated). Pinned bytest/query-intent-concept.test.ts+test/cli-concept-nudge.test.ts.