Garry's Opinionated OpenClaw/Hermes Agent Brain
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 thequeryop'scragmeta and escalation) and the W3 rerank gate's PRE-rerank grade.gradePreRerankis 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), elsehigh_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, isidentity_ambiguous; multimodal queries and image rows are never strong;applyRerankGateTrustdemotes a strong page belowmax(caller min_trust, unknown)tobelow_trust_floor.RERANK_GATE_SKIP_REASONS(onlyhigh_vector_match) decideswould_skip; title, alias and exact-lookup strengths areskip_blocked: shadow_only_reason, and an active System One rerank slot isdecide_rerank_slot.rerankAndPinstartsreadIdentityLookups(alias and exact lookups, any gate mode) alongside the reranker;sizeReturnPoolapplies them.prepareRerankGate(the stage, gate notoff) grades with them, reads rank-1's page tier throughstampPageTruston a copy, and returnsmeta.rerank_gate(mode,eligible/ineligible_reason— reranker off, egress denied, no candidates —grade,reason,top_cosine,gap,candidates,would_skip,skip_blocked,provider_called).shadowresults, provider payloads and lookup counts are identical tooff. Pinned bytest/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/confidentialityvalues gbrain does not read.ignoredPrivacyLabelsand its SQL twinignoredPrivacyLabelSqlare one rule (test/ignored-privacy-labels.test.ts): novisibility, no recognizedPRIVACY_ALIASESvalue, no default-private rule. Oneprivacy_label_ignoredsafety notice (counts by value, no content, git sentence only whensourceHasRepo) from put_page (withIgnoredPrivacyLabelNotice), import and sync (ignoredPrivacyLabelRunNotice); the doctor check isdoctor/checks/privacy-label-ignored.ts. Reads nothing differently.src/core/search/rerank.ts— the call-site abstraction.applyReranker(query, results, opts)slots betweendedupResults()andenforceTokenBudget()insrc/core/search/hybrid.ts. Slicesopts.topNIn(default 30) by current RRF order, caps each document viacapRerankDoc(RERANK_MAX_DOC_CHARS=6000then a measured-ratio shrink toRERANK_MAX_DOC_TOKENS=1400— a 2048-ubatch llama-server minus query/template headroom minus a Qwen-tokenizer margin; every cut throughtruncateUtf8so 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 togateway.rerank(), reorders byrelevanceScoredesc (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 everyRerankError.reason: any error logs vialogRerankFailureand returns the input array unchanged — except the SKIP classno_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 firesopts.onSkip(reason); every OTHER thrown failure (HTTP error, network, timeout, budget) is audited and firesopts.onFailure(reason)withRerankFailedReasontimeout | budget | rate_limited | unreachable | auth | provider_error(gatewayrate_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 bytest/rerank-failure-reason.serial.test.ts), whichhybrid.tsstamps as{stage: 'rerank_failed', reason}(recall-affecting, likererank_passthrough; the LongMemEval reranker gate and the R1 script count it as un-reranked);hybrid.tspasses anonSkipthat stamps{stage: 'reranker_skipped', reason}intoHybridSearchMeta.degraded(closed vocabulary intypes.ts), which--explainrenders asdegraded: reranker_skipped (no_key)viaformatDegradedSummary— the only place a silently skipped reranker is visible from the CLI.types.tsclassifies the stage as ranking-only:RANKING_ONLY_DEGRADED_STAGES(={reranker_skipped}) +affectsRecall(entry)— consumers that ask "was recall impaired?" filter through it (the CLINo results.line incli.ts:describeEmptyRetrievaland the MCP empty-result block indispatch.ts:buildEmptyRetrievalBlockkeep 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 bytest/degraded-stages-recall.test.ts.hybridSearchCachedexcludesreranker_skippedfrom the short degraded-TTL rule (it is a config state, not a transient limp: a keyless balanced brain keeps the fullcache.ttl_seconds, and the stored meta still carries the stamp). Stampsrerank_scoreonto reordered items so downstream telemetry sees the new ordering signal.topNOut: nullis the explicit "don't truncate" signal — semantically distinct fromundefined("fall through to mode bundle"). Test seam:opts.rerankerFnstubsgateway.rerankwithout the network. Document cap pinned bytest/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, so412never matchest004120); an image page counts only when an image arm ran (HybridSearchMeta.image_arm) or it was returned;could_affect.pending_imagescounts the could-affectsealable/reimportimages, which the notice words as waiting for an operator.src/core/search/rrf-page-fusion.ts—accumulateRrf(lists), the one accumulation step behindrrfFusion/rrfFusionWeightedinhybrid.ts. Votes are keyed on the PAGE(source_id, slug): each list addsweight / (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-propagatedkeyword_hit(keyword_relaxedonly if every holding list was relaxed), and each page's lead chunk (largestown, first-seen on ties — a vector arm incomposeFusionListsorder) scores the page's summed vote while its other chunks score their own vote. Pure. Pinned bytest/search/rrf-page-grain.test.ts.src/core/search/evidence-delivery.ts— thereturn_unitevidence assembler (defaultauto: conversation pages by type orchat//conversations/slug come back whole undersearch.return_budget_conversation(24,000), every other hit is its unchanged chunk;effectivePlanskips the stage when an impliedautosees no conversation hit, so that path andchunkstay byte-identical).resolveEvidencePlanvalidatesreturn_unit/return_window(invalid_params naming the allowed values and an example), readssearch.return_unit/think.return_unit,search.return_window,search.return_budget_default(6,000),search.return_budget_conversation(24,000) and clamps remote budgets tosearch.return_budget_max_remote(32,000, reported). Snippet precedence: explicitsnippet_chars> explicitreturn_unit> subagent default cap > config unit.deliverEvidencegroups hits by page_id (one block per page at its best rank), makes ONEengine.getChunkWindowscall (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 throughcredentialSafeProjectionbefore 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), cutswindow/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 withdeliveredplus adeliverymeta. The plan recordsbudgetExplicit(the caller passed the budget) and the resolvedpacking(search.auto_packingor the library override);capEngaged(unitauto, explicit budget, packing notoff) routes allocation toallocateCapped: global rank one first (cut withEVIDENCE_CUT_MARKERwhen it alone exceeds the budget), the rank-order prefix of other non-conversation chunks that fits (restbudget_note), then conversations bycap_only(floors, then enrichment),breadth_capped(longest prefix whose title + floor +return_windowtarget window fits; restbreadth_cap) ordepth_first(each session grown in turn); nothing spills.capEvidenceToBudgetrecounts title +chunk_textat the final boundary (after redaction andcapDeliveredSnippets, whose marker is paid from the row's own allocation) and rewritesbudget_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/ opassemble_evidencedeliver the exact evidencequeryreturns for a frozen(source_id, slug, chunk_id)list,effective_dateincluded (applyEffectiveDate, the live rows' normalizer);evidenceFingerprinthashes it (gbrain-evals E1/E3 parity). Withsearch.evidence_date_headeron (plan.dateHeader), each block (includingautopassthrough chunks) starts with its one-line date header fromevidence-date.ts, reserved in the block floor like the title, counted indelivered.tokens, with spans shifted past it anddelivery.date_header: true; a failed date read rendersunknownand addsdate_header_unavailable.search.long_page_unit(F2, defaultoff):withLongPagePolicy(called only by thesearch/querycaller, so recall, think andassemble_evidencenever carry it) setsplan.longPage(unit plussearch.long_page_min_chars, default 20,000) under an impliedautowith no explicit budget (snippet_charsdoes not turn it off;capDeliveredSnippetsskipsreason: long_pagerows and cuts every other row);selectLongPagesruns one character/byte-count preflight under the read scope (long = stored body at leastminCharscharacters, confirmed on the renderedpageEvidenceTextat delivery; at mostLONG_PAGE_MAX_PAGES5 andLONG_PAGE_MAX_INPUT_BYTES1,000,000, whole pages only;LONG_PAGE_DEADLINE_MS2,000 for preflight plus fetch) and returns exactlyeffectivePlanwhen no page is long;deliverEvidencefetches the selected pages in their own boundedgetChunkWindowscall, delivers them in the unit withreason: long_page, and returns any it cannot deliver (limits, deadline, fetch failure, over budget) as their ranked chunk withreason: long_page_chunkand along_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; benchscripts/bench-evidence-delivery.ts. Large pages: apage(or auto→page) unit over 256 KB is delivered as a window withfallback_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 byplanSegmentedBlockfrom the windowssegmented-evidence.tsreads around its hits, one run per window (emission marks the gap between runs, a section never crosses one); no page text, whole-page projection orlocateChunksruns 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 offdisables it): withreturn_unit: pageand a caller budget,resolveEvidencePlanstoresrankCut({mode, factor, caller_budget}, factor fromsearch.page_rank_cut_factor, default 1.5) on the plan;search/query/recallpass it asHybridSearchOpts.pageRankCut, andliftModeCutdrops the mode's chunk-tokentokenBudgetin 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.tswholeCost: floor plus every enrichment piece within the block char cap) fitsfactor × the shared budget, keeps the crossing page only when its floor fits what is left, and drops the rest asrank_cut.delivery.page_rank_cutreports 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 byCOALESCE(effective_date, updated_at); question/synthesis/pinned-question pages excluded) andprefixAnchoredPages, shared by pinned-question refresh (questions/refresh.tsanchoredSlugs) and thequery/searchops;asksForCurrentState(deterministic cue regex),namedEntity(exactly oneisFactEntityPagepage whose titleisTitleMentionedInQuerymatches, 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 throughgetChunkWindowsunder the caller's scope, rows stampedentity_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'squestion(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 throughprojectionEligibleSql, the trust floor, world-only facts when the scope saysworldOnly(worldOnlyFacts),privateProvenanceFilterFragmentwhenexcludePrivate) plus recall's filters inside every arm before its LIMIT ((source_id, entity_slug)pairs,source_session, event-time since, escapedILIKEgrep); arms, run concurrently and merged in a fixed order, are keyword FTS (factsFtsDocument, served byidx_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_searchsized to the depth and pgvector's iterative scan whenhnswIterativeScanis set) and the named entity page's facts in its own source (withhistory, GBRA-574, that arm also takes the entity's ended facts,ENDED_FACT_SQL: superseded or pastvalid_until, never withdrawn, forgotten or from a purged page); depths are bound parameters;cosineForAllscores every candidate's cosine whichever arm found it;distinctiveTerms(recall's question, GST-1304) searches a question overMAX_QUERY_TERMS(12) content terms on its last 24 and returns intermsthe 12 of those the fewest candidates hold (heldTerms; later word first on a tie) forscoreFactCandidates, 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, oneto_tsvectorread 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 pastTERM_STUFFING_RATIOtimes the question's terms for a long fact; order score, newest valid_from, id.admitted: thereserverule (cosine >= 0.5 or share >= 0.34) or thefacts_armrule (cosine >= 0.6, half the terms, or the named entity).countUncomparableFactscounts the pool's facts the cosine arm cannot compare, per source: candidates fromidx_facts_unembeddedandidx_facts_embedding_modelfirst, the read policy on those rows only. The keyword arm and the count run undercustomPlan(plan_cache_mode = force_custom_planin a transaction): a cached generic plan cannot see the source arrays and nests the policy anti-joins over every match.readSlotRows(GBRA-574 B2) andlaterRetractions(B5): a slot's unwithdrawn conversation rows, pastvalid_untilincluded, 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: thequeryop'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 passedtoken_budgettakes the facts block (search.query_facts_block, default on; at mostlimitrows, 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(oneEXISTS embedding_image IS NOT NULLprobe per engine, cached 60 s, fail-open to true).hybrid/arms.tsuses it so an inferred image/both modality on a brain with no image embeddings stays text: no multimodal embed, keyword arm kept, novector_arm_failed; the opt-in LLM modality tie-break still runs, and an image or both answer is demoted to text. An explicitcrossModalis 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 forBrainEngine.getChunkWindows. The SQL lives once insrc/core/engine-sql/chunks.ts(getChunkWindows): page rows (authorization + seal + max chunk index + raw body columns; a segmented page's row sayssegmentedand 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 carryprojected_byte_start/endwhen recorded, and on a segmented page theiroccurrence_id(the span is relative to that occurrence's projection), the referencessearch/segmented-evidence.tsreads 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.readSegmentedWindowsopens 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 withreadBodyRange(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.tsplanSegmentedBlockjoins them. Never builds a page text or callslocateChunks. 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_targetdiagnosis. ATargetTrace(HybridSearchOpts.explainTarget) records the target page's presence and 1-based rank at each pipeline stage: every arm instance (arm:<label>, plusarm:keyword_raw/arm:title_rawbefore relaxed-row demotion),fused,deduped,reranked,return_pool,limit_slice,token_budget.diagnoseTracereturns 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+diagnoseProberun 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 sametarget_not_found_or_not_visible. Every diagnosis carries an Action-contract fix thesearch/queryops emit as a notice. Pinned bytest/search/explain.test.ts.src/core/search/output-redaction.ts— copies retrieval results and metadata before output sanitation, sharing the canonicalsecret-scan.tsplan 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 withhighEntropy: true, soKEY=valueassignments 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 endpointsfrom_slug,to_slug,origin_slugand 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.uncappedscans every field whole (nooutput_limitreplacement; one echo dictionary, every field planned before any write; the depth cap stays) andverbatimcopies the named keys of each top-level result unscanned.withOutputRedaction(op)is the registration-time wrapper behindOperation.outputRedaction(src/core/ops/contract.ts):operations.tswraps every'retrieval'op's handler once, so the CLI, stdio and HTTP MCP, subagent tools andgbrain callall pass the whole response (early returns included) through the uncapped redactor, linear in output size;{ retrieval: { localVerbatim } }leaves the named keys raw only whenctx.remote === false. The memory verbs:recall,context_packanddeltaredact their presentation sets with one echo dictionary before packing, so budgets,budget_usedand the delta cursor follow the delivered text, and their renderedtextis never replaced byoutput_limit; facts (fact,context,source) arelocalVerbatim, 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 withremote = trueagainst 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.entityintent gets a tight cap;temporal/event/generalget a recall-preserving cap (conceptis coerced togeneralbyhybrid.tsbefore the call — concept queries want breadth). AminKeepfailsafe (≥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. ExportsAdaptiveReturnConfig,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 intohybridSearchAFTERapplyReranker, BEFORE thelimitslice, 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 ontoHybridSearchMeta.adaptive_returnforgbrain search --explain.hybridSearchCachedSKIPS 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_returndeclared insrc/core/types.ts. Agent-facing: thequeryop (src/core/operations.ts) exposes anadaptive_returnboolean param whose description instructs the agent WHEN to set it (single-answer → on; breadth/exploration → off; passlimit:1for a hard single-answer cap), threaded intohybridSearchCached— end users never touch the config knob; their agent decides per query (same pattern assalience/recency). Pinned bytest/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.currentTextProjectionFilteremits(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.belowSafeChunkFenceis the page-level predicate shared by the importers' unchanged-content re-seal and the drain.chunkWriteInvalidations(pageId, chunks)yields one guardedchunker_version = -1invalidation per row batch of a chunk replacement (batch-rows.tsjsonRowBatches); 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;pneedsbody_storage),chunkGenerationProbe(c)the same without a joined page, andchunkManifestJoin/chunkDocumentOrdergive segmented rows document order (manifest byte_start, local_ordinal);scripts/check-chunk-visibility.tsrequires one of them or a reason on everycontent_chunksreader (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) andDEFAULT_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/parseHardExcludesEnvparse comma-separatedprefix:factorpairs fromGBRAIN_SOURCE_BOOST/GBRAIN_SEARCH_EXCLUDE.resolveBoostMap(env, config)layers defaults (dropped by anoneentry), the brain'ssearch.source_boostsconfig and the env override; hybridSearch resolves it once from the mode config snapshot and passes it to the engines asSearchOpts.source_boosts(engines fall back to defaults + env when absent; the keyword-onlysearchop branch reads the key itself).resolveHardExcludesmerges defaults + env + callerSearchOpts.exclude_slug_prefixes/include_slug_prefixes. The surviving exclude policy is auditable via thehidden_by_search_policydoctor check (src/commands/doctor/checks/calibration.ts, local + remote paths) which counts chunked pages withheld per active exclude prefix, reusingresolveHardExcludes+buildVisibilityClause+ the exportedescapeLikePattern.src/core/link-ranking-policy.ts— the link-type ranking participation policy:NON_RANKING_LINK_TYPES(amends),linkTypeRanks, andrankingLinkSql(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 inapplyIdentityBoosts(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 (frontmatterdream_generated: true, typeextract_receipt) getprovenance: 'generated'; such a row is multiplied byGENERATED_FACTOR(0.5, stampedgenerated_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(frontmattersupersedes/corrects, a facts-fence row withvalid_until) exempts corrections.search.demote_generated=falsekeeps scores. Its page read (readGeneratedPages) starts beforerunPostFusionStages. Tests:test/search-provenance-demotion.test.ts.src/core/search/frontmatter-where.ts+src/core/ops/where-param.ts— thewherefrontmatter equality filter onsearch,query,list_pages(#7159; CLI--where key=value). Bounded keys and values, elseinvalid_params; each value is a boundp.frontmatter @> $n::text::jsonbtest (GIN-served), pushed into every SQL leg; a filtered call skips the hybrid cache andkeepFrontmatterMatchesre-checks the other arms. Tests:test/search-frontmatter-where.test.ts, its e2e parity file.src/core/search/filter-hint.ts— onesearch_filter_hintinfo notice per session when a first-pagesearch/querynames 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):withSearchCostmeters everyinvokeAIin the request viawithAIInvocationMeter(AsyncLocalStorage); refused calls are not counted;gateway.expandgets anexpansionline. Test:test/search-cost.serial.test.ts.src/core/search/stage-timings.ts— per-request search stage timings. Thesearch/queryhandlers create oneSearchTimingsand 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) intooverlapped_ms, outside any stage.part()books a stage's serial steps intoparts_ms.branch()returns a timer for stages run alongside the critical path (hybrid's vector side: modality, expansion, embed, vector arms); untiljoin(branch, promise)its stage time goes tooverlapped_msunder the stage name, and from the join the wait is booked to the branch's current stage (its key shows instages_mseven at 0).snapshot()readstotal_msfrom its own monotonic start, apportions integerstages_ms+other_mssumming to it exactly (other_ms >= 0);searchOutputtakes it once the returned rows exist and emits it as_meta.retrieval.timings(never in content blocks);formatTimingsSummaryis the--explainline. Stages: setup, lexical, relational, expansion, embed, vector, fuse, post_fusion, rerank, alias_fanout, anchoring, facts_arm, response. The gate (per bench query0 <= total - sum(stages) <= 10%) is thetimingsphase ofscripts/bench-refactor-wave-1.ts. Pinned bytest/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'whendetail === 'high'for temporal-bypass parity with COMPILED_TRUTH_BOOST).buildHardExcludeClause(slugColumn, prefixes)emitsNOT (col LIKE 'p1%' OR col LIKE 'p2%')— OR-chain wrapped in NOT, NOTNOT 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'searchVectorinject — instead of returning the single best chunk per page from an innerORDER 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 ofPostgresEngine.searchKeyword's statement (ccsource, full-text match, text modality). For excludePrivate callers it plans the match alone in anOFFSET 0subquery; joined, the visibility subplans' cost let a seq scan detoasting everysearch_vectorwin (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 oneLIMIT 1key 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 bytest/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=2non-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 (givenNameVariantsinentities/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. ExportstokenizeTitle+__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 withhnsw.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 rawcandidatePool(a short window means the index ran dry) and an optionaleligiblePool(fresh candidates);hasMorereceives 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_scanin the caller's mode (defaultrelaxed_order);walkOverfetchaddsINDEX_WALK_SETTINGSand sizesef_searchfor the over-fetched window;joined(a pool attempt of a statement with an index walk) addsJOINED_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, doctorvector_planand the plan-proof E2E:{ sql, exactSql, hasMoreSql, params, innerLimitIdx, innerLimit, indexed, relaxed, indexWalkSql?, indexWalkOverfetch, scopeScanSql? }. On an HNSW-indexedembeddingcolumn (relaxed variant) the candidate CTE carries only the model check; content freshness (embedded_text_hash = md5(chunk_text)or NULL) is projected ashash_currentand filtered inscored, because Postgres cannot estimate that expression and drops the index when it sits in the CTE (#5824). Non-indexed columns, the legacy guard,exactSqlandhasMoreSqlkeep the full guard inside. The pool row reportscandidate_pool(raw) andeligible_pool(fresh). Since/until bounds are spelled per column (effective_date, thenupdated_at, thencreated_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:annorderscontent_chunksalone 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 nearestinnerLimit. Run withenable_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 withef_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'svectorScopeLoaderreadsPAGE_SOURCE_STATS_SQL(pages.source_idplanner statistics pluscontent_chunksreltuples) at most once a minute, only for source-scoped searches, and passesscope(share, andchunks). For a scope underSCOPE_SCAN_MAX_SHARE,chunkscomes fromSCOPE_CHUNKS_SQL(at most once a minute per scope): the scope's live pages times the chunks per page of ahashint4stride 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-fetchesindexWalkOverfetch(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 belowINDEX_WALK_MIN_SCOPE_SHARE(0.04) skips it.scopeScanSql(relaxed variant, same parameters) serves a scope underSCOPE_SCAN_MAX_SHARE(0.3) of pages with at mostSCOPE_SCAN_MAX_CHUNKS(120k) counted chunks: an exact distance scan over the scope's chunks, page filters and visibility applied once per page insidecc.page_id = ANY(ARRAY(...))so chunks are always reached throughidx_chunks_page(an inline join flipped to a sequential scan with the private-page rule), ordering only chunk ids with(distance) + 0to keep the index out, then the window joins back for its columns. Up toSCOPE_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 bytest/e2e/vector-scope-recall-postgres.test.ts. Missing statistics leave only the unscoped walk and the joined statement. PGLite adds the timelinestalecolumn; everything else is byte-identical across dialects. Also exports the extension-version probe and the transaction-localstatement_timeoutSQL the Postgres engine runs. Pinned bytest/search/vector-statement.test.ts,test/search/vector-freshness.test.tsandtest/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_GUARDwins oversearch.vector_legacy_guard);resolveVectorLegacyGuard(engine, cfg)latches it once per engine (engineKey) forhybrid/request.ts, which passesSearchOpts.vectorLegacyGuardto the engines (they never read config), and prints[gbrain] vector legacy guard activeto 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_onlydefault,breadth_capped,depth_first) forsearch.auto_packing,MIN_EXPLICIT_AUTO_BUDGET(32; an explicitautobudget below it, or non-finite, is refused withinvalid_paramsnaming it),parseAutoPacking(the library override, unknown values refused),configPacking(unknown stored values read as the default) andautoPackingValueProblem(theconfig setrefusal wired throughsearch/config-values.ts);queryBudgetUsesAuto(search.query_budget_unit, GBRA-205:automakesquery'stoken_budgetthe hard cap, defaultchunk). Tests:test/evidence-delivery.test.ts,test/search-8k-conversion.test.ts.src/core/search/hnsw-iterative-scan.ts— the pgvectorhnsw.iterative_scanmode for filtered vector search (#6132 idea):relaxed_orderby default,strict_orderoroffthroughGBRAIN_HNSW_ITERATIVE_SCAN(wins) orsearch.hnsw_iterative_scan(file > DB via loadConfigWithEngine).resolveHnswIterativeScan(engine, cfg)latches once per engine (hybridrequest.tspasses it asSearchOpts.hnswIterativeScan; engines hand it towithVectorSettings), logging once per override mode per process when an override is active.hnswIterativeScanValueProblembacks theconfig setrefusal throughsearch/config-values.ts(searchConfigValueRefusal: enum/range rules forsearch.*keys, exit 2invalid_params, nothing written). Pinned bytest/search/hnsw-iterative-scan.test.tsand the Postgres recall fixturetest/e2e/hnsw-iterative-scan-recall-postgres.test.ts; benchscripts/bench/hnsw-iterative-scan.ts(its--corpus latentmode, withscripts/bench/hnsw-latent-corpus.tsand the VM bootstrapscripts/bench/hnsw-scale-vm-setup.sh, is the E5.4 scale and index-build bench; results indocs/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 intohybridSearchwhen 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 bytest/internal-breadth-callers.serial.test.ts;eval-contradictions/runner.tsstill 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 withno_cue,duration_question("how long", "how many days ago/passed/before…") ormulti_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:reservedkeeps the top ⌈k/2⌉ in place and fills the rest of k with in-range results;partitionmoves every in-range result first. These are used by the eval-only--time-scopearm; 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) andfactKeyedEmbeddingInput(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_textis never changed. Used by the eval-only--fact-keysarm. 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 currentcontent_hashin one query by page id, stampscontent_hash(answer recording uses it) and, whenfeedback.influenceλ > 0, multiplies the ordering score by1 + λ·2·(w − 0.5)(bounded[1 − λ, 1 + λ], stampedfeedback_boost). The ordering score isrerank_scorewhen the reranker reordered the list (unscored tail rows stay after the head) and the fusedscoreotherwise; rawscore/rerank_scoreare never modified, so autocut and evidence read the same values. Neutral weights return the list untouched. Called once fromhybrid/rank.tsrerankAndPin(between the reranker and the relational re-pin) and at the end of both keyword-only paths inhybrid/keyword-only.ts; paths that bypasshybridSearchget no feedback. Fail-open (errors counted, shown bygbrain feedback status). Pinned bytest/feedback-boost.test.tsandtest/e2e/feedback-parity.test.ts.src/core/search/relational-chain.ts— multi-hop chain runner overrelationalChainHop: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, statusesfired/anchor_not_found/no_edges/empty_hop/truncatedwithcap_hit; plusresolveChainAnchors,validateChainHops(agenthops) andpresentEdgeContext(remote: sanitized, ≤160 chars). Pinned bytest/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). Returnsplan/not_applicable(fewer than two relationships) /unsupportedwith a reason (coordination, negation, time, counting, quotes, multiple entities, incoherent types).isRelationalQuery(query, plannerOn)is the relational test for ranking decisions; planner off it equalsparseRelationalQuery. Pinned bytest/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 throughresolveEntitySlugWithSourceand afallback_slugifyresult is dropped (confidence gate D3). The entity resolver never returns meetings, so for an incomingattendedrelation (Who attended <meeting>?) a livemeetingoreventpage whose title is exactly the seed phrase (case-insensitive, unique in the source) is the seed; other relations never seed from titles. Pinned bytest/relational-recall.test.ts,test/relational-recall-scope-sources.test.tsandtest/pack-relation-direction-engine.test.ts. Withplanneron (search.relational_planner, on in balanced/tokenmax), a 2-3 relationship question (parseRelationalPlan) runsrunRelationalChainfirst: answers then evidence pages, each with arelationalfield; nothing found → the one-hop path; refused → no arm (meta.plan). WithorientOneHop(search.relational_orient_onehop, off in every bundle) typed one-hop walks add neighbors reached through links written on the other page.answerRowslimits the pin and evidence slot to answers. Hydrate selects a bounded body prefix and shows its synopsis throughpage-window/bounded-lead.ts. Pinned bytest/relational-recall.test.ts.src/core/search/relational-rerank-pin.ts— relational-arm rows bypass reranker DEMOTION (ranker wave, receipt R1 inscripts/r1-namedthing-rerank-ab.ts: on NamedThingBench's 39 graph-relationship questions the shippedbalanceddefault 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) claimmin(fused_rank, reranked_rank)(fused rank = position among relational rows infusedOrder, the pre-rerankdedupedpool; arm order for rows absent from it), claims sort ascending with ties resolved to the FUSED order then the reranked position, the firstmaxclaimants form the top block in that order, every other row follows in reranked order (an unpinned row lands at its reranked position or up topinned.lengthlower, never higher). Pinned rows are shallow copies stampedrelational_pinned: true; no row is added or removed (re-injecting rows dropped upstream staysensureRelationalEvidenceSlot's job). Every no-op path (max <= 0, empty pool, empty arm, no relational page in the pool) returns the input array itself.normalizeRelationalRerankPinis the ONE range contract for the knob (non-negative integer<= 10or a string parsing to one → that integer; the literalsoff/false(any case) or booleanfalse→ 0; anything else →undefined= fall through), shared bymode.ts:loadOverridesFromConfigand both per-call seams inhybrid.ts;DEFAULT_RELATIONAL_RERANK_PIN(3) andRELATIONAL_RERANK_PIN_MAX(10) are exported.RelationalRerankPinDecision({max, relational_in_pool, pinned:[{slug, source_id, from_rank, to_rank, fused_rank}], moved}) is surfaced asHybridSearchMeta.relational_rerank_pinfor--explain. Wired inhybridSearchimmediately afterapplyRerankerand before the alias hop, gated on the reranker having actually reordered (reranked !== deduped—applyRerankerreturns its input on every fail-open / skip / pass-through path, and the fused order already carries the arm) and on non-image modality; autocut'sscoreOfignores 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 tomaxedge pages at ranks 1..max instead of one atlimit; mitigations are the arm'sfallback_slugifyconfidence gate, the tier-2 resolution-margin TODO, configsearch.relational_rerank_pin off, and per-callSearchOpts.relationalRerankPin. Pinned bytest/search/relational-rerank-pin.test.ts(pure contract + tie policy) andtest/search/relational-rerank-pin-hybrid.serial.test.ts(hermetic PGLite on the relational corpus through the REAL gateway rerank path behind__setRerankTransportForTestswith 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.tscollapsePool, 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 stampedredirect_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 incollapsed;meta.collapsecounts them. Knobsearch.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 stampedimage_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 carriesrank_priorandrank_score. Knobsearch.rank_priors.