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): strip multi-word glue tokens and prefer code over bare name passages (#1364)
Christian M. Todieba957badda9c
diff --git a/engine/crates/xerj-autoindex/src/search.rs b/engine/crates/xerj-autoindex/src/search.rsindex cfeda3959..90f6a1f70 100644--- a/engine/crates/xerj-autoindex/src/search.rs+++ b/engine/crates/xerj-autoindex/src/search.rs@@ -42,12 +42,23 @@ pub(crate) fn passage_text(hit: &Value) -> Option<String> {let first = hit.pointer("/fields/_passage/0")?;match first {Value::String(s) => Some(s.clone()),- Value::Object(o) => o- .get("text")- .or_else(|| o.get("passage"))- .or_else(|| o.get("snippet"))- .and_then(Value::as_str)- .map(str::to_string),+ Value::Object(o) => {+ if matches!(+ o.get("field").and_then(Value::as_str),+ Some("name" | "title" | "defs")+ ) && hit+ .pointer("/_source/code")+ .and_then(Value::as_str)+ .is_some_and(|s| !s.is_empty())+ {+ return None;+ }+ o.get("text")+ .or_else(|| o.get("passage"))+ .or_else(|| o.get("snippet"))+ .and_then(Value::as_str)+ .map(str::to_string)+ }_ => None,}}@@ -61,6 +72,207 @@ pub(crate) fn is_identifier(q: &str) -> bool {&& q.chars().all(|c| c.is_alphanumeric() || c == '_')}+fn is_two_letter_tech_term(w: &str) -> bool {+ matches!(+ w,+ "db" | "ui"+ | "ux"+ | "ip"+ | "gc"+ | "vm"+ | "id"+ | "kv"+ | "ir"+ | "ci"+ | "pr"+ | "ai"+ | "ml"+ | "tx"+ | "rx"+ | "fs"+ | "fd"+ | "pk"+ | "fk"+ )+}++fn is_three_letter_glue_word(w: &str) -> bool {+ matches!(+ w,+ "del"+ | "por"+ | "los"+ | "las"+ | "una"+ | "uno"+ | "con"+ | "sin"+ | "sus"+ | "mis"+ | "tus"+ | "nos"+ | "les"+ | "mas"+ | "muy"+ | "tan"+ | "que"+ | "son"+ | "fue"+ | "era"+ | "ser"+ | "hay"+ | "the"+ | "and"+ | "for"+ | "not"+ | "are"+ | "but"+ | "can"+ | "all"+ | "has"+ | "had"+ | "was"+ | "one"+ | "out"+ | "who"+ | "how"+ | "why"+ | "his"+ | "her"+ | "its"+ | "our"+ | "you"+ | "any"+ | "may"+ | "via"+ | "per"+ | "des"+ | "aux"+ | "par"+ | "sur"+ | "une"+ | "est"+ | "ses"+ | "vos"+ | "ils"+ | "pas"+ | "qui"+ | "der"+ | "die"+ | "das"+ | "den"+ | "dem"+ | "ein"+ | "und"+ | "mit"+ | "von"+ | "aus"+ | "bei"+ | "vor"+ | "zur"+ | "zum"+ | "wie"+ | "wir"+ | "sie"+ | "ich"+ | "uma"+ | "dos"+ | "nas"+ | "com"+ | "sem"+ | "seu"+ | "sua"+ | "nao"+ | "gli"+ | "nel"+ | "sul"+ | "col"+ | "tra"+ | "fra"+ | "che"+ | "non"+ | "piu"+ )+}++fn is_natural_language_glue_token(clean: &str) -> bool {+ if clean.is_empty() || clean.contains('_') {+ return false;+ }+ if !clean.chars().all(|c| c.is_alphabetic() && c.is_lowercase()) {+ return false;+ }+ let char_len = clean.chars().count();+ (char_len <= 2 && !is_two_letter_tech_term(clean)) || is_three_letter_glue_word(clean)+}++/// Normalize a plain-words `xerj search` query before expanding it into+/// `multi_match` / `match_phrase` / `term` clauses (#1364):+///+/// 1. Deduplicate tokens case-insensitively while preserving first-seen order+/// so a repeated word (`"de"` ×3) never gets 3× BM25 multiplication.+/// 2. When a query has 3+ distinct tokens, drop lowercase natural-language+/// glue tokens (`"de"`, `"el"`, `"la"`, `"en"`, `"the"`, `"of"`, `"in"`, …)+/// so short function/variable names like `de` or `in` on `name^4` / `title`+/// cannot outscore files matching the query's content words, and unrelated+/// questions that only share `"de"` do not collapse onto the same top hits.+/// Single-token queries (`xerj search de`) and 2-token queries keep all+/// tokens untouched, as do UPPERCASE/camelCase acronyms (`IO`, `DB`, `ID`)+/// and alphanumeric tokens (`v2`, `u8`, `o68`).+pub(crate) fn normalize_code_search_query(query: &str) -> String {+ let mut seen = Vec::<String>::new();+ let mut dedup = Vec::<&str>::new();+ for raw in query.split_whitespace() {+ let clean = raw.trim_matches(|c: char| !c.is_alphanumeric() && c != '_');+ if clean.is_empty() {+ continue;+ }+ let lower = clean.to_lowercase();+ if !seen.contains(&lower) {+ seen.push(lower);+ dedup.push(clean);+ }+ }+ if dedup.len() < 3 {+ return if dedup.is_empty() {+ query.trim().to_string()+ } else {+ dedup.join(" ")+ };+ }+ let content: Vec<&str> = dedup+ .iter()+ .copied()+ .filter(|tok| !is_natural_language_glue_token(tok))+ .collect();+ if content.is_empty() {+ dedup.join(" ")+ } else {+ content.join(" ")+ }+}++/// Build the ES search request body used by `xerj search`.+pub fn search_query_body(query: &str, k: usize) -> Value {+ let shaped = normalize_code_search_query(query);+ json!({+ "size": k,+ "query": { "bool": { "should": [+ { "multi_match": {+ "query": shaped,+ "fields": ["name^4", "code^2", "body", "defs^3", "title"],+ "type": "most_fields"+ }},+ { "match_phrase": { "defs": { "query": shaped, "boost": 8 } } },+ { "term": { "name": { "value": shaped, "boost": 10 } } }+ ]}},+ // No `body` here: whole-file bodies are the token flood (measured ~9x+ // the size of the matching passage). `_passage` carries the snippet.+ "_source": ["ax_path", "line", "start_line", "language", "kind", "code", "title"],+ "fields": ["_passage"]+ })+}+/// Entry point for the `search` subcommand. Returns a process exit code.pub fn run_search_cli() -> i32 {let mut url = std::env::var("XERJ_URL")@@ -137,22 +349,7 @@ pub fn run_search_cli() -> i32 {// simply contributes no score). `name` is a keyword field on symbol docs// (issue #500), so the `term` clause fires only when the whole query IS// the identifier — the strongest possible signal.- let body = json!({- "size": k,- "query": { "bool": { "should": [- { "multi_match": {- "query": query,- "fields": ["name^4", "defs^3", "code^2", "body", "title"],- "type": "most_fields"- }},- { "match_phrase": { "defs": { "query": query, "boost": 8 } } },- { "term": { "name": { "value": query, "boost": 10 } } }- ]}},- // No `body` here: whole-file bodies are the token flood (measured ~9x- // the size of the matching passage). `_passage` carries the snippet.- "_source": ["ax_path", "line", "start_line", "language", "kind", "code", "title"],- "fields": ["_passage"]- });+ let body = search_query_body(&query, k);let pattern = format!("{prefix}-*");let resp = match es.search(&pattern, &body) {@@ -232,3 +429,77 @@ pub fn run_search_cli() -> i32 {);0}++#[cfg(test)]+mod tests {+ use super::*;++ /// #1364: multi-word natural-language queries strip repeated/glue particles+ /// (`de`, `la`, `por`, `en`, `the`, `of`) so a 2-letter function named `de`+ /// cannot hijack `name^4`/`title` and unrelated questions do not return+ /// identical top hits, while single-identifier lookups (`de`), acronyms+ /// (`IO`, `WAL`), and 2-letter tech terms (`db`, `gc`, `tx`) are preserved.+ #[test]+ fn normalize_code_search_query_strips_multiword_glue_and_deduplicates() {+ assert_eq!(+ normalize_code_search_query(+ "factor de calibracion de la encuesta multiplicador de ponderacion"+ ),+ "factor calibracion encuesta multiplicador ponderacion"+ );+ assert_eq!(+ normalize_code_search_query("ponderacion de hogares por departamento en la encuesta"),+ "ponderacion hogares departamento encuesta"+ );+ assert_eq!(+ normalize_code_search_query("ingreso total del hogar correccion por inflacion"),+ "ingreso total hogar correccion inflacion"+ );+ // Single-token lookup for a function literally named `de` is untouched.+ assert_eq!(normalize_code_search_query("de"), "de");+ // Two-letter technical terms, uppercase acronyms, and alphanumeric tokens stay.+ assert_eq!(+ normalize_code_search_query("fsync the WAL segment on db tx rotation v2"),+ "fsync WAL segment db tx rotation v2"+ );+ assert_eq!(+ normalize_code_search_query("indicador de agua potable o68"),+ "indicador agua potable o68"+ );++ let body = search_query_body(+ "factor de calibracion de la encuesta multiplicador de ponderacion",+ 5,+ );+ assert_eq!(+ body["query"]["bool"]["should"][0]["multi_match"]["query"],+ "factor calibracion encuesta multiplicador ponderacion"+ );+ }++ /// #1364: if `_passage` came back from a bare identifier metadata field+ /// (`name` or `title`) on a symbol doc that carries `_source.code`,+ /// `passage_text` yields `None` so the caller falls back to `_source.code`+ /// (`de <- function(col)`) instead of printing bare `de`.+ #[test]+ fn passage_text_skips_bare_name_field_when_source_code_is_present() {+ let hit = json!({+ "_source": {+ "ax_path": "hogares_ech.R",+ "line": 1221,+ "kind": "function",+ "name": "de",+ "title": "de",+ "code": "de <- function(col)"+ },+ "fields": {+ "_passage": [{+ "field": "name",+ "ordinal": 0,+ "text": "de"+ }]+ }+ });+ assert_eq!(passage_text(&hit), None);+ }+}diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rsindex a880cd5bb..f752a99b4 100644--- a/engine/crates/xerj-engine/src/index.rs+++ b/engine/crates/xerj-engine/src/index.rs@@ -40121,6 +40121,26 @@ fn apply_lexical_passages(hits: Vec<Hit>, query: &QueryNode) -> Vec<Hit> {Vec::new();for spec in &field_specs {for (field_name, text) in collect_passage_field_texts(&hit.source, spec) {+ // `defs` and `name` are autoindex's synthetic symbol-list+ // and identifier fields whose actual source lives in `body`+ // (whole-file docs) or `code` (per-symbol docs). Ensure+ // `body` and `code` are candidates ahead of `defs` and+ // `name` even when a query lists `name^4` / `defs^3` first+ // (`xerj search` / `xerj def`, #1364).+ if matches!(field_name.as_str(), "defs" | "name") {+ for primary in ["body", "code"] {+ if !seen_fields.contains(primary) {+ for (primary_name, primary_text) in+ collect_passage_field_texts(&hit.source, primary)+ {+ if seen_fields.insert(primary_name.clone()) {+ let (lower, map) = build_lower_offset_map(&primary_text);+ candidates.push((primary_name, primary_text, lower, map));+ }+ }+ }+ }+ }if seen_fields.insert(field_name.clone()) {let (lower, map) = build_lower_offset_map(&text);candidates.push((field_name, text, lower, map));@@ -40156,26 +40176,29 @@ fn apply_lexical_passages(hits: Vec<Hit>, query: &QueryNode) -> Vec<Hit> {// `refine_code_passage` would usually force it back// to the tree root (the padding routinely spills// outside the enclosing function) and silently no-op- // the refinement. Anchor on one actual query-term- // occurrence inside the window instead — any point- // inside the matched region resolves to the same- // enclosing block. ASCII-lowercase only (not the- // Unicode-aware `lower`/`map` used above): it never- // changes byte length, so `pos` lines up with `text`- // without a second offset table; source identifiers+ // the refinement. Anchor on the highest-weight (rarest)+ // query-term occurrence inside the window (#1364) so a+ // common term in the leading context padding cannot pull+ // the AST refinement onto an adjacent block. ASCII-lowercase+ // only (not the Unicode-aware `lower`/`map` used above):+ // it never changes byte length, so `pos` lines up with+ // `text` without a second offset table; source identifiers// are ASCII in the overwhelming case, and a missed// non-ASCII anchor just skips the refinement, not a// correctness bug.- let (start, end) = weighted_terms- .iter()- .find_map(|&(term, _)| {- if term.is_empty() {- return None;- }- text.get(start..end)?- .to_ascii_lowercase()- .find(term)- .map(|pos| start + pos)+ let window_lower = text.get(start..end).map(str::to_ascii_lowercase);+ let (start, end) = window_lower+ .as_deref()+ .and_then(|win| {+ weighted_terms+ .iter()+ .enumerate()+ .filter(|(_, &(term, _))| !term.is_empty())+ .filter_map(|(idx, &(term, weight))| {+ win.find(term).map(|pos| (weight, idx, start + pos))+ })+ .max_by(|a, b| a.0.total_cmp(&b.0).then_with(|| b.1.cmp(&a.1)))+ .map(|(_, _, anchor)| anchor)}).and_then(|anchor| {let anchor_end = (anchor + 1).min(text.len());@@ -56463,6 +56486,121 @@ mod lexical_passage_tests {);}+ /// #1364: on a per-symbol code hit (`name: "de"`, `title: "de"`, `code:+ /// "de <- function(col)"`), `_passage` must come from `code` rather than+ /// the single-word `name` field; and when a multi-word query hits a+ /// whole-file document where a common glue token (`"de"`) appears in an+ /// adjacent function just above the rarer target token+ /// (`"factor_calibracion"`), `refine_code_passage` must anchor on the+ /// highest-weight matched query term in the window rather than the first+ /// alphabetically sorted term.+ #[test]+ fn code_lexical_passage_prefers_code_over_name_and_anchors_on_rarest_term() {+ // 1. Per-symbol hit: `code` wins over `name` and `title`.+ let symbol_source = serde_json::json!({+ "ax_path": "R/utils.R",+ "language": "r",+ "symbol_count": 1,+ "name": "de",+ "title": "de",+ "code": "de <- function(col) {\n trimws(col)\n}",+ });+ let symbol_query = QueryNode::MultiMatch {+ fields: vec![+ "name^4".into(),+ "defs^3".into(),+ "code^2".into(),+ "body".into(),+ "title".into(),+ ],+ query: "de".into(),+ match_type: Default::default(),+ operator: None,+ analyzer: None,+ boost: None,+ slop: 0,+ max_expansions: 50,+ lenient: false,+ };+ let symbol_hit = Hit {+ id: "sym-de".into(),+ score: 1.0,+ source: symbol_source,+ seq_no: None,+ version: None,+ sort: Vec::new(),+ explain: None,+ highlight: None,+ matched_queries: Vec::new(),+ passage: None,+ };+ let out = apply_lexical_passages(vec![symbol_hit], &symbol_query);+ let passage = out[0].passage.as_ref().expect("symbol passage filled");+ assert_eq!(passage.field, "code");+ assert!(+ passage.text.starts_with("de <- function(col)"),+ "expected function body from `code`, got {:?}",+ passage.text+ );++ // 2. Whole-file hit: common token `de` appears frequently across the+ // file and in an adjacent helper right above `pub fn compute_calibration`,+ // while `factor_calibracion` appears only inside `compute_calibration`.+ let mut body = String::new();+ for i in 0..25 {+ body.push_str(&format!("// comentario de relleno linea {i}\n"));+ }+ body.push_str(+ "pub fn helper_anterior() {\n // nota de control\n let x = 1;\n}\n\n\+ pub fn compute_calibration() -> f64 {\n let factor_calibracion = 0.85;\n factor_calibracion\n}\n",+ );+ let file_source = serde_json::json!({+ "ax_path": "src/calib.rs",+ "language": "rust",+ "symbol_count": 2,+ "defs": "helper_anterior compute_calibration",+ "title": "calib",+ "body": body,+ });+ let file_query = QueryNode::MultiMatch {+ fields: vec![+ "name^4".into(),+ "code^2".into(),+ "body".into(),+ "defs^3".into(),+ "title".into(),+ ],+ query: "de factor_calibracion".into(),+ match_type: Default::default(),+ operator: None,+ analyzer: None,+ boost: None,+ slop: 0,+ max_expansions: 50,+ lenient: false,+ };+ let file_hit = Hit {+ id: "file-calib".into(),+ score: 1.0,+ source: file_source,+ seq_no: None,+ version: None,+ sort: Vec::new(),+ explain: None,+ highlight: None,+ matched_queries: Vec::new(),+ passage: None,+ };+ let out = apply_lexical_passages(vec![file_hit], &file_query);+ let passage = out[0].passage.as_ref().expect("file passage filled");+ assert_eq!(passage.field, "body");+ assert!(+ passage.text.starts_with("pub fn compute_calibration"),+ "expected enclosing function of rarest matched term, got {:?}",+ passage.text+ );+ }+/// #174: a document that merely carries a field named `language` (not/// autoindex's code-extractor shape — no `symbol_count`) must keep the/// exact line-snapped window the lexical selector already computed.diff --git a/engine/crates/xerj-mcp/src/lib.rs b/engine/crates/xerj-mcp/src/lib.rsindex 7b2a0bba5..dc9ec280b 100644--- a/engine/crates/xerj-mcp/src/lib.rs+++ b/engine/crates/xerj-mcp/src/lib.rs@@ -1377,6 +1377,176 @@ fn apply_judge(Ok(())}+fn is_two_letter_tech_term(w: &str) -> bool {+ matches!(+ w,+ "db" | "ui"+ | "ux"+ | "ip"+ | "gc"+ | "vm"+ | "id"+ | "kv"+ | "ir"+ | "ci"+ | "pr"+ | "ai"+ | "ml"+ | "tx"+ | "rx"+ | "fs"+ | "fd"+ | "pk"+ | "fk"+ )+}++fn is_three_letter_glue_word(w: &str) -> bool {+ matches!(+ w,+ "del"+ | "por"+ | "los"+ | "las"+ | "una"+ | "uno"+ | "con"+ | "sin"+ | "sus"+ | "mis"+ | "tus"+ | "nos"+ | "les"+ | "mas"+ | "muy"+ | "tan"+ | "que"+ | "son"+ | "fue"+ | "era"+ | "ser"+ | "hay"+ | "the"+ | "and"+ | "for"+ | "not"+ | "are"+ | "but"+ | "can"+ | "all"+ | "has"+ | "had"+ | "was"+ | "one"+ | "out"+ | "who"+ | "how"+ | "why"+ | "his"+ | "her"+ | "its"+ | "our"+ | "you"+ | "any"+ | "may"+ | "via"+ | "per"+ | "des"+ | "aux"+ | "par"+ | "sur"+ | "une"+ | "est"+ | "ses"+ | "vos"+ | "ils"+ | "pas"+ | "qui"+ | "der"+ | "die"+ | "das"+ | "den"+ | "dem"+ | "ein"+ | "und"+ | "mit"+ | "von"+ | "aus"+ | "bei"+ | "vor"+ | "zur"+ | "zum"+ | "wie"+ | "wir"+ | "sie"+ | "ich"+ | "uma"+ | "dos"+ | "nas"+ | "com"+ | "sem"+ | "seu"+ | "sua"+ | "nao"+ | "gli"+ | "nel"+ | "sul"+ | "col"+ | "tra"+ | "fra"+ | "che"+ | "non"+ | "piu"+ )+}++fn is_natural_language_glue_token(clean: &str) -> bool {+ if clean.is_empty() || clean.contains('_') {+ return false;+ }+ if !clean.chars().all(|c| c.is_alphabetic() && c.is_lowercase()) {+ return false;+ }+ let char_len = clean.chars().count();+ (char_len <= 2 && !is_two_letter_tech_term(clean)) || is_three_letter_glue_word(clean)+}++/// Normalize a plain-words `xerj_search` query before expanding it into+/// `multi_match` / `match_phrase` / `term` clauses (#1364), matching+/// `xerj_autoindex::search::normalize_code_search_query`.+fn normalize_code_search_query(query: &str) -> String {+ let mut seen = Vec::<String>::new();+ let mut dedup = Vec::<&str>::new();+ for raw in query.split_whitespace() {+ let clean = raw.trim_matches(|c: char| !c.is_alphanumeric() && c != '_');+ if clean.is_empty() {+ continue;+ }+ let lower = clean.to_lowercase();+ if !seen.contains(&lower) {+ seen.push(lower);+ dedup.push(clean);+ }+ }+ if dedup.len() < 3 {+ return if dedup.is_empty() {+ query.trim().to_string()+ } else {+ dedup.join(" ")+ };+ }+ let content: Vec<&str> = dedup+ .iter()+ .copied()+ .filter(|tok| !is_natural_language_glue_token(tok))+ .collect();+ if content.is_empty() {+ dedup.join(" ")+ } else {+ content.join(" ")+ }+}+fn build_search(args: &Value) -> Result<BuiltRequest, String> {// #962: `index` used to be required, but nothing an agent reads said what// to pass — the first real tool call after `xerj autoindex` was an error@@ -1399,16 +1569,17 @@ fn build_search(args: &Value) -> Result<BuiltRequest, String> {// untouched for structured queries.Some(Value::String(q)) if !q.trim().is_empty() => {plain_string = true;+ let shaped = normalize_code_search_query(q);body.insert("query".into(),json!({ "bool": { "should": [{ "multi_match": {- "query": q,- "fields": ["name^4", "defs^3", "code^2", "body", "title"],+ "query": shaped,+ "fields": ["name^4", "code^2", "body", "defs^3", "title"],"type": "most_fields"}},- { "match_phrase": { "defs": { "query": q, "boost": 8 } } },- { "term": { "name": { "value": q, "boost": 10 } } }+ { "match_phrase": { "defs": { "query": shaped, "boost": 8 } } },+ { "term": { "name": { "value": shaped, "boost": 10 } } }]}}),);}@@ -1984,6 +2155,27 @@ mod tests {assert_eq!(path, "/docs/_search");}+ #[test]+ fn search_plain_string_strips_multiword_glue_tokens_and_preserves_single_word() {+ let (_, _, body) = built(build_search(&json!({+ "query": "factor de calibracion de margen de seguridad"+ })));+ assert_eq!(+ body["query"]["bool"]["should"][0]["multi_match"]["query"],+ "factor calibracion margen seguridad"+ );+ assert_eq!(+ body["query"]["bool"]["should"][0]["multi_match"]["fields"],+ json!(["name^4", "code^2", "body", "defs^3", "title"])+ );++ let (_, _, single) = built(build_search(&json!({ "query": "de" })));+ assert_eq!(+ single["query"]["bool"]["should"][0]["multi_match"]["query"],+ "de"+ );+ }+#[test]fn plan_posts_prompt_to_ask_with_default_index() {// #1056: the proxy carries exactly the two arguments; the planner