AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.
Rust agent-memoryai-agentsbm25claude-codeclicode-searchcursordatabaseelasticsearchfull-text-searchhybrid-searchjsonllocal-firstmcpmcp-servermodel-context-protocolragrustsearch-enginevector-search
fix(search): rank multi-term coverage above one-word symbols (#2329)
xerj-org4df39315145d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ff8ba3f3d..8cbcebc5a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -85,6 +85,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- A multi-term question no longer ranks a one-word symbol definition+ (`type Token`) above a hit that covers more of the question. `xerj search`,+ `xerj def`, `xerj code`, and the plain-string `xerj_search` tool add a+ coverage score when the question has three or more content tokens, and+ drop a one-term `name`+`kind` hit behind those results. A one-token+ lookup (`xerj def Token`) is unchanged. A nested test callback larger+ than a passage is no longer returned whole: the line-snapped window is+ kept, with its line. An archived path (`archive/`, `archived/`, or+ `keep_archived`) is marked on the `xerj code` header and on `xerj search`+ (#2327).+- Scoped autoindex threads and `POST /{index}/_update/{id}` no longer abortthe process when a thread stack or a large body cannot be allocated(#1122). Indexing workers, sync replay, object-watch fetches, and mailboxdiff --git a/engine/crates/xerj-autoindex/src/def.rs b/engine/crates/xerj-autoindex/src/def.rsindex 8153bd04d..b2b5cd669 100644--- a/engine/crates/xerj-autoindex/src/def.rs+++ b/engine/crates/xerj-autoindex/src/def.rs@@ -197,13 +197,13 @@ pub fn definition_query(/// Rank the fetched window, keep the best hit per location, and return `k`/// definitions. Only `hits.hits` is replaced: totals still describe engine/// matches before deduplication, just as in `xerj def --json`.-pub fn finalize_definition_response(response: &mut Value, k: usize) -> Vec<Value> {+pub fn finalize_definition_response(response: &mut Value, query: &str, k: usize) -> Vec<Value> {let mut hits = response.pointer("/hits/hits").and_then(Value::as_array).cloned().unwrap_or_default();- rerank_def_hits(&mut hits);+ rerank_def_hits(&mut hits, query);let mut hits = unique_locations(hits);hits.truncate(k);if let Some(slot) = response.pointer_mut("/hits/hits") {@@ -261,6 +261,12 @@ fn build_def_query("type": "most_fields"}}));}+ // Same coverage clauses as `xerj search` (#2327). An identifier does not+ // grow them: `coverage_match_clauses` is empty below three tokens, so+ // `xerj def Token` stays an exact `name` lookup.+ should.extend(xerj_common::code_query::coverage_match_clauses(+ query, &fields,+ ));if is_identifier(query) && field_lookup_ok(mapped, numeric, "code") {// `code` holds the declaration text; a phrase hit there ("def <name>(",// "class <name>:") is a definition even when `name` casing differs.@@ -431,7 +437,7 @@ fn declaration_is_public(code: &str) -> bool {/// returned, then sort. A preferred kind scores +20 unless the path is a/// test, example, fuzz target, or bench. A public declaration scores +5./// Ties keep the engine order.-pub(crate) fn rerank_def_hits(hits: &mut [Value]) {+pub(crate) fn rerank_def_hits(hits: &mut [Value], query: &str) {const KIND_WEIGHT: f64 = 20.0;const PUB_WEIGHT: f64 = 5.0;let adjusted: Vec<f64> = hits@@ -469,6 +475,9 @@ pub(crate) fn rerank_def_hits(hits: &mut [Value]) {}hits[place] = hit;}+ // After the kind/visibility sort, so a +20 preferred kind cannot put a+ // one-word type back above a definition that covers the question (#2327).+ xerj_common::xccode::render::demote_sparse_definition_hits(hits, query);}/// Entry point for the `def` subcommand. Returns a process exit code.@@ -600,7 +609,7 @@ pub fn run_def_cli() -> i32 {}};- let hits = finalize_definition_response(&mut resp, k);+ let hits = finalize_definition_response(&mut resp, &query, k);if as_json {println!(@@ -857,7 +866,7 @@ mod tests {}});let mut hits = vec![test_struct, alias.clone(), src_struct];- rerank_def_hits(&mut hits);+ rerank_def_hits(&mut hits, "");assert_eq!(hits[0]["_source"]["ax_path"],"tokio/src/runtime/runtime.rs"@@ -887,6 +896,51 @@ mod tests {assert!(!declaration_is_public("publication"));}+ /// #2327: kind and `pub` weights run first. A one-word type with a higher+ /// score still finishes behind the definition that covers the question.+ /// An exact `Token` lookup does not move.+ #[test]+ fn a_one_word_type_does_not_outrank_a_multi_term_definition() {+ let token = json!({+ "_score": 400.0,+ "_source": {+ "ax_path": "src/types.ts",+ "name": "Token",+ "kind": "type",+ "line": 1,+ "code": "export type Token = string"+ }+ });+ let refresh = json!({+ "_score": 3.0,+ "_source": {+ "ax_path": "src/session.ts",+ "name": "refreshSession",+ "kind": "function",+ "line": 12,+ "code": "export function refreshSession(token: Token, handler: Handler): Session"+ }+ });+ let mut hits = vec![token, refresh];+ rerank_def_hits(&mut hits, "session token refresh handler");+ assert_eq!(hits[0]["_source"]["name"], "refreshSession");+ assert_eq!(hits[1]["_source"]["name"], "Token");++ let mut exact = vec![+ json!({+ "_score": 50.0,+ "_source": { "name": "Token", "kind": "type", "code": "export type Token = string", "ax_path": "a.ts" }+ }),+ json!({+ "_score": 10.0,+ "_source": { "name": "Alias", "kind": "type", "code": "type Alias = number", "ax_path": "b.ts" }+ }),+ ];+ rerank_def_hits(&mut exact, "Token");+ assert_eq!(exact[0]["_source"]["name"], "Token");+ assert_eq!(exact[1]["_source"]["name"], "Alias");+ }+/// "flush the tree to disk" has to search the symbol body. An identifier/// does not grow that leg, and a mapping without `impl` does not either.#[test]diff --git a/engine/crates/xerj-autoindex/src/search.rs b/engine/crates/xerj-autoindex/src/search.rsindex 97c36efe7..a177fc4d0 100644--- a/engine/crates/xerj-autoindex/src/search.rs+++ b/engine/crates/xerj-autoindex/src/search.rs@@ -349,10 +349,19 @@ pub fn search_fetch_size(k: usize) -> usize {/// of test/example/fuzz/bench paths and the page is trimmed back to `page`/// after the existing same-path and catalog passes. A prose corpus skips/// the penalty and the trim — the node was asked for `page` hits already.-pub(crate) fn rank_plain_search_hits(hits: &mut Vec<Value>, code_corpus: bool, page: usize) {+pub(crate) fn rank_plain_search_hits(+ hits: &mut Vec<Value>,+ code_corpus: bool,+ page: usize,+ query: &str,+) {if code_corpus {crate::def::penalize_demoted_paths(hits);}+ // A one-word symbol (`type Token`) must not stay ahead of a hit that+ // covers more terms of a multi-term question (#2327). One-token lookups+ // are unchanged inside that pass.+ xerj_common::xccode::render::demote_sparse_definition_hits(hits, query);prefer_citable_line_on_the_same_path(hits);let mut ordered = demote_catalog_noise(std::mem::take(hits));if code_corpus {@@ -800,7 +809,7 @@ pub fn run_search_cli() -> i32 {// catalog partition (#1504). `--json` sees the same order as the printer.// The penalty trims the wider fetch back to `-k`.if let Some(hits) = resp.pointer_mut("/hits/hits").and_then(Value::as_array_mut) {- rank_plain_search_hits(hits, code_corpus, k);+ rank_plain_search_hits(hits, code_corpus, k, &query);}// Same annotation `xerj_search` adds (#2266), so `--json` and the printed// header cite the matched line. `xerj code --json` is the raw server@@ -842,7 +851,12 @@ pub fn run_search_cli() -> i32 {} else {format!(" [{kind}]")};- println!("\n─── {loc}{tag} (score {score:.2})");+ let archived = if xerj_common::xccode::render::source_looks_archived(&src) {+ ", archived"+ } else {+ ""+ };+ println!("\n─── {loc}{tag} (score {score:.2}{archived})");// Passage-first: `_passage` is the engine's matching snippet (an// array-wrapped object with a text payload); `code` is the symbol// declaration. Never the whole file body — that is the 9x token flood@@ -1516,9 +1530,17 @@ mod tests {let mapped = names_of(&["message", "ts", "host"]);let body = search_query_body_for_mapping("SIP 403 Forbidden", 3, Some(&mapped), None);let should = body["query"]["bool"]["should"].as_array().unwrap();- assert_eq!(should.len(), 2, "{body}");+ // Recall multi_match, the exact-phrase leg, then the two coverage+ // clauses a three-token question adds (#2327).+ assert_eq!(should.len(), 4, "{body}");assert_eq!(should[0]["multi_match"]["fields"], json!(["message"]));+ assert!(should[2].get("constant_score").is_some(), "{body}");+ assert!(should[3].get("constant_score").is_some(), "{body}");assert_eq!(phrase_fields(&body), vec!["message"], "{body}");+ let rendered = body["query"].to_string();+ assert!(!rendered.contains("\"code\""), "{rendered}");+ assert!(!rendered.contains("\"name\""), "{rendered}");+ assert!(!rendered.contains("\"defs\""), "{rendered}");}/// Fields named by the exact-phrase legs, in order. The `defs` phrase@@ -1571,6 +1593,18 @@ mod tests {assert!(should[1].pointer("/match_phrase/defs").is_some(), "{body}");assert!(should[2].pointer("/term/name").is_some(), "{body}");assert_eq!(phrase_fields(&body), vec!["body"], "{body}");+ // Three content tokens (glue word "the" is dropped) grow the coverage+ // clauses. A one-token lookup above does not.+ assert!(+ should.iter().any(|c| c.get("constant_score").is_some()),+ "{body}"+ );+ assert!(+ !search_query_body("Token", 5)+ .to_string()+ .contains("constant_score"),+ "an exact symbol lookup must not grow a coverage clause"+ );}/// A content field some index maps as numeric is dropped from the@@ -1892,7 +1926,7 @@ mod tests {hit("ax_path", "src/Foo.test.tsx", 14.0),hit("ax_path", "src/fixtures/transcript.json", 8.0),];- rank_plain_search_hits(&mut hits, true, 5);+ rank_plain_search_hits(&mut hits, true, 5, "");let paths: Vec<&str> = hits.iter().map(|h| {@@ -1921,7 +1955,7 @@ mod tests {hit("ax_path", "examples/App.tsx", 11.0),hit("ax_path", "src/render.tsx", 9.0),];- rank_plain_search_hits(&mut wide, true, 5);+ rank_plain_search_hits(&mut wide, true, 5, "");assert_eq!(wide.len(), 2, "a demoted hit stays when it still fits");assert_eq!(wide[0]["_source"]["ax_path"], "src/render.tsx");assert_eq!(wide[1]["_source"]["ax_path"], "examples/App.tsx");@@ -1932,7 +1966,7 @@ mod tests {hit("ax_path", "tests/a.rs", 10.0),hit("ax_path", "fuzz/targets/b.rs", 8.0),];- rank_plain_search_hits(&mut only_tests, true, 5);+ rank_plain_search_hits(&mut only_tests, true, 5, "");assert_eq!(only_tests[0]["_source"]["ax_path"], "tests/a.rs");assert_eq!(only_tests[1]["_source"]["ax_path"], "fuzz/targets/b.rs");assert_eq!(only_tests[0]["_score"], json!(5.0));@@ -1941,7 +1975,7 @@ mod tests {hit("ax_path", "tests/a.rs", 12.0),hit("ax_path", "src/render.tsx", 9.0),];- rank_plain_search_hits(&mut prose, false, 1);+ rank_plain_search_hits(&mut prose, false, 1, "");assert_eq!(prose.len(), 2, "a prose page is not trimmed");assert_eq!(prose[0]["_source"]["ax_path"], "tests/a.rs");assert_eq!(prose[0]["_score"], json!(12.0));@@ -1968,7 +2002,7 @@ mod tests {hit("ax_path", "tests/test_model.py", 12.0),hit("ax_path", "src/model.py", 9.0),];- rank_plain_search_hits(&mut hits, true, 5);+ rank_plain_search_hits(&mut hits, true, 5, "");let paths: Vec<&str> = hits.iter().map(|h| h["_source"]["ax_path"].as_str().unwrap())diff --git a/engine/crates/xerj-common/src/code_query.rs b/engine/crates/xerj-common/src/code_query.rsindex 6b29069f0..518809fa8 100644--- a/engine/crates/xerj-common/src/code_query.rs+++ b/engine/crates/xerj-common/src/code_query.rs@@ -201,6 +201,70 @@ pub fn normalize_code_search_query(query: &str) -> String {/// body's own BM25 score.pub const EXACT_PHRASE_BOOST: f64 = 4.0;+/// Score added when a multi-term question matches on coverage, not on one+/// short symbol field (#2327).+///+/// A `name^4` / `code^2` hit whose text is `type Token = string` collects a+/// large BM25 score from field length. Definition pages in this crate's+/// tests sit near 172. One thousand sits above that, so a hit that contains+/// at least half the content terms sorts ahead of a one-term name. A hit+/// that contains every term gets this boost a second time.+pub const COVERAGE_MATCH_BOOST: f64 = 1000.0;++/// Extra `constant_score` clauses for a question with at least three content+/// tokens. Empty for a one- or two-token lookup — that is an identifier+/// search, and the exact `name` term stays the strongest signal.+///+/// The first clause matches at least half the tokens (rounded up). The+/// second matches every token. Both are filters: they do not multiply BM25,+/// and a document that fails them still matches the recall clauses.+pub fn coverage_match_clauses(query: &str, fields: &[String]) -> Vec<Value> {+ let shaped = normalize_code_search_query(query);+ let tokens: Vec<&str> = shaped.split_whitespace().collect();+ if tokens.len() < 3 || fields.is_empty() {+ return Vec::new();+ }+ let need = tokens.len().saturating_add(1) / 2;+ let per_term: Vec<Value> = tokens+ .iter()+ .map(|token| {+ json!({+ "multi_match": {+ "query": token,+ "fields": fields,+ "type": "most_fields"+ }+ })+ })+ .collect();+ vec![+ json!({+ "constant_score": {+ "filter": {+ "bool": {+ "should": per_term,+ "minimum_should_match": need+ }+ },+ "boost": COVERAGE_MATCH_BOOST+ }+ }),+ json!({+ "constant_score": {+ "filter": {+ "multi_match": {+ "query": shaped,+ "fields": fields,+ "type": "most_fields",+ "operator": "and"+ }+ },+ "boost": COVERAGE_MATCH_BOOST+ }+ }),+ ]+}+/// The text an exact-phrase content clause matches, or `None` when the query/// is a single token.///@@ -490,6 +554,10 @@ fn build_search_query(}}}+ // Appended last so the #916 clause positions do not move. A one-word+ // symbol still matches the recall `multi_match`; these clauses only+ // add score when the document covers the question (#2327).+ should.extend(coverage_match_clauses(&shaped, &fields));json!({"size": k,"query": { "bool": { "should": should }},diff --git a/engine/crates/xerj-common/src/xccode/mod.rs b/engine/crates/xerj-common/src/xccode/mod.rsindex c89f00085..d6f1ec1b4 100644--- a/engine/crates/xerj-common/src/xccode/mod.rs+++ b/engine/crates/xerj-common/src/xccode/mod.rs@@ -542,6 +542,8 @@ pub fn run_code_query(// that shrank says so in the note, naming only the caps that fired.// #1504: translation catalogs and minified bundles repeat every UI phrase// and win natural-language queries. They stay searchable, behind source.+ let mut hits = hits;+ render::demote_sparse_definition_hits(&mut hits, &query);let hits = demote_catalog_noise(hits);let (hits, file_dropped, index_dropped) = diversify(hits, params.k);if file_dropped > 0 || index_dropped > 0 {@@ -849,14 +851,16 @@ pub(crate) fn bm25_body(query: &str, k: usize, lang: &Option<String>, fields: &[if let Some(lg) = lang {must.push(serde_json::json!({ "match": { "language": lg } }));}- serde_json::json!({+ let mut body = serde_json::json!({"size": k,"query": { "bool": { "must": must } },// Response-only. `_passage.ordinal` is the 0-based line of a lexical// window (#174). It is not a highlight block, which changes ranking// (#177). The scored fast path does not serve text `multi_match`."fields": ["_passage"]- })+ });+ attach_coverage_clauses(&mut body, query, fields);+ body}/// #1237: second BM25 leg over symbol-record `impl` fields. Excludes `impl`@@ -870,11 +874,29 @@ pub(crate) fn symbol_bm25_body(query: &str, k: usize, lang: &Option<String>) ->if let Some(lg) = lang {must.push(serde_json::json!({ "match": { "language": lg } }));}- serde_json::json!({+ let fields = vec!["impl".to_string()];+ let mut body = serde_json::json!({"size": k,"_source": { "excludes": ["impl", "body"] },"query": { "bool": { "must": must } }- })+ });+ attach_coverage_clauses(&mut body, query, &fields);+ body+}++/// `should` coverage clauses for a multi-term question (#2327). A one-token+/// lookup leaves the body untouched, so the measured BM25 shape stays.+fn attach_coverage_clauses(body: &mut Value, query: &str, fields: &[String]) {+ let clauses = crate::code_query::coverage_match_clauses(query, fields);+ if clauses.is_empty() {+ return;+ }+ if let Some(obj) = body+ .pointer_mut("/query/bool")+ .and_then(Value::as_object_mut)+ {+ obj.insert("should".into(), Value::Array(clauses));+ }}fn hit_file_key(hit: &Value) -> Option<String> {diff --git a/engine/crates/xerj-common/src/xccode/passage.rs b/engine/crates/xerj-common/src/xccode/passage.rsindex 8f7d20e89..5d5e4542a 100644--- a/engine/crates/xerj-common/src/xccode/passage.rs+++ b/engine/crates/xerj-common/src/xccode/passage.rs@@ -101,11 +101,12 @@ fn symbol_spans(src: &Value) -> Vec<(String, String, i64, Option<i64>)> {/// The best matching DEFINITION, as `(text, label)`.///-/// Query terms score by count-in-span; a term appearing in the symbol's NAME-/// adds 25 — the strongest signal an agent can act on: a query mentioning-/// `addReplyNull` should return addReplyNull, not whichever unrelated span-/// repeats a common word most often. Truncation keeps the label so the-/// truncation is visible.+/// Distinct query terms in the span rank first. A term appearing in the+/// symbol's NAME adds 25 only when the query is a single identifier, or the+/// name contains every query term — `addReplyNull` still returns+/// addReplyNull. A multi-term question must not let a generic one-word name+/// (`type Token`) outrank the span that covers the rest of the question+/// (#2327). Truncation keeps the label so the truncation is visible.pub fn symbol_passage(body: &str,src: &Value,@@ -124,7 +125,8 @@ pub fn symbol_passage(if terms.is_empty() {return None;}- let mut best: Option<(i64, String, String, i64, String)> = None;+ // (distinct terms covered, score, name, kind, line, text)+ let mut best: Option<(usize, i64, String, String, i64, String)> = None;for (name, kind, start, end) in spans {let lo = (start - 1).max(0) as usize;let hi = end@@ -137,16 +139,23 @@ pub fn symbol_passage(let text = lines[lo..hi].join("\n");let low = text.to_lowercase();let nm = name.to_lowercase();+ let covered = terms.iter().filter(|t| low.contains(t.as_str())).count();+ let name_hits = terms.iter().filter(|t| nm.contains(t.as_str())).count();let mut score: i64 = terms.iter().map(|t| count_occurrences(&low, t)).sum();- score += 25 * terms.iter().filter(|t| nm.contains(t.as_str())).count() as i64;+ if terms.len() <= 1 || name_hits == terms.len() {+ score += 25 * name_hits as i64;+ }if score <= 0 {continue;}- if best.as_ref().is_none_or(|b| score > b.0) {- best = Some((score, name, kind, start, text));+ if best+ .as_ref()+ .is_none_or(|b| covered > b.0 || (covered == b.0 && score > b.1))+ {+ best = Some((covered, score, name, kind, start, text));}}- let (_, name, kind, start, mut text) = best?;+ let (_, _, name, kind, start, mut text) = best?;if py_len(&text) > width {text = format!("{}\n ... [{kind} {name} truncated at {width} chars]",@@ -809,6 +818,38 @@ mod tests {assert!(symbol_passage(body, &src, "zzzzz", 800).is_none());}+ /// #2327: a multi-term question must not prefer a one-word type whose+ /// name matches a single term. An exact one-word lookup still prefers+ /// the definition that carries that name.+ #[test]+ fn multi_term_query_prefers_the_span_covering_more_terms() {+ let body = "\+export type Token = string;\n\+\n\+export function apply(token: Token, handler: Handler): Session {\n\+ return handler.refresh(token);\n\+}\n\+\n\+export type Handler = { refresh(token: Token): Session };\n\+";+ let src = json!({+ "symbols": [+ { "name": "Token", "kind": "type", "line": 1, "end_line": 1 },+ { "name": "apply", "kind": "function", "line": 3, "end_line": 5 },+ { "name": "Handler", "kind": "type", "line": 7, "end_line": 7 }+ ]+ });+ let (text, label) =+ symbol_passage(body, &src, "session token refresh handler", 800).unwrap();+ assert_eq!(label, "function apply @ line 3");+ assert!(text.contains("handler.refresh"), "{text}");+ assert!(!text.contains("export type Token"), "{text}");++ let (exact, exact_label) = symbol_passage(body, &src, "Token", 800).unwrap();+ assert_eq!(exact_label, "type Token @ line 1");+ assert!(exact.contains("type Token"), "{exact}");+ }+#[test]fn best_window_is_densest_and_snaps_only_without_evidence_loss() {let body = format!(diff --git a/engine/crates/xerj-common/src/xccode/render.rs b/engine/crates/xerj-common/src/xccode/render.rsindex e55251d7e..aff743a58 100644--- a/engine/crates/xerj-common/src/xccode/render.rs+++ b/engine/crates/xerj-common/src/xccode/render.rs@@ -247,6 +247,95 @@ fn terms_covered(haystack: &str, terms: &[String]) -> usize {.count()}+/// A directory or file name that marks archived documentation.+fn path_is_archived(path: &str) -> bool {+ path.split(['/', '\\']).any(|seg| {+ let s = seg.to_ascii_lowercase();+ matches!(+ s.as_str(),+ "archive" | "archived" | "archives" | "_archive" | "_archived"+ ) || s.starts_with("archived.")+ || s.ends_with(".archived")+ || s.contains(".archived.")+ })+}++/// True when the hit is an archived note or lives under an archive path.+///+/// Semantic pages mix current and archived docs with no other signal+/// (#2327). The path is already on the hit; this is the explicit mark the+/// header prints. A source file named `archive.ts` is not archived.+pub fn source_looks_archived(src: &Value) -> bool {+ if src.get("keep_archived").and_then(Value::as_bool) == Some(true) {+ return true;+ }+ let path = ["ax_path", "ax_file", "path", "file"]+ .iter()+ .find_map(|k| src.get(*k).and_then(Value::as_str))+ .unwrap_or("");+ path_is_archived(path)+}++/// Move a one-term symbol definition behind hits that cover more of a+/// multi-term question (#2327).+///+/// The definition is the per-symbol document (`name` + `kind`) whose name+/// matches exactly one content term and whose text matches no other. Hits+/// that cover more terms keep their relative order, then the sparse+/// definitions follow in theirs. A one- or two-term query is a lookup and+/// is left alone, including two definitions that share one name. When no+/// hit covers a second term, the page is unchanged.+pub fn demote_sparse_definition_hits(hits: &mut [Value], query: &str) {+ let terms = content_terms(query);+ if terms.len() < MIN_TERMS_FOR_COVERAGE || hits.len() < 2 {+ return;+ }+ let covered: Vec<usize> = hits+ .iter()+ .map(|hit| terms_covered(&hit_haystack(hit), &terms))+ .collect();+ if covered.iter().copied().max().unwrap_or(0) < 2 {+ return;+ }+ let sparse: Vec<bool> = hits+ .iter()+ .enumerate()+ .map(|(i, hit)| {+ let src = hit.get("_source").unwrap_or(&Value::Null);+ let Some(name) = src.get("name").and_then(Value::as_str) else {+ return false;+ };+ if name.is_empty() || src.get("kind").and_then(Value::as_str).is_none() {+ return false;+ }+ let name_l = name.to_lowercase();+ let name_hits = terms.iter().filter(|t| name_l.contains(t.as_str())).count();+ name_hits == 1 && covered[i] == 1+ })+ .collect();+ if sparse.iter().all(|flag| !flag) {+ return;+ }+ let mut order = Vec::with_capacity(hits.len());+ for (i, flag) in sparse.iter().enumerate() {+ if !flag {+ order.push(i);+ }+ }+ if order.is_empty() {+ return;+ }+ for (i, flag) in sparse.iter().enumerate() {+ if *flag {+ order.push(i);+ }+ }+ let original = hits.to_vec();+ for (dest, src) in order.into_iter().enumerate() {+ hits[dest] = original[src].clone();+ }+}+/// One RRF leg at rank 1: `1/(k+1)`. Two legs at rank 1 — a typical strong/// hybrid hit — score twice that. k is [`super::RRF_K`] (60), the value the/// request sends.@@ -569,7 +658,12 @@ fn render_hit(format!(" why={lic}")};let weak_tok = if weak { " weak" } else { "" };- return format!("@ok f={loc} {shown}{why}{weak_tok}\n");+ let archived_tok = if source_looks_archived(&src) {+ " archived"+ } else {+ ""+ };+ return format!("@ok f={loc} {shown}{why}{weak_tok}{archived_tok}\n");}let shown = if opts.rrf_scores {@@ -583,7 +677,12 @@ fn render_hit(format!(", {lic}")};let weak_part = if weak { ", weak" } else { "" };- let mut out = format!("\n─── {loc} ({shown}{lic_part}{weak_part})\n");+ let archived_part = if source_looks_archived(&src) {+ ", archived"+ } else {+ ""+ };+ let mut out = format!("\n─── {loc} ({shown}{lic_part}{weak_part}{archived_part})\n");// `body` is the content field of every family EXCEPT plain text (`.txt`// mirrors put their passage in `text`, #1139) and `*-symbols` records@@ -1493,6 +1592,122 @@ mod tests {assert!(!page_is_weak_match(&hit, &opts, 5.0));}+ /// #2327: synthetic TypeScript symbol + Markdown. The one-word `Token`+ /// type outscores the note that answers the question; after the pass it+ /// does not. `xerj def Token` (one term) keeps the type first.+ #[test]+ fn one_term_definition_does_not_outrank_a_multi_term_hit() {+ let query = "session token refresh handler";+ let token = json!({+ "_score": 180.0,+ "_source": {+ "ax_path": "src/types.ts",+ "name": "Token",+ "kind": "type",+ "line": 4,+ "code": "export type Token = string;"+ }+ });+ let refresh = json!({+ "_score": 12.0,+ "_source": {+ "ax_path": "src/session.ts",+ "name": "refreshSession",+ "kind": "function",+ "line": 20,+ "code": "export function refreshSession(token: Token, handler: Handler): Session"+ }+ });+ let note = json!({+ "_score": 6.0,+ "_source": {+ "ax_path": "docs/session-token.md",+ "title": "Refreshing a session token",+ "body": "The refresh handler exchanges a session token for a new session."+ }+ });+ let mut hits = vec![token, refresh, note];+ demote_sparse_definition_hits(&mut hits, query);+ let names: Vec<&str> = hits+ .iter()+ .map(|h| {+ h["_source"]+ .get("name")+ .and_then(Value::as_str)+ .unwrap_or(h["_source"]["ax_path"].as_str().unwrap())+ })+ .collect();+ assert_eq!(+ names,+ vec!["refreshSession", "docs/session-token.md", "Token"],+ "{names:?}"+ );++ let mut exact = vec![+ json!({+ "_score": 40.0,+ "_source": { "name": "Token", "kind": "type", "line": 4, "code": "export type Token = string;", "ax_path": "src/types.ts" }+ }),+ json!({+ "_score": 11.0,+ "_source": { "name": "TokenStore", "kind": "class", "line": 8, "code": "export class TokenStore { token: Token }", "ax_path": "src/store.ts" }+ }),+ ];+ let before = exact.clone();+ demote_sparse_definition_hits(&mut exact, "Token");+ assert_eq!(exact, before, "a one-term lookup keeps engine order");++ // Nothing on the page covers a second term: leave the order alone.+ let mut only = vec![+ json!({+ "_score": 90.0,+ "_source": { "name": "Token", "kind": "type", "code": "export type Token = string" }+ }),+ json!({+ "_score": 40.0,+ "_source": { "name": "Handler", "kind": "type", "code": "export type Handler = object" }+ }),+ ];+ let only_before = only.clone();+ demote_sparse_definition_hits(&mut only, query);+ assert_eq!(only, only_before);+ }++ #[test]+ fn archived_path_is_marked_on_the_header() {+ let current = doc(+ "docs/session-token.md",+ 8.0,+ "The refresh handler exchanges a session token.",+ );+ let archived = doc(+ "docs/archive/session-token.md",+ 9.0,+ "The refresh handler exchanges a session token.",+ );+ let text = render(+ &[archived, current],+ &HashMap::new(),+ &prose_opts("session token refresh", false),+ None,+ );+ assert!(+ text.contains("docs/archive/session-token.md:10 (score 9.00, archived)"),+ "{text}"+ );+ assert!(+ text.contains("docs/session-token.md:10 (score 8.00)\n"),+ "{text}"+ );+ assert!(!text.contains("session-token.md:10 (score 8.00, archived)"));+ assert!(!source_looks_archived(+ &json!({ "ax_path": "src/archive.ts" })+ ));+ assert!(source_looks_archived(+ &json!({ "path": "notes/today.md", "keep_archived": true })+ ));+ }+#[test]fn a_passage_below_half_the_top_score_is_marked_and_the_top_is_not() {assert!(diff --git a/engine/crates/xerj-engine/src/code_blocks.rs b/engine/crates/xerj-engine/src/code_blocks.rsindex f768fd8ec..3ab9b8427 100644--- a/engine/crates/xerj-engine/src/code_blocks.rs+++ b/engine/crates/xerj-engine/src/code_blocks.rs@@ -50,6 +50,17 @@ use tree_sitter::{Language, Parser, Tree};/// `XERJ_CODE_PASSAGE_MAX_BYTES` for deployments with different tolerances.pub const DEFAULT_MAX_BLOCK_BYTES: usize = 16_384;+/// A call-argument callback larger than this is not a passage (#2327).+///+/// The same bound as the lexical `_passage` window (`LEXICAL_PASSAGE_MAX_BYTES`+/// in `index.rs`). A nested `it(() => { ... })` body under the 16 KiB block+/// cap used to come back whole. Past this size the caller keeps that+/// line-snapped window instead. A top-level arrow (`const f = () => {}`) is+/// not a call argument and keeps [`DEFAULT_MAX_BLOCK_BYTES`].+pub const NESTED_CALLBACK_MAX_BYTES: usize = 2_048;++const CALLBACK_KINDS: &[&str] = &["arrow_function", "function_expression"];+fn max_block_bytes() -> usize {std::env::var("XERJ_CODE_PASSAGE_MAX_BYTES").ok()@@ -298,6 +309,30 @@ const WRAPPER_KINDS: &[&str] = &[// ── Public API ────────────────────────────────────────────────────────────+/// An arrow or function expression passed as a call argument (`it(() => {})`,+/// `items.map(function () {})`). Wrappers between the function and `arguments`+/// (`await`, parentheses) still count. A `const f = () => {}` declarator does+/// not.+fn is_call_callback(node: tree_sitter::Node<'_>) -> bool {+ if !CALLBACK_KINDS.contains(&node.kind()) {+ return false;+ }+ let mut cur = node.parent();+ for _ in 0..4 {+ let Some(parent) = cur else {+ return false;+ };+ match parent.kind() {+ "arguments" => return true,+ "parenthesized_expression" | "await_expression" | "unary_expression" => {+ cur = parent.parent();+ }+ _ => return false,+ }+ }+ false+}+/// Find the smallest node enclosing byte range `[start, end)` in `body`/// whose kind counts as an acceptable semantic block for `language`, and/// return its own `[start_byte, end_byte)` span.@@ -313,7 +348,9 @@ const WRAPPER_KINDS: &[&str] = &[/// top-level `use`/`import` statement, not inside any function/class);/// - the smallest acceptable block exceeds [`max_block_bytes`] — since any/// larger enclosing block is only bigger, this stops at the first-/// candidate rather than searching further up.+/// candidate rather than searching further up;+/// - that block is a call-argument callback bigger than+/// [`NESTED_CALLBACK_MAX_BYTES`] (#2327).pub fn enclosing_block(language: &str,body: &str,@@ -334,6 +371,15 @@ pub fn enclosing_block(let mut cur = Some(node);while let Some(n) = cur {if kinds.contains(&n.kind()) {+ // A nested test callback (`it("…", () => { … })`) is an argument,+ // not the function a reader asked for. One larger than a passage+ // falls back to the caller's window (#2327). Walking further up+ // only finds a bigger callback.+ let callback_cap = if is_call_callback(n) {+ NESTED_CALLBACK_MAX_BYTES.min(max_block_bytes())+ } else {+ max_block_bytes()+ };// Widen through modifier wrappers so the passage carries the// declaration as written. Returning the bare `function_declaration`// inside `export function f() {}` would show an agent a function@@ -349,7 +395,7 @@ pub fn enclosing_block(}let n = outer;let (s, e) = (n.start_byte(), n.end_byte());- if e.saturating_sub(s) > max_block_bytes() {+ if e.saturating_sub(s) > callback_cap {return None;}if s > e || e > body.len() || !body.is_char_boundary(s) || !body.is_char_boundary(e) {@@ -538,6 +584,67 @@ mod tests {assert_eq!(enclosing_block("rust", body, start, end), None);}+ /// #2327: a nested test callback under the 16 KiB block cap and over a+ /// passage is not returned whole. A short callback still is, and a+ /// top-level arrow keeps the normal cap.+ #[test]+ fn nested_test_callback_larger_than_a_passage_is_not_a_block() {+ let mut inner = String::from("() => {\n const CALLBACK_START_SENTINEL = 1;\n");+ for i in 0..70 {+ inner.push_str(&format!(+ " const pad_{i:03} = \"session-token-handler-pad\";\n"+ ));+ }+ inner.push_str(" const refreshMarker = sessionTokenHandler();\n}\n");+ assert!(+ inner.len() > NESTED_CALLBACK_MAX_BYTES,+ "the callback has to be the oversized case, got {}",+ inner.len()+ );+ assert!(inner.len() < DEFAULT_MAX_BLOCK_BYTES);+ let body = format!(+ "describe(\"session token\", () => {{\n it(\"refreshes the handler\", {inner});\n}});\n"+ );+ let needle = "refreshMarker";+ let start = body.find(needle).unwrap();+ assert_eq!(+ enclosing_block("typescript", &body, start, start + needle.len()),+ None,+ "a nested callback bigger than a passage must fall back to the window"+ );++ let small =+ "describe(\"s\", () => {\n it(\"t\", () => {\n return refreshMarker;\n });\n});\n";+ let start = small.find(needle).unwrap();+ let (s, e) = enclosing_block("typescript", small, start, start + needle.len())+ .expect("a short callback is still the block");+ let block = &small[s..e];+ assert!(+ block.contains("refreshMarker") && block.len() <= NESTED_CALLBACK_MAX_BYTES,+ "{block:?}"+ );+ assert!(!block.contains("describe"), "{block:?}");++ let mut top = String::from("const refreshSession = () => {\n");+ for i in 0..70 {+ top.push_str(&format!(+ " const pad_{i:03} = \"session-token-handler-pad\";\n"+ ));+ }+ top.push_str(" return refreshMarker;\n};\n");+ assert!(top.len() > NESTED_CALLBACK_MAX_BYTES);+ assert!(top.len() < DEFAULT_MAX_BLOCK_BYTES);+ let start = top.find(needle).unwrap();+ let (s, e) = enclosing_block("typescript", &top, start, start + needle.len())+ .expect("a top-level arrow is a function, not a callback");+ let block = &top[s..e];+ assert!(+ block.contains("refreshMarker") && block.len() > NESTED_CALLBACK_MAX_BYTES,+ "the whole arrow stays the block: {} bytes",+ block.len()+ );+ }+#[test]fn oversized_block_falls_back_to_caller_window() {let mut body = String::from("fn huge() {\n");diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rsindex f6202b498..90d1542b8 100644--- a/engine/crates/xerj-engine/src/index.rs+++ b/engine/crates/xerj-engine/src/index.rs@@ -59483,6 +59483,77 @@ mod lexical_passage_tests {assert!(passage.ordinal > 0, "window must not hug the file head");}+ /// #2327: a nested test callback under the 16 KiB AST cap used to be+ /// returned whole. The passage stays inside the lexical window and keeps+ /// the line ordinal of that window.+ #[test]+ fn nested_test_callback_passage_stays_inside_the_lexical_window() {+ let mut callback = String::from("() => {\n const CALLBACK_START_SENTINEL = 1;\n");+ for i in 0..70 {+ callback.push_str(&format!(+ " const pad_{i:03} = \"session-token-handler-pad\";\n"+ ));+ }+ callback.push_str(" const refreshMarker = sessionTokenHandler();\n}\n");+ assert!(callback.len() > LEXICAL_PASSAGE_MAX_BYTES);+ assert!(callback.len() < crate::code_blocks::DEFAULT_MAX_BLOCK_BYTES);+ let body = format!(+ "{}\ndescribe(\"session token\", () => {{\n it(\"refreshes the handler\", {callback});\n}});\n",+ "// preamble\n".repeat(8)+ );+ let query = QueryNode::MultiMatch {+ fields: vec!["body".into()],+ query: "refreshMarker sessionTokenHandler".into(),+ match_type: Default::default(),+ operator: None,+ analyzer: None,+ boost: None,+ slop: 0,+ max_expansions: 50,+ lenient: false,+ };+ let hit = Hit {+ id: "doc-1".into(),+ score: 1.0,+ source: json!({+ "body": body,+ "language": "typescript",+ "symbol_count": 2+ }),+ seq_no: None,+ version: None,+ sort: Vec::new(),+ explain: None,+ highlight: None,+ matched_queries: Vec::new(),+ passage: None,+ };+ let out = apply_lexical_passages(vec![hit], &query);+ let passage = out[0].passage.as_ref().expect("lexical passage filled");+ assert!(+ passage.text.contains("refreshMarker"),+ "the window must contain the match: {}",+ passage.text+ );+ assert!(+ passage.text.len() <= LEXICAL_PASSAGE_MAX_BYTES,+ "a nested callback must not be returned whole ({} bytes)",+ passage.text.len()+ );+ assert!(+ !passage.text.contains("CALLBACK_START_SENTINEL"),+ "the callback head is outside the window: {}",+ passage.text+ );+ let start = passage.start_offset as usize;+ assert_eq!(+ passage.ordinal as usize,+ body[..start].matches('\n').count(),+ "ordinal is the file line of the bounded window"+ );+ assert!(passage.ordinal > 0, "the preamble keeps a real line");+ }+/// A short symbol-list field must not capture the passage from the body:/// term rarity is weighted per DOCUMENT, so `defs` containing each term/// once does not look artificially rare next to `body`.diff --git a/engine/crates/xerj-mcp/src/def.rs b/engine/crates/xerj-mcp/src/def.rsindex 355069904..a7e88bcf9 100644--- a/engine/crates/xerj-mcp/src/def.rs+++ b/engine/crates/xerj-mcp/src/def.rs@@ -102,7 +102,7 @@ pub(crate) async fn run(ctx: &Ctx, args: &Value) -> Value {true,);}- finalize_definition_response(&mut response, k);+ finalize_definition_response(&mut response, symbol, k);let text = response.to_string();tool_text(match budget {diff --git a/engine/crates/xerj-mcp/src/lib.rs b/engine/crates/xerj-mcp/src/lib.rsindex 6cff933e7..be2c94b50 100644--- a/engine/crates/xerj-mcp/src/lib.rs+++ b/engine/crates/xerj-mcp/src/lib.rs@@ -1994,7 +1994,7 @@ fn plain_search_demotes_test_paths(args: &Value, mapping: Option<&Value>) -> boo/// The penalty is [`xerj_autoindex::def::penalize_demoted_paths`] — the same/// `path_is_demoted` rules `xerj def` uses. A response that is not a search/// hit list is returned unchanged.-fn apply_search_path_demotion(text: &str, page: usize) -> String {+fn apply_search_path_demotion(text: &str, page: usize, query: &str) -> String {let Ok(mut resp) = serde_json::from_str::<Value>(text) else {return text.to_string();};@@ -2003,6 +2003,7 @@ fn apply_search_path_demotion(text: &str, page: usize) -> String {return text.to_string();};xerj_autoindex::def::penalize_demoted_paths(hits);+ xerj_common::xccode::render::demote_sparse_definition_hits(hits, query);hits.truncate(page);}serde_json::to_string(&resp).unwrap_or_else(|_| text.to_string())@@ -3190,7 +3191,9 @@ async fn engine_request(let text = resp.text().await.unwrap_or_default();if status.is_success() {let text = match demote_page {- Some(page) => apply_search_path_demotion(&text, page),+ Some(page) => {+ apply_search_path_demotion(&text, page, match_query.unwrap_or(""))+ }None => text,};let text = match match_query {@@ -3824,7 +3827,7 @@ mod tests {{"_id":"s","_score":30.0,"_source":{"ax_path":"tests/contract.rs"}},{"_id":"x","_score":1.0,"_source":{"ax_path":"src/extra.rs"}}]}}"#;- let text = apply_search_path_demotion(raw, 3);+ let text = apply_search_path_demotion(raw, 3, "");let resp: Value = serde_json::from_str(&text).unwrap();let paths: Vec<&str> = resp["hits"]["hits"].as_array()@@ -3842,7 +3845,7 @@ mod tests {);assert_eq!(resp["hits"]["hits"][2]["_score"], json!(6.0));assert_eq!(resp["hits"]["hits"][1]["_score"], json!(9.0));- assert_eq!(apply_search_path_demotion("not json", 3), "not json");+ assert_eq!(apply_search_path_demotion("not json", 3, ""), "not json");}/// A numeric mapping of a code field drops that leg (#1284 via #1601):