Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
58.6 KB
Raw Blame

Key files: Core Search (2/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/crag.ts + src/core/search/hybrid/rerank-gate.ts — the CRAG retrieval-confidence grade on the final list (gradeRetrievalConfidence, read by the query op's crag meta and escalation) and the W3 rerank gate's PRE-rerank grade. gradePreRerank is pure and reads the deduped candidates in fused order plus the identity lookups, never mutating them: strong is exactly one exact-lookup page, else exactly one full-query alias page, else a full-title identity at rank 1 (normalized title equals the normalized query; a phrase inside a longer title is not identity), else high_vector_match (rank-1 raw cosine ≥ search.evidence_cosine_floor) whose gap over the best cosine of a DIFFERENT page (image rows excluded; rank-1's own chunks never count) is at least δ (search.reranker.gate_min_gap, 0.05). More than one identity page, or a single-token alias hop that would move rank 1, is identity_ambiguous; multimodal queries and image rows are never strong; applyRerankGateTrust demotes a strong page below max(caller min_trust, unknown) to below_trust_floor. RERANK_GATE_SKIP_REASONS (only high_vector_match) decides would_skip; title, alias and exact-lookup strengths are skip_blocked: shadow_only_reason, and an active System One rerank slot is decide_rerank_slot. rerankAndPin starts readIdentityLookups (alias and exact lookups, any gate mode) alongside the reranker; sizeReturnPool applies them. prepareRerankGate (the stage, gate not off) grades with them, reads rank-1's page tier through stampPageTrust on a copy, and returns meta.rerank_gate (mode, eligible/ineligible_reason — reranker off, egress denied, no candidates — grade, reason, top_cosine, gap, candidates, would_skip, skip_blocked, provider_called). shadow results, provider payloads and lookup counts are identical to off. Pinned by test/search/rerank-gate-grade.test.ts, test/search/rerank-gate-hybrid.test.ts (both engines), test/search/rerank-gate-knobs.test.ts, test/search/rerank-gate-telemetry.test.ts (both engines).

  • src/core/search/ignored-privacy-labels.ts (GST-2462) — access / confidentiality values gbrain does not read. ignoredPrivacyLabels and its SQL twin ignoredPrivacyLabelSql are one rule (test/ignored-privacy-labels.test.ts): no visibility, no recognized PRIVACY_ALIASES value, no default-private rule. One privacy_label_ignored safety notice (counts by value, no content, git sentence only when sourceHasRepo) from put_page (withIgnoredPrivacyLabelNotice), import and sync (ignoredPrivacyLabelRunNotice); the doctor check is doctor/checks/privacy-label-ignored.ts. Reads nothing differently.

  • src/core/search/rerank.ts — the call-site abstraction. applyReranker(query, results, opts) slots between dedupResults() and enforceTokenBudget() in src/core/search/hybrid.ts. Slices opts.topNIn (default 30) by current RRF order, caps each document via capRerankDoc (RERANK_MAX_DOC_CHARS=6000 then a measured-ratio shrink to RERANK_MAX_DOC_TOKENS=1400 — a 2048-ubatch llama-server minus query/template headroom minus a Qwen-tokenizer margin; every cut through truncateUtf8 so no lone surrogate reaches the JSON body; docs under 1400 chars skip the tokenizer; applies to hosted providers too, so code/CJK chunks at the chunker ceiling lose part of their tail while prose is untouched), sends to gateway.rerank(), reorders by relevanceScore desc (within a run of exactly equal finite scores the fused input order decides, so provider tie order never leaks; rows never cross a different score), appends the un-reranked tail unchanged (recall protection). Fail-open on every RerankError.reason: any error logs via logRerankFailure and returns the input array unchanged — except the SKIP class no_key (RerankSkipReason), which returns the input immediately WITHOUT a per-query audit row (the gateway already wrote the one per-process-per-model row) and fires opts.onSkip(reason); every OTHER thrown failure (HTTP error, network, timeout, budget) is audited and fires opts.onFailure(reason) with RerankFailedReason timeout | budget | rate_limited | unreachable | auth | provider_error (gateway rate_limit → rate_limited, a transport failure with no HTTP response → unreachable, 401/403 → auth, 5xx and everything else → provider_error; Cat 40 R0, pinned on the real wire by test/rerank-failure-reason.serial.test.ts), which hybrid.ts stamps as {stage: 'rerank_failed', reason} (recall-affecting, like rerank_passthrough; the LongMemEval reranker gate and the R1 script count it as un-reranked); hybrid.ts passes an onSkip that stamps {stage: 'reranker_skipped', reason} into HybridSearchMeta.degraded (closed vocabulary in types.ts), which --explain renders as degraded: reranker_skipped (no_key) via formatDegradedSummary — the only place a silently skipped reranker is visible from the CLI. types.ts classifies the stage as ranking-only: RANKING_ONLY_DEGRADED_STAGES (= {reranker_skipped}) + affectsRecall(entry) — consumers that ask "was recall impaired?" filter through it (the CLI No results. line in cli.ts:describeEmptyRetrieval and the MCP empty-result block in dispatch.ts:buildEmptyRetrievalBlock keep saying "clean miss"; the degraded cache-TTL rule below uses the same predicate), while consumers that report what did not run (--explain, telemetry, eval rows) keep it; pinned by test/degraded-stages-recall.test.ts. hybridSearchCached excludes reranker_skipped from the short degraded-TTL rule (it is a config state, not a transient limp: a keyless balanced brain keeps the full cache.ttl_seconds, and the stored meta still carries the stamp). Stamps rerank_score onto reordered items so downstream telemetry sees the new ordering signal. topNOut: null is the explicit "don't truncate" signal — semantically distinct from undefined ("fall through to mode bundle"). Test seam: opts.rerankerFn stubs gateway.rerank without the network. Document cap pinned by test/rerank-doc-cap.test.ts.

  • src/core/search/retrieval-coverage.ts — query-scoped _meta.retrieval.coverage: relevant pending and held counts, capped, null on failure. A query word counts only as a whole token of a title, slug or path (~ regex bounded by non-alphanumerics, so 412 never matches t004120); an image page counts only when an image arm ran (HybridSearchMeta.image_arm) or it was returned; could_affect.pending_images counts the could-affect sealable/reimport images, which the notice words as waiting for an operator.

  • src/core/search/rrf-page-fusion.ts — accumulateRrf(lists), the one accumulation step behind rrfFusion / rrfFusionWeighted in hybrid.ts. Votes are keyed on the PAGE (source_id, slug): each list adds weight / (k + rank) to a page once, at its best rank, chunks stay distinct rows keyed (source_id, slug, chunk_id) with their own vote (own) and an OR-propagated keyword_hit (keyword_relaxed only if every holding list was relaxed), and each page's lead chunk (largest own, first-seen on ties — a vector arm in composeFusionLists order) scores the page's summed vote while its other chunks score their own vote. Pure. Pinned by test/search/rrf-page-grain.test.ts.

  • src/core/search/evidence-delivery.ts — the return_unit evidence assembler (default auto: conversation pages by type or chat//conversations/ slug come back whole under search.return_budget_conversation (24,000), every other hit is its unchanged chunk; effectivePlan skips the stage when an implied auto sees no conversation hit, so that path and chunk stay byte-identical). resolveEvidencePlan validates return_unit / return_window (invalid_params naming the allowed values and an example), reads search.return_unit / think.return_unit, search.return_window, search.return_budget_default (6,000), search.return_budget_conversation (24,000) and clamps remote budgets to search.return_budget_max_remote (32,000, reported). Snippet precedence: explicit snippet_chars > explicit return_unit > subagent default cap > config unit. deliverEvidence groups hits by page_id (one block per page at its best rank), makes ONE engine.getChunkWindows call (re-authorizes every page; unauthorized pages are dropped, never served from hit text), builds the page text from the stored body sanitized whole and passed through credentialSafeProjection before slicing (pageEvidenceText: compiled truth + serializer timeline sentinel + timeline; frontmatter excluded; private-key spans become newline-padded <REDACTED:private_key_pem> tokens, the same text the chunkers cut from), locates the hit chunks in it (locateChunks: exact, then whitespace-insensitive, since the chunker trims and folds whitespace), cuts window / section (ATX headings outside code fences, or conversation rounds detected structurally, never by page type) / page / auto (fenced-code hits are placed by their code minus the chunker's synthesized header), counts tokens as the sum of per-line cl100k counts, reserves each page's matching span before enriching by rank, caps blocks at 60,000 characters, redacts secrets before final accounting, and returns NEW rows with delivered plus a delivery meta. The plan records budgetExplicit (the caller passed the budget) and the resolved packing (search.auto_packing or the library override); capEngaged (unit auto, explicit budget, packing not off) routes allocation to allocateCapped: global rank one first (cut with EVIDENCE_CUT_MARKER when it alone exceeds the budget), the rank-order prefix of other non-conversation chunks that fits (rest budget_note), then conversations by cap_only (floors, then enrichment), breadth_capped (longest prefix whose title + floor + return_window target window fits; rest breadth_cap) or depth_first (each session grown in turn); nothing spills. capEvidenceToBudget recounts title + chunk_text at the final boundary (after redaction and capDeliveredSnippets, whose marker is paid from the row's own allocation) and rewrites budget_used. Without an explicit budget none of this runs and the bytes are the pre-cap path's. Fetch failure/timeout (5 s) falls back to the hit chunk only for live hits. assembleEvidenceForHits / op assemble_evidence deliver the exact evidence query returns for a frozen (source_id, slug, chunk_id) list, effective_date included (applyEffectiveDate, the live rows' normalizer); evidenceFingerprint hashes it (gbrain-evals E1/E3 parity). With search.evidence_date_header on (plan.dateHeader), each block (including auto passthrough chunks) starts with its one-line date header from evidence-date.ts, reserved in the block floor like the title, counted in delivered.tokens, with spans shifted past it and delivery.date_header: true; a failed date read renders unknown and adds date_header_unavailable. search.long_page_unit (F2, default off): withLongPagePolicy (called only by the search/query caller, so recall, think and assemble_evidence never carry it) sets plan.longPage (unit plus search.long_page_min_chars, default 20,000) under an implied auto with no explicit budget (snippet_chars does not turn it off; capDeliveredSnippets skips reason: long_page rows and cuts every other row); selectLongPages runs one character/byte-count preflight under the read scope (long = stored body at least minChars characters, confirmed on the rendered pageEvidenceText at delivery; at most LONG_PAGE_MAX_PAGES 5 and LONG_PAGE_MAX_INPUT_BYTES 1,000,000, whole pages only; LONG_PAGE_DEADLINE_MS 2,000 for preflight plus fetch) and returns exactly effectivePlan when no page is long; deliverEvidence fetches the selected pages in their own bounded getChunkWindows call, delivers them in the unit with reason: long_page, and returns any it cannot deliver (limits, deadline, fetch failure, over budget) as their ranked chunk with reason: long_page_chunk and a long_page_* fallback. Normative spec: docs/evidence-delivery.md. Tests: test/evidence-delivery.test.ts, test/evidence-delivery-golden.test.ts, test/e2e/evidence-delivery-leak.test.ts, test/e2e/evidence-delivery-parity.test.ts; bench scripts/bench-evidence-delivery.ts. Large pages: a page (or auto→page) unit over 256 KB is delivered as a window with fallback_reason: page_over_inline_bytes; above 1 MiB, hits are located only by stored spans (locateChunksByStoredSpans) and the anchor fallback never whitespace-folds the whole text. A segmented page (Wave B PR 2) is planned by planSegmentedBlock from the windows segmented-evidence.ts reads around its hits, one run per window (emission marks the gap between runs, a section never crosses one); no page text, whole-page projection or locateChunks runs for it, and a failed segment read falls back to the hit chunk (segment_read_failed, live hits only).

  • src/core/search/page-rank-cut.ts — W5 page-unit ranking cut (on by default; search.page_rank_cut off disables it): with return_unit: page and a caller budget, resolveEvidencePlan stores rankCut ({mode, factor, caller_budget}, factor from search.page_rank_cut_factor, default 1.5) on the plan; search/query/recall pass it as HybridSearchOpts.pageRankCut, and liftModeCut drops the mode's chunk-token tokenBudget in both the inner request and the cache resolver (tb= is in the knobs hash). Delivery applies the cut: cutWholePages (this file, pure) keeps rank-order pages while their whole delivered cost (evidence-delivery.ts wholeCost: floor plus every enrichment piece within the block char cap) fits factor × the shared budget, keeps the crossing page only when its floor fits what is left, and drops the rest as rank_cut. delivery.page_rank_cut reports mode, factor, caller budget, target, applied cost, candidates and kept. Tests: test/search/page-rank-cut.test.ts (both engines).

  • Evidence date headers (search/evidence-date.ts) and the tail trim (search/evidence-tail-trim.ts): Core Search (evidence blocks).

  • src/core/search/entity-anchor.ts — entity-anchored retrieval: entityAnchoredPages (the entity page plus up to 10 pages that link to it by a ranking link type or name it as a word, newest by COALESCE(effective_date, updated_at); question/synthesis/pinned-question pages excluded) and prefixAnchoredPages, shared by pinned-question refresh (questions/refresh.ts anchoredSlugs) and the query/search ops; asksForCurrentState (deterministic cue regex), namedEntity (exactly one isFactEntityPage page whose title isTitleMentionedInQuery matches, the title match before the read-policy filter; a title inside a longer matched title is the same mention); applyEntityAnchoring (anchored rows first, at most half the row count, organic rows of the same page moved up, missing pages read through getChunkWindows under the caller's scope, rows stamped entity_anchored, token budget re-applied, fail-open); entityAnchoringEnabled (search.entity_anchoring, default off). Tests: test/search-entity-anchor.test.ts. Gates: docs/eval/decisions/entity-anchoring-query/.

  • The facts arm, temporal fact reserve, facts block and fact source pages (search/facts-arm.ts): Core Search (evidence blocks).

  • src/core/search/fact-relevance.ts — question relevance for saved facts, shared by recall's question (facts/question-recall.ts), the temporal fact reserve and (pool only) the facts arm. collectFactCandidates: one bounded pool under recall's read policy (source scope, active and not superseded, audit rows excluded, quarantine and rederive hiding through projectionEligibleSql, the trust floor, world-only facts when the scope says worldOnly (worldOnlyFacts), privateProvenanceFilterFragment when excludePrivate) plus recall's filters inside every arm before its LIMIT ((source_id, entity_slug) pairs, source_session, event-time since, escaped ILIKE grep); arms, run concurrently and merged in a fixed order, are keyword FTS (factsFtsDocument, served by idx_facts_fts), cosine (cast to the facts column type, filtered on model only so the HNSW index serves it, a stale hash or other dimensions yielding no similarity; ef_search sized to the depth and pgvector's iterative scan when hnswIterativeScan is set) and the named entity page's facts in its own source (with history, GBRA-574, that arm also takes the entity's ended facts, ENDED_FACT_SQL: superseded or past valid_until, never withdrawn, forgotten or from a purged page); depths are bound parameters; cosineForAll scores every candidate's cosine whichever arm found it; distinctiveTerms (recall's question, GST-1304) searches a question over MAX_QUERY_TERMS (12) content terms on its last 24 and returns in terms the 12 of those the fewest candidates hold (heldTerms; later word first on a tie) for scoreFactCandidates, so a provider preamble no fact holds stops filling the share's denominator. A missing embedding column or other dimensions skips the cosine arm; any other DB error throws. scoreFactCandidates: cosine + term share + 0.1 when dated (terms match on their stems under the brain's full-text config, one to_tsvector read per pool, whole words when it fails; a stem-only match adds 0.9 of an exact one to the score but counts fully in the share; ISO dates, years and auxiliaries count on neither side), the share's denominator growing past TERM_STUFFING_RATIO times the question's terms for a long fact; order score, newest valid_from, id. admitted: the reserve rule (cosine >= 0.5 or share >= 0.34) or the facts_arm rule (cosine >= 0.6, half the terms, or the named entity). countUncomparableFacts counts the pool's facts the cosine arm cannot compare, per source: candidates from idx_facts_unembedded and idx_facts_embedding_model first, the read policy on those rows only. The keyword arm and the count run under customPlan (plan_cache_mode = force_custom_plan in a transaction): a cached generic plan cannot see the source arrays and nests the policy anti-joins over every match. readSlotRows (GBRA-574 B2) and laterRetractions (B5): a slot's unwithdrawn conversation rows, past valid_until included, and a fact's later retractions, under the same policy, for the facts block. p95 at 100k facts: Postgres 51 ms local / 65 ms remote, PGLite 152 / 139 ms. Tests: test/fact-relevance.test.ts, test/recall-question.test.ts.

  • src/core/search/query-arms.ts — applyQueryArms: the query op's post-retrieval arms in order (entity anchoring, fact source pages, then the facts arm), each behind its own key (the facts arm default on, the rest off); a query whose caller passed token_budget takes the facts block (search.query_facts_block, default on; at most limit rows, scored at the top page's score; #8411) or, with a temporal cue, the temporal fact reserve (search.temporal_fact_reserve) instead of the facts arm; with all off it returns the rows untouched.

  • src/core/search/image-vector-presence.ts — brainHasImageVectors (one EXISTS embedding_image IS NOT NULL probe per engine, cached 60 s, fail-open to true). hybrid/arms.ts uses it so an inferred image/both modality on a brain with no image embeddings stays text: no multimodal embed, keyword arm kept, no vector_arm_failed; the opt-in LLM modality tie-break still runs, and an image or both answer is demoted to text. An explicit crossModal is honored. Tests: test/search-image-arm-text-only.test.ts, test/cross-modal-hybrid-integration.serial.test.ts.

  • src/core/search/chunk-windows.ts — request/response shapes and the row mapper for BrainEngine.getChunkWindows. The SQL lives once in src/core/engine-sql/chunks.ts (getChunkWindows): page rows (authorization + seal + max chunk index + raw body columns; a segmented page's row says segmented and carries no body) and chunk rows (inside the requested chunk_index ranges, text modality, requested chunk sources, row cap) come back in one UNION so the row cap never hides a page's authorization; the predicate is the search legs' (source scope, deleted, current text projection, archived source, quarantine, private pages, safe chunks). Postgres runs it inside the scoped read transaction. Chunk rows carry projected_byte_start/end when recorded, and on a segmented page their occurrence_id (the span is relative to that occurrence's projection), the references search/segmented-evidence.ts reads windows around.

  • src/core/search/segmented-evidence.ts — Wave B PR 2 (spec 7.4): the windows an evidence block of a segmented page is cut from. readSegmentedWindows opens the body (page-body/read-range.ts), places each hit from its chunk's occurrence and segment-relative projected span through the projected layout (a span is trusted only while it still holds the chunk's text; a hit whose chunk has no span is placed by a unique exact match inside its own segment, else positionally), and reads with readBodyRange (projected space, the remote read projection with the per-segment withdrawal and fence overlays) only the hits' neighbor chunks (window), the hit's segment (section) or the whole text while within the inline read size (page), widened to whole lines and merged where they meet. Returns the runs in document order with chunk spans in UTF-16; evidence-delivery.ts planSegmentedBlock joins them. Never builds a page text or calls locateChunks. Tests: test/large-pages/segmented-evidence.test.ts (privacy, projection parity, separate windows), test/large-pages/segmented-evidence-read-cost.test.ts (40 MiB page: at most two segment texts loaded per hit).

  • src/core/search/explain-target.ts — explain_target diagnosis. A TargetTrace (HybridSearchOpts.explainTarget) records the target page's presence and 1-based rank at each pipeline stage: every arm instance (arm:<label>, plus arm:keyword_raw/arm:title_raw before relaxed-row demotion), fused, deduped, reranked, return_pool, limit_slice, token_budget. diagnoseTrace returns one state (retrieved / dropped / reinjected / not_retrieved / not_recorded) naming the first stage that lost the page; boost stages are never reported as drops (they only re-order). probeTarget + diagnoseProbe run one read under the caller's read policy and separate not-indexed / stale projection / unsealed safe chunks / ambiguous slug; an unreadable page and an absent page return the same target_not_found_or_not_visible. Every diagnosis carries an Action-contract fix the search/query ops emit as a notice. Pinned by test/search/explain.test.ts.

  • src/core/search/output-redaction.ts — copies retrieval results and metadata before output sanitation, sharing the canonical secret-scan.ts plan and echo dictionary. Keyword, hybrid, image, exact and CRAG paths sanitize after internal grading/capture and before snippet truncation; CLI search/query JSON, explain and human rendering repeat the defense-in-depth pass. Every field is planned with highEntropy: true, so KEY=value assignments redact alongside the named shapes. Identity fields (id, slug, source_id, page_id, chunk_id, message_id, thread_id, graph_session_prefix, relational seed/path, superseded_by, fact_id, entity_slug, and the link and graph endpoints from_slug, to_slug, origin_slug and their *_source_id) remain byte-identical: never put secrets in IDs. By default each field is capped at 64 Ki UTF-16 characters, the response at 1 Mi characters/8192 text fields, and nesting at 24 levels; oversized/unscannable text becomes <REDACTED:output_limit>. RetrievalRedactionOpts.uncapped scans every field whole (no output_limit replacement; one echo dictionary, every field planned before any write; the depth cap stays) and verbatim copies the named keys of each top-level result unscanned. withOutputRedaction(op) is the registration-time wrapper behind Operation.outputRedaction (src/core/ops/contract.ts): operations.ts wraps every 'retrieval' op's handler once, so the CLI, stdio and HTTP MCP, subagent tools and gbrain call all pass the whole response (early returns included) through the uncapped redactor, linear in output size; { retrieval: { localVerbatim } } leaves the named keys raw only when ctx.remote === false. The memory verbs: recall, context_pack and delta redact their presentation sets with one echo dictionary before packing, so budgets, budget_used and the delta cursor follow the delivered text, and their rendered text is never replaced by output_limit; facts (fact, context, source) are localVerbatim, so a remembered credential is readable raw only by the trusted local CLI on the brain host (stdio MCP and thin clients are remote). Handlers that clip or summarize stored text (transcript summaries, entity-card and compiled-context excerpts) redact the whole field before clipping. THREAT MODEL: this defends against accidental exposure of stored credentials into agent context and transcripts through retrieval ops. It does not cover the raw-read exemptions (get_page, fetch, get_chunks, get_raw_data, get_versions, the skill catalog, admin job ops), stored content (unchanged), or configured providers (embeddings at ingest, the hosted reranker, synthesis/think generation still receive unredacted text, except private keys, which the credential-safe projection keeps out of chunks). Unknown formats and short fragments can escape detection. This is output hygiene, not authorization or provider/eval no-egress. Tests: test/search/output-redaction.serial.test.ts, test/search/output-redaction.test.ts, test/retrieval-op-redaction.test.ts (every 'retrieval' and 'no_stored_text' op run through MCP dispatch with remote = true against a planted secret, plus the registration wrapper), test/transcripts-redaction.test.ts.

  • src/core/search/return-policy.ts (default OFF) — intent-aware adaptive return-sizing. Pure, dependency-light module that trims the final ranked candidate set to an intent-driven cap instead of returning the full top-K. entity intent gets a tight cap; temporal/event/general get a recall-preserving cap (concept is coerced to general by hybrid.ts before the call — concept queries want breadth). A minKeep failsafe (≥1) guarantees a human never gets a silent blank when candidates exist. WHY a cap, not a score-cliff detector: PrecisionMemBench instrumentation (gbrain-evals) measured the rank1→rank2 RRF gap is ~identical whether rank-1 is correct (0.602) or wrong (0.569) — mechanical decay, not a separatrix; rank-1 is right in 94% of single-answer cases, so "return a tight set" is the whole win and cliff-cutting just adds noise. Exports AdaptiveReturnConfig, DEFAULT_ADAPTIVE_RETURN (frozen: enabled=false, entityMax=2, otherMax=6, minKeep=1), AdaptiveReturnDecision ({applied, intent, cap, kept, total}), AdaptiveReturnInput (boolean | Partial<AdaptiveReturnConfig> | undefined), adaptiveReturnFromConfig(cfg), resolveAdaptiveReturn(perCall, fromConfig) (defaults → config → per-call merge), adaptiveReturnEnabled(...) (cache-skip gate check), applyAdaptiveReturn(results, intent, cfg) (the trim). Config knobs (DB or file plane): search.adaptive_return (master switch), search.adaptive_return_entity_max, search.adaptive_return_other_max, search.adaptive_return_min_keep (each clamped ≥1). Wired into hybridSearch AFTER applyReranker, BEFORE the limit slice, and ONLY on the first page (offset===0) — paginating a confidence-gated set is incoherent, so paginated calls fall through to the fixed limit. Stamps the decision onto HybridSearchMeta.adaptive_return for gbrain search --explain. hybridSearchCached SKIPS the cache when the gate is on (a trimmed set must not be served to a gate-off lookup and vice versa). SearchOpts.adaptiveReturn + HybridSearchMeta.adaptive_return declared in src/core/types.ts. Agent-facing: the query op (src/core/operations.ts) exposes an adaptive_return boolean param whose description instructs the agent WHEN to set it (single-answer → on; breadth/exploration → off; pass limit:1 for a hard single-answer cap), threaded into hybridSearchCached — end users never touch the config knob; their agent decides per query (same pattern as salience/recency). Pinned by test/search/return-policy.test.ts (mechanism) + test/search/query-op-adaptive-return.test.ts (agent surface: param exists + description teaches both directions + the never-empty contract).

  • src/core/search/safe-chunks.ts — shared current-revision and remote safe-chunk predicates. currentTextProjectionFilter emits (text_projection_revision = knowledge_revision) IS TRUE, preserving NULL exclusion while allowing expression statistics to guide the planner. Visibility and revision predicates stay inside candidate selection. Body/chunk changes invalidate the safe index until a guarded rebuild. belowSafeChunkFence is the page-level predicate shared by the importers' unchanged-content re-seal and the drain. chunkWriteInvalidations(pageId, chunks) yields one guarded chunker_version = -1 invalidation per row batch of a chunk replacement (batch-rows.ts jsonRowBatches); the caller stops at the first that returns a row. Wave B: chunkVisibleFilter(p, c) (served projection (servedTextProjectionFilter) plus a row at or below the page's body generation; sealed pages hold no retired rows, and no subplan keeps vector search on HNSW) is the search predicate; chunkGenerationFilter(p, c) serves generation readers (an inline row of a non-segmented page, or a row whose occurrence has a live manifest row, hiding rows a deferred retirement or demotion left; p needs body_storage), chunkGenerationProbe(c) the same without a joined page, and chunkManifestJoin / chunkDocumentOrder give segmented rows document order (manifest byte_start, local_ordinal); scripts/check-chunk-visibility.ts requires one of them or a reason on every content_chunks reader (rules in its header).

  • src/core/search/source-boost.ts — Source-type boost map keyed by slug prefix. DEFAULT_SOURCE_BOOSTS (originals/ 1.5, concepts/ 1.3, writing/ 1.4, people/companies/deals/ 1.2, daily/ 0.8, media/x/ 0.7, /chat/ 0.5, archive/ 0.5, extracts/ 0.3) and DEFAULT_HARD_EXCLUDES (test/, attachments/, .raw/). archive/ is DEMOTED (findable, ranked below curated), not hard-excluded — archive holds high-signal history users expect to retrieve; the demote is a prior at the SQL/fusion layer and the cross-encoder reranker can still promote a strongly-matching archive page. parseSourceBoostEnv/parseHardExcludesEnv parse comma-separated prefix:factor pairs from GBRAIN_SOURCE_BOOST/GBRAIN_SEARCH_EXCLUDE. resolveBoostMap(env, config) layers defaults (dropped by a none entry), the brain's search.source_boosts config and the env override; hybridSearch resolves it once from the mode config snapshot and passes it to the engines as SearchOpts.source_boosts (engines fall back to defaults + env when absent; the keyword-only search op branch reads the key itself). resolveHardExcludes merges defaults + env + caller SearchOpts.exclude_slug_prefixes/include_slug_prefixes. The surviving exclude policy is auditable via the hidden_by_search_policy doctor check (src/commands/doctor/checks/calibration.ts, local + remote paths) which counts chunked pages withheld per active exclude prefix, reusing resolveHardExcludes + buildVisibilityClause + the exported escapeLikePattern.

  • src/core/link-ranking-policy.ts — the link-type ranking participation policy: NON_RANKING_LINK_TYPES (amends), linkTypeRanks, and rankingLinkSql(alias), the inlined predicate every link-counting ranking reader applies (read-enrichment backlinks, adjacency, fanout, chain hops and degree; enrich inbound order; entity-resolution connection count; generated-page demotion; entity anchoring). Reference reads (graph ops, cards, backlink_count, referrers) keep these edges. Tests: test/amends-link.test.ts (+ Postgres twin), one invariance row per consumer.

  • src/core/search/provenance-demotion.ts — applyGeneratedDemotion(engine, list, query, scope), called first in applyIdentityBoosts (hybrid/request.ts) on the fused path and both keyword-only paths, so it runs before reranking and before the pool is cut. Rows whose page carries a gbrain-owned marker (frontmatter dream_generated: true, type extract_receipt) get provenance: 'generated'; such a row is multiplied by GENERATED_FACTOR (0.5, stamped generated_demotion) only when the query names an entity (resolveQueryEntity), the page links to it by a ranking link type, and a non-generated row in the pool is the entity page or links to it. recordsCorrection (frontmatter supersedes/corrects, a facts-fence row with valid_until) exempts corrections. search.demote_generated=false keeps scores. Its page read (readGeneratedPages) starts before runPostFusionStages. Tests: test/search-provenance-demotion.test.ts.

  • src/core/search/frontmatter-where.ts + src/core/ops/where-param.ts — the where frontmatter equality filter on search, query, list_pages (#7159; CLI --where key=value). Bounded keys and values, else invalid_params; each value is a bound p.frontmatter @> $n::text::jsonb test (GIN-served), pushed into every SQL leg; a filtered call skips the hybrid cache and keepFrontmatterMatches re-checks the other arms. Tests: test/search-frontmatter-where.test.ts, its e2e parity file.

  • src/core/search/filter-hint.ts — one search_filter_hint info notice per session when a first-page search/query names a type or time it did not filter on, or one type fills its top rows. Never changes results.

  • src/core/search/search-cost.ts — _meta.retrieval.cost (#7158): withSearchCost meters every invokeAI in the request via withAIInvocationMeter (AsyncLocalStorage); refused calls are not counted; gateway.expand gets an expansion line. Test: test/search-cost.serial.test.ts.

  • src/core/search/stage-timings.ts — per-request search stage timings. The search/query handlers create one SearchTimings and thread it into every hybrid call of the request (HybridSearchOpts._timings, HybridRequest.timer; absent = UNTIMED, a pass-through). stage(name, work) books critical-path blocked wall-clock time: one current stage at a time, a nested stage takes the clock and hands it back, so a fan-out or escalation hybrid call is booked once under its own stages, and retries accumulate. overlap(label, promise) times concurrent work (keyword/title arms, meta reads) into overlapped_ms, outside any stage. part() books a stage's serial steps into parts_ms. branch() returns a timer for stages run alongside the critical path (hybrid's vector side: modality, expansion, embed, vector arms); until join(branch, promise) its stage time goes to overlapped_ms under the stage name, and from the join the wait is booked to the branch's current stage (its key shows in stages_ms even at 0). snapshot() reads total_ms from its own monotonic start, apportions integer stages_ms + other_ms summing to it exactly (other_ms >= 0); searchOutput takes it once the returned rows exist and emits it as _meta.retrieval.timings (never in content blocks); formatTimingsSummary is the --explain line. Stages: setup, lexical, relational, expansion, embed, vector, fuse, post_fusion, rerank, alias_fanout, anchoring, facts_arm, response. The gate (per bench query 0 <= total - sum(stages) <= 10%) is the timings phase of scripts/bench-refactor-wave-1.ts. Pinned by test/search/stage-timings{,-ops}.test.ts.

  • src/core/search/sql-ranking.ts — Pure SQL string builders. buildSourceFactorCase(slugColumn, boostMap, detail) emits a CASE with longest-prefix-match wins (returns literal '1.0' when detail === 'high' for temporal-bypass parity with COMPILED_TRUTH_BOOST). buildHardExcludeClause(slugColumn, prefixes) emits NOT (col LIKE 'p1%' OR col LIKE 'p2%') — OR-chain wrapped in NOT, NOT NOT LIKE ALL/ANY (those quantifiers don't express set-exclusion). LIKE meta-character escape covers all three of %, _, AND \ (backslash is Postgres LIKE's default escape char). Single-quote doubling on SQL string literals so injection-style inputs are inert text. buildBestPerPagePoolCte(...) is the shared per-page max-pool CTE both engines' searchVector inject — instead of returning the single best chunk per page from an inner ORDER BY embedding <=> vec LIMIT N (which lets a page lose to a neighbor on ONE weak chunk while its strong chunk sits just below the inner cut), the CTE pools the BEST chunk score per (source_id, slug) composite key so a page surfaces on its strongest evidence; composite key (not bare slug) keeps multi-source brains correct; single source of truth so the two engines can't drift. keywordPhraseFactorSql: opt-in 2x on a phrase match (#7175).

  • src/core/search/keyword-chunk-match.ts — buildKeywordChunkMatch(ftsLang, excludePrivate): the chunk side of PostgresEngine.searchKeyword's statement (cc source, full-text match, text modality). For excludePrivate callers it plans the match alone in an OFFSET 0 subquery; joined, the visibility subplans' cost let a seq scan detoasting every search_vector win (1.1 → 0.2 s, common term, 250k chunks). Local callers keep the unfenced, parallel-capable join. KEYWORD_RANKED_ROWS_CTE: ranking carries only ids, score and bounded_rows; display columns come from one LIMIT 1 key probe per ranked chunk. Output equals the wide statement's; under the 50k bound (sample in plan order), its unspilled output. Not on PGLite. Pinned by test/search/keyword-arm-ranking.test.ts, test/e2e/keyword-arm-ranking-postgres.test.ts.

  • src/core/search/title-match.ts — pure, zero-I/O title-phrase matcher shared by the production title boost AND NamedThingBench (no drift). isTitlePhraseMatch(query, title) returns true when the normalized query is a contiguous token run inside the title with >= MIN_CONTENT_TOKENS=2 non-stopword tokens, OR an exact full-title match (covers deliberate 1-word chosen names like "Helios"). Token-boundary matching (never raw substring, so "art" doesn't match "Bartholomew"); small conservative English stopword set excluded from the content-token floor (guards against promoting generic pages on stopword-y queries); NFKC normalize so CJK / width variants converge. contentTokenCount(s) counts non-stopword tokens (the qualified alias windows and the qualified title boost read it). isTitleMentionedInQuery(query, title) is the reverse direction the intent exact-match boost and the opt-in qualified title boost use: the title appears as a contiguous token run INSIDE the query ("who is Alice Example" → "Alice Example"), guarded to titles with ≥2 content tokens or one content token of ≥4 characters. titleNameVariants(query) (#7471) is the query with its given name swapped for each other form in its nickname group (givenNameVariants in entities/name-variants.ts), none for websearch-operator queries; the title arm ORs them into its query and the T2 boost accepts a variant title-phrase match. Exports tokenizeTitle + __test__ internals.

  • src/core/search/tune-recommendations.ts — tuning recommendations never propose enabling or tuning unavailable semantic result caching. Mode-reduction suggestions describe payload size, not expansion savings: shipped commands pin expansion independently of the bundle.

  • src/core/search/vector-pool.ts + vector-settings.ts — shared bounded candidate escalation and transaction-local scan settings. SQL output limits are independent of ef_search; scoped witnesses distinguish genuine exhaustion from ANN shortfall. Postgres has one server-cancelled exact fallback; PGLite reports incompleteness. Pooled attempts scan with hnsw.max_scan_tuples = POOL_MAX_SCAN_TUPLES (20,000), so a filtered attempt fills its window before acceptance; the walk and scope scan keep a window-sized budget. Settings are restored even inside caller-owned transactions. A batch carries the raw candidatePool (a short window means the index ran dry) and an optional eligiblePool (fresh candidates); hasMore receives the eligible count, else the raw one. vectorScanSettings(...) computes one attempt's settings (Postgres sets them in one settings statement, postgres-engine/search-settings.ts); withVectorSettings(...) (PGLite, fact-relevance) reads, sets and restores them, hnsw.iterative_scan in the caller's mode (default relaxed_order); walkOverfetch adds INDEX_WALK_SETTINGS and sizes ef_search for the over-fetched window; joined (a pool attempt of a statement with an index walk) adds JOINED_STATEMENT_SETTINGS (enable_material = off): pages are probed per HNSW candidate, never materialized and rescanned. Rows are judged under exact evaluation: a small scope may get an exact plan. searchIndexWalk(stmt, limit, run) runs the statement's index walk before the pool and returns its rows only when its window is full and they fill the limit. Too few pages widen a full window x4 (INDEX_WALK_ESCALATIONS); else the pool runs.

  • src/core/search/vector-statement.ts — buildVectorSearchStatement({ dialect, embedding, limit, offset, opts }) builds the vector-search SQL once for both engines, doctor vector_plan and the plan-proof E2E: { sql, exactSql, hasMoreSql, params, innerLimitIdx, innerLimit, indexed, relaxed, indexWalkSql?, indexWalkOverfetch, scopeScanSql? }. On an HNSW-indexed embedding column (relaxed variant) the candidate CTE carries only the model check; content freshness (embedded_text_hash = md5(chunk_text) or NULL) is projected as hash_current and filtered in scored, because Postgres cannot estimate that expression and drops the index when it sits in the CTE (#5824). Non-indexed columns, the legacy guard, exactSql and hasMoreSql keep the full guard inside. The pool row reports candidate_pool (raw) and eligible_pool (fresh). Since/until bounds are spelled per column (effective_date, then updated_at, then created_at) so each arm has column statistics. indexWalkSql (relaxed variant without a type or date filter, same parameters) is the statement both engines run first: ann orders content_chunks alone with the chunk-level filters over twice the window, then pages and sources are joined by key and every page filter, visibility and the private-page rule apply to those rows, keeping the nearest innerLimit. Run with enable_sort = off (INDEX_WALK_SETTINGS) the HNSW scan is its only ordered path; the joined statement's plan sat on a cost knife edge (TOASTed vectors cost a sequential scan too little, the HNSW estimate grows with ef_search, the private-page rule's subplans priced every page lookup high) and flipped to a full scan and sort at a 50-row limit or on any remote read. A full walk window selects the same rows as the joined statement (test/search/vector-index-walk.test.ts); a short one falls back to it. Source scopes: each engine's vectorScopeLoader reads PAGE_SOURCE_STATS_SQL (pages.source_id planner statistics plus content_chunks reltuples) at most once a minute, only for source-scoped searches, and passes scope (share, and chunks). For a scope under SCOPE_SCAN_MAX_SHARE, chunks comes from SCOPE_CHUNKS_SQL (at most once a minute per scope): the scope's live pages times the chunks per page of a hashint4 stride sample of about 400 of them (every page in a smaller scope), because the page share undercounts sources of long pages; otherwise, and when the count fails, it is the share times chunk reltuples. The walk over-fetches indexWalkOverfetch(share) = ceil(2 / share) rows per window slot (2 unscoped or for a whole-brain scope, so that statement is byte-identical), and a share below INDEX_WALK_MIN_SCOPE_SHARE (0.04) skips it. scopeScanSql (relaxed variant, same parameters) serves a scope under SCOPE_SCAN_MAX_SHARE (0.3) of pages with at most SCOPE_SCAN_MAX_CHUNKS (120k) counted chunks: an exact distance scan over the scope's chunks, page filters and visibility applied once per page inside cc.page_id = ANY(ARRAY(...)) so chunks are always reached through idx_chunks_page (an inline join flipped to a sequential scan with the private-page rule), ordering only chunk ids with (distance) + 0 to keep the index out, then the window joins back for its columns. Up to SCOPE_SCAN_FIRST_MAX_CHUNKS (25k) it replaces the walk; above that the walk runs first and the scan answers when the walk comes back short (a scope clustered away from the query). It returns the joined statement's rows (test/search/vector-index-walk.test.ts); recall across share buckets on 1024-dim vectors is pinned by test/e2e/vector-scope-recall-postgres.test.ts. Missing statistics leave only the unscoped walk and the joined statement. PGLite adds the timeline stale column; everything else is byte-identical across dialects. Also exports the extension-version probe and the transaction-local statement_timeout SQL the Postgres engine runs. Pinned by test/search/vector-statement.test.ts, test/search/vector-freshness.test.ts and test/e2e/vector-plan-real-column-postgres.test.ts.

  • src/core/search/vector-legacy-guard.ts — one-release rollback for the #5824 statement change. readVectorLegacyGuard(cfg, env) reports the setting (GBRAIN_VECTOR_LEGACY_GUARD wins over search.vector_legacy_guard); resolveVectorLegacyGuard(engine, cfg) latches it once per engine (engineKey) for hybrid/request.ts, which passes SearchOpts.vectorLegacyGuard to the engines (they never read config), and prints [gbrain] vector legacy guard active to stderr once per process when on. A changed setting takes effect when the owning service restarts.

  • src/core/search/evidence-packing.ts — the explicit-budget packing surface of evidence delivery: AUTO_PACKINGS (off, cap_only default, breadth_capped, depth_first) for search.auto_packing, MIN_EXPLICIT_AUTO_BUDGET (32; an explicit auto budget below it, or non-finite, is refused with invalid_params naming it), parseAutoPacking (the library override, unknown values refused), configPacking (unknown stored values read as the default) and autoPackingValueProblem (the config set refusal wired through search/config-values.ts); queryBudgetUsesAuto (search.query_budget_unit, GBRA-205: auto makes query's token_budget the hard cap, default chunk). Tests: test/evidence-delivery.test.ts, test/search-8k-conversion.test.ts.

  • src/core/search/hnsw-iterative-scan.ts — the pgvector hnsw.iterative_scan mode for filtered vector search (#6132 idea): relaxed_order by default, strict_order or off through GBRAIN_HNSW_ITERATIVE_SCAN (wins) or search.hnsw_iterative_scan (file > DB via loadConfigWithEngine). resolveHnswIterativeScan(engine, cfg) latches once per engine (hybrid request.ts passes it as SearchOpts.hnswIterativeScan; engines hand it to withVectorSettings), logging once per override mode per process when an override is active. hnswIterativeScanValueProblem backs the config set refusal through search/config-values.ts (searchConfigValueRefusal: enum/range rules for search.* keys, exit 2 invalid_params, nothing written). Pinned by test/search/hnsw-iterative-scan.test.ts and the Postgres recall fixture test/e2e/hnsw-iterative-scan-recall-postgres.test.ts; bench scripts/bench/hnsw-iterative-scan.ts (its --corpus latent mode, with scripts/bench/hnsw-latent-corpus.ts and the VM bootstrap scripts/bench/hnsw-scale-vm-setup.sh, is the E5.4 scale and index-build bench; results in docs/eval/hnsw-scale-bench.md).

  • src/core/search/internal-breadth.ts — INTERNAL_BREADTH_SEARCH_OPTS (autocut: false, adaptiveReturn: false), the one option object internal callers spread into hybridSearch when they need the full ranked set rather than a reader-trimmed one (#5890): think gather (both legs), brainstorm close-set, grade-takes evidence, whoknows and enrich. Pinned by test/internal-breadth-callers.serial.test.ts; eval-contradictions/runner.ts still inherits both trims.

  • src/core/temporal-grammar.ts + src/core/search/time-range.ts + src/core/event-dates.ts + src/core/search/hybrid/time-scope.ts — deterministic time expressions (no LLM). findTimeMentions(text, refDay, direction) resolves explicit cues only (ISO and written dates, in/during <Month>, capitalized bare months, Qn YYYY, in YYYY, yesterday/today/tomorrow, last/this/next week|weekend|month|year, rolling "past month", seasons, last/this , N units ago, in N units) to inclusive day ranges; quoted spans, plural weekdays and modal "may" never resolve; overlapping matches keep the longest. parseQueryTimeRange(query, refDay) returns one range or abstains with no_cue, duration_question ("how long", "how many days ago/passed/before…") or multi_role (two times not joined by and/or/to/through). extractEventDates(text, observationDay) returns the observation day plus mentioned dates, resolving relative phrases only against a known observation day and skipping code fences, inline code and URLs. applyTimeScope(results, range, datesOf, {mode, k, slackDays=2}) is a permutation: reserved keeps the top ⌈k/2⌉ in place and fills the rest of k with in-range results; partition moves every in-range result first. These are used by the eval-only --time-scope arm; no production search path calls them yet. Tests: test/time-range-parse.test.ts (published LongMemEval time-range examples as goldens), test/time-scope-stage.test.ts.

  • src/core/fact-keys.ts — fact keys merged into a chunk's embedding input. assignFactKeys(items, chunks, 'chunk'|'page') (chunk = each fact on the chunk sharing the most content words, page = all facts on every chunk; code/image chunks never keyed; 800-char cap; <context> tags stripped) and factKeyedEmbeddingInput(chunkText, title, keys) (<context>{title}\nFacts: {keys}\n</context>\n{chunk}; null keys reproduce today's title-wrapped or raw input byte-for-byte). chunk_text is never changed. Used by the eval-only --fact-keys arm. Test: test/fact-keys.test.ts.

  • src/core/search/feedback-boost.ts — the use-attributed feedback ranking stage. applyFeedbackStage(engine, results, { reranked }) reads each result page's learned weight (retrieval_weights, half its learned deviation when the page changed since) and current content_hash in one query by page id, stamps content_hash (answer recording uses it) and, when feedback.influence λ > 0, multiplies the ordering score by 1 + λ·2·(w − 0.5) (bounded [1 − λ, 1 + λ], stamped feedback_boost). The ordering score is rerank_score when the reranker reordered the list (unscored tail rows stay after the head) and the fused score otherwise; raw score/rerank_score are never modified, so autocut and evidence read the same values. Neutral weights return the list untouched. Called once from hybrid/rank.ts rerankAndPin (between the reranker and the relational re-pin) and at the end of both keyword-only paths in hybrid/keyword-only.ts; paths that bypass hybridSearch get no feedback. Fail-open (errors counted, shown by gbrain feedback status). Pinned by test/feedback-boost.test.ts and test/e2e/feedback-parity.test.ts.

  • src/core/search/relational-chain.ts — multi-hop chain runner over relationalChainHop: LINK_SIGNATURES / CHAIN_LINK_TYPES / linkFamily, path records with path-local cycle prevention (a path may end on its anchor), frontier 50 / paths-per-node 10, hub-dampened path weights (CHAIN_HUB_HALF_DEGREE), uncertain edges at half weight, (score, source_id, slug) byte-wise order, statuses fired / anchor_not_found / no_edges / empty_hop / truncated with cap_hit; plus resolveChainAnchors, validateChainHops (agent hops) and presentEdgeContext (remote: sanitized, ≤160 chars). Pinned by test/relational-chain.test.ts.

  • src/core/search/relational-plan.ts — parseRelationalPlan: deterministic planner for questions chaining 2-3 typed relationships (bounded lexer, fixed lexicon of verb / passive / agent-noun / outgoing-noun forms, one anchor span, anchor-outward hop order with the main-clause verb outermost, type coherence, head-noun constraint). Returns plan / not_applicable (fewer than two relationships) / unsupported with a reason (coordination, negation, time, counting, quotes, multiple entities, incoherent types). isRelationalQuery(query, plannerOn) is the relational test for ranking decisions; planner off it equals parseRelationalQuery. Pinned by test/relational-plan.test.ts.

  • src/core/search/hub-dampening.ts — hubWeight(degree, H) = 1 / (1 + ((max(n,1) − 1) / H)²), 'off' → 1; dampenBoost, normalizeHubDampening. Pure; callers pass the caller-visible degree.

  • src/core/search/relational-recall.ts — the relational recall arm: parseRelationalQuery → seed resolution per in-scope source (federated set, scalar source, or every non-archived source for an unscoped caller; a literal __all__ resolves no seeds, fail-closed) → relationalFanout → hydrate, fail-open. Seeds resolve through resolveEntitySlugWithSource and a fallback_slugify result is dropped (confidence gate D3). The entity resolver never returns meetings, so for an incoming attended relation (Who attended <meeting>?) a live meeting or event page whose title is exactly the seed phrase (case-insensitive, unique in the source) is the seed; other relations never seed from titles. Pinned by test/relational-recall.test.ts, test/relational-recall-scope-sources.test.ts and test/pack-relation-direction-engine.test.ts. With planner on (search.relational_planner, on in balanced/tokenmax), a 2-3 relationship question (parseRelationalPlan) runs runRelationalChain first: answers then evidence pages, each with a relational field; nothing found → the one-hop path; refused → no arm (meta.plan). With orientOneHop (search.relational_orient_onehop, off in every bundle) typed one-hop walks add neighbors reached through links written on the other page. answerRows limits the pin and evidence slot to answers. Hydrate selects a bounded body prefix and shows its synopsis through page-window/bounded-lead.ts. Pinned by test/relational-recall.test.ts.

  • src/core/search/relational-rerank-pin.ts — relational-arm rows bypass reranker DEMOTION (ranker wave, receipt R1 in scripts/r1-namedthing-rerank-ab.ts: on NamedThingBench's 39 graph-relationship questions the shipped balanced default lost hit@1 21/39 → 3/39 and hit@3 27/39 → 5/39 with the reranker on — 19 and 22 paired losses — because the cross-encoder scores chunk TEXT and an edge-derived answer's text need not mention the query's entity; with the pin at its default 3, measured with --autocut on, the shape that shipped before rule R2 turned autocut off, the same paired run shows 0 hit@1 / 0 hit@3 losses, 21/39 and 27/39, and the 11 non-relational core queries show 0 losses — one hard-negative gain, hit@1 10/11 → 11/11). pinRelationalRows(reranked, relationalList, {max, fusedOrder?, onPin?}) is a pure PERMUTATION of the post-rerank pool: relational rows (page key (source_id, slug) in the arm's list; ONE row per page — its first, highest-ranked occurrence) claim min(fused_rank, reranked_rank) (fused rank = position among relational rows in fusedOrder, the pre-rerank deduped pool; arm order for rows absent from it), claims sort ascending with ties resolved to the FUSED order then the reranked position, the first max claimants form the top block in that order, every other row follows in reranked order (an unpinned row lands at its reranked position or up to pinned.length lower, never higher). Pinned rows are shallow copies stamped relational_pinned: true; no row is added or removed (re-injecting rows dropped upstream stays ensureRelationalEvidenceSlot's job). Every no-op path (max <= 0, empty pool, empty arm, no relational page in the pool) returns the input array itself. normalizeRelationalRerankPin is the ONE range contract for the knob (non-negative integer <= 10 or a string parsing to one → that integer; the literals off / false (any case) or boolean false → 0; anything else → undefined = fall through), shared by mode.ts:loadOverridesFromConfig and both per-call seams in hybrid.ts; DEFAULT_RELATIONAL_RERANK_PIN (3) and RELATIONAL_RERANK_PIN_MAX (10) are exported. RelationalRerankPinDecision ({max, relational_in_pool, pinned:[{slug, source_id, from_rank, to_rank, fused_rank}], moved}) is surfaced as HybridSearchMeta.relational_rerank_pin for --explain. Wired in hybridSearch immediately after applyReranker and before the alias hop, gated on the reranker having actually reordered (reranked !== deduped — applyReranker returns its input on every fail-open / skip / pass-through path, and the fused order already carries the arm) and on non-image modality; autocut's scoreOf ignores pinned rows and its preserve predicate keeps them, so text-row autocut is byte-identical to the pre-pin behavior. Known cost: a false-positive arm (relational shape parsed AND a real seed resolved, but wrong/stale edges) now puts up to max edge pages at ranks 1..max instead of one at limit; mitigations are the arm's fallback_slugify confidence gate, the tier-2 resolution-margin TODO, config search.relational_rerank_pin off, and per-call SearchOpts.relationalRerankPin. Pinned by test/search/relational-rerank-pin.test.ts (pure contract + tie policy) and test/search/relational-rerank-pin-hybrid.serial.test.ts (hermetic PGLite on the relational corpus through the REAL gateway rerank path behind __setRerankTransportForTests with an inverted-relevance stub: pin 0 reproduces the regression, pin 3 restores hit@1/hit@3 on all 8 who-invested questions, non-relational queries and reranker-off runs are byte-identical).

  • src/core/search/collapse.ts — collapseResults: folds copies of one result into the best-ranked row before reranking and again after the identity tiers (rank.ts collapsePool, both keyword-only paths): same slug in another source (twin), a redirect stub whose readable target it names (redirect; a target missing from the pool is read under the alias-hop read policy, an unresolved stub stays stamped redirect_to), and copies of one document (family: identical bodies, or a derivative or leaf-extension slug in the same source). The kept row lists them in collapsed; meta.collapse counts them. Knob search.collapse (#4612, #7153, #7154).

  • src/core/search/rank-priors.ts — applyRankPriors: multiplicative priors after rerank and pinning (person rows on an organization question, low-coverage image rows stamped image_page, undated rows on a when-question, redirect stubs, and archive rows (GST-2768: ARCHIVE_PRIOR under a close non-archive row, ARCHIVE_HITS_PER_DAY per day, off for a conversation or date query)); each changed row carries rank_prior and rank_score. Knob search.rank_priors.

More entries