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
feat(autoindex,common): index symbol impl bodies and fuse with file hits via RRF (#1237)
Christian M. Todie5c29cc2545db
diff --git a/engine/crates/xerj-autoindex/src/extract/code.rs b/engine/crates/xerj-autoindex/src/extract/code.rsindex 52f7ac599..15e338617 100644--- a/engine/crates/xerj-autoindex/src/extract/code.rs+++ b/engine/crates/xerj-autoindex/src/extract/code.rs@@ -1395,6 +1395,8 @@ fn emit_code_doc(// So dedup by locator here, BEFORE counting/emitting — do not rely on the// downstream `_id` overwrite (which fixes the doc but not the count).let mut emitted_locators = std::collections::HashSet::new();+ let lines: Vec<&str> = text.lines().collect();+ const IMPL_CAP: usize = 16_384;for s in symbols {if s.code.is_empty() {continue;@@ -1414,14 +1416,52 @@ fn emit_code_doc(sf.insert("name".into(), Value::String(name.clone()));sf.insert("kind".into(), Value::String(s.kind.clone()));sf.insert("line".into(), Value::Number((line as u64).into()));+ sf.insert(+ "end_line".into(),+ Value::Number((s.end_line.max(line) as u64).into()),+ );sf.insert("code".into(), Value::String(s.code.clone()));- // No field beyond the five #579 froze: a NEW scalar field on this- // document would make `reconcile_plan::ensure_compatible` (see- // reconcile_plan.rs, "field {name} is absent from frozen dataset")- // abort the next incremental run over an index an older binary froze.- // `end_line` therefore rides in the file document's `symbols` array,- // which that check exempts because an array carries no scalar- // observations (the #580/#581 rule).+ // #1237: symbol records carry a bounded `impl` slice (`body[line..=end_line]`,+ // capped at 16 KB on a UTF-8 char boundary) so `xerj code --fuse-symbols`+ // can score a second BM25 leg over definition bodies without length-norm+ // dilution from a 4,000-line file. For container kinds (`class`), bound+ // `impl` to the lines preceding the first nested definition so method+ // bodies are not duplicated inside the enclosing class record.+ // `reconcile_plan::ensure_compatible` exempts `impl` and `end_line` on+ // pre-#1237 frozen datasets so incremental runs over older state dirs+ // never abort.+ let impl_end_line = if s.kind == "class" {+ symbols+ .iter()+ .filter(|child| child.line > line && child.line <= s.end_line)+ .map(|child| child.line.saturating_sub(1).max(line))+ .min()+ .unwrap_or(s.end_line.max(line))+ } else {+ s.end_line.max(line)+ };+ if s.end_line > line+ || matches!(+ s.kind.as_str(),+ "function" | "method" | "class" | "macro" | "struct" | "enum" | "trait" | "impl"+ )+ {+ let lo = line.saturating_sub(1).min(lines.len());+ let hi = impl_end_line.min(lines.len()).max(lo);+ if hi > lo {+ let mut impl_slice = lines[lo..hi].join("\n");+ if impl_slice.len() > IMPL_CAP {+ let mut cut = IMPL_CAP;+ while cut > 0 && !impl_slice.is_char_boundary(cut) {+ cut -= 1;+ }+ impl_slice.truncate(cut);+ }+ if !impl_slice.is_empty() {+ sf.insert("impl".into(), Value::String(impl_slice));+ }+ }+ }stats.records += 1;if !sink(RawRecord {fields: sf,@@ -4442,4 +4482,46 @@ mod tests {Some("0".to_string()));}++ #[test]+ fn emit_code_doc_records_symbol_impl_and_bounds_class_before_methods() {+ let mut records = Vec::new();+ let mut stats = ExtractStats::default();+ let src =+ "class Widget:\n kind = 'box'\n def render(self):\n return self.kind\n";+ let s = syms("python", src);+ let ok = emit_code_doc(+ Path::new("widget.py"),+ "python",+ src,+ &s,+ &mut stats,+ &mut |rec| {+ records.push(rec);+ true+ },+ );+ assert!(ok);+ let class_rec = records+ .iter()+ .find(|r| r.locator == "code:1:Widget")+ .expect("Widget symbol record");+ assert_eq!(+ class_rec.fields.get("impl").and_then(Value::as_str),+ Some("class Widget:\n kind = 'box'"),+ "class impl stops before nested method definition so method bodies are not duplicated"+ );+ let method_rec = records+ .iter()+ .find(|r| r.locator == "code:3:render")+ .expect("render symbol record");+ assert_eq!(+ method_rec.fields.get("impl").and_then(Value::as_str),+ Some(" def render(self):\n return self.kind")+ );+ assert_eq!(+ method_rec.fields.get("end_line").and_then(Value::as_u64),+ Some(4)+ );+ }}diff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rsindex 5b62320ba..0be397309 100644--- a/engine/crates/xerj-autoindex/src/lib.rs+++ b/engine/crates/xerj-autoindex/src/lib.rs@@ -407,6 +407,19 @@ fn install_dataset_mappings(fn dataset_create_body(dataset: &PlanDataset) -> Value {let mut create_body = build_mapping(&dataset.specs);create_body["mappings"]["properties"]["ax_paths"] = json!({"type": "keyword"});+ if dataset.family == "docs" || dataset.family == "code" {+ if let Some(props) = create_body+ .pointer_mut("/mappings/properties")+ .and_then(Value::as_object_mut)+ {+ props+ .entry("impl".to_string())+ .or_insert_with(|| json!({"type": "text"}));+ props+ .entry("end_line".to_string())+ .or_insert_with(|| json!({"type": "long"}));+ }+ }if let Some(analyzer) = &dataset.text_analyzer {create_body["settings"] = json!({"analysis": {"analyzer": {"default": {"type": analyzer}diff --git a/engine/crates/xerj-autoindex/src/reconcile_plan.rs b/engine/crates/xerj-autoindex/src/reconcile_plan.rsindex db7577d55..07f50b6a6 100644--- a/engine/crates/xerj-autoindex/src/reconcile_plan.rs+++ b/engine/crates/xerj-autoindex/src/reconcile_plan.rs@@ -636,8 +636,15 @@ fn ensure_compatible(fields: &HashMap<String, FieldAcc>, dataset: &PlanDataset)// (#580), because `symbols` is observed on every generation but was// pruned from the frozen schema. A field that DOES carry scalar// values yet is absent is still a real incompatibility.+ //+ // #1237: `impl` and `end_line` on symbol records were added after+ // #579 froze the five symbol scalar fields; tolerate their absence+ // on pre-#1237 frozen `docs`/`code` datasets so incremental runs+ // over existing state dirs do not abort.+ let pre_1237_symbol_field = (name == "impl" || name == "end_line")+ && (dataset.family == "docs" || dataset.family == "code");anyhow::ensure!(- acc.n == 0,+ acc.n == 0 || pre_1237_symbol_field,"field {name} is absent from frozen dataset {}",dataset.slug);diff --git a/engine/crates/xerj-autoindex/src/xc.rs b/engine/crates/xerj-autoindex/src/xc.rsindex 9dc8200cd..4c1bd57b8 100644--- a/engine/crates/xerj-autoindex/src/xc.rs+++ b/engine/crates/xerj-autoindex/src/xc.rs@@ -112,8 +112,8 @@ fn emit(out: &CodeOutcome) {const CODE_USAGE: &str ="usage: xerj code <corpus> \"<what you need>\" [-k N] [--mode bm25|semantic|hybrid]- [--hybrid] [--lang <lg>] [--full N] [--no-symbol] [--json] [--meatl] [--stale-ok]- [--url URL] [--api-key KEY]+ [--hybrid] [--lang <lg>] [--full N] [--no-symbol] [--fuse-symbols]+ [--json] [--meatl] [--stale-ok] [--url URL] [--api-key KEY]retrieval over a reference corpus (see `xerj corpus list`):-k N passages to return (default 5)@@ -122,6 +122,7 @@ retrieval over a reference corpus (see `xerj corpus list`):--lang LG filter to one language field (e.g. rust, go)--full N max chars per passage (default 800; 0 = file head only)--no-symbol window selection instead of the matching definition+ --fuse-symbols fuse file-level BM25 with symbol-impl BM25 by RRF(k=60)--json raw server response on stdout--meatl machine-readable one-line-per-hit output--stale-ok override the 30-day staleness refusal@@ -183,6 +184,7 @@ pub fn run_code_cli(args: &[String]) -> i32 {}}"--no-symbol" => p.no_symbol = true,+ "--fuse-symbols" => p.fuse_symbols = true,"--json" => p.as_json = true,"--meatl" => p.meatl = true,"--stale-ok" => p.stale_ok = true,diff --git a/engine/crates/xerj-common/src/xccode/fields.rs b/engine/crates/xerj-common/src/xccode/fields.rsindex 89417e0f6..bdce6fc47 100644--- a/engine/crates/xerj-common/src/xccode/fields.rs+++ b/engine/crates/xerj-common/src/xccode/fields.rs@@ -192,7 +192,10 @@ fn own_text_fields(obj: &serde_json::Map<String, Value>, min_indices: usize) ->.get("type").and_then(Value::as_str).is_some_and(|t| t == "text" || t == "semantic_text");- if searchable && !key.starts_with(AX) {+ // #1237: `impl` is the symbol-record implementation field queried+ // by its own dedicated BM25 leg under `--fuse-symbols`; never fold+ // it into the file-level `multi_match` over `body`/`defs`/`title`.+ if searchable && !key.starts_with(AX) && key != "impl" {*counts.entry(key.clone()).or_insert(0) += 1;}}@@ -233,6 +236,7 @@ fn own_recall_legs(obj: &serde_json::Map<String, Value>, min_union_indices: usiz.iter().filter(|(key, spec)| {!key.starts_with("ax_")+ && *key != "impl"&& spec.get("type").and_then(Value::as_str)@@ -264,6 +268,19 @@ fn own_recall_legs(obj: &serde_json::Map<String, Value>, min_union_indices: usiz.collect()}+/// Whether at least one index under the prefix maps the symbol-record `impl`+/// field (#1237) as searchable text (`text` or `semantic_text`).+pub fn has_symbol_impl(mapping: Option<&Value>) -> bool {+ let Some(mapping) = mapping.and_then(Value::as_object) else {+ return false;+ };+ mapping.values().any(|m| {+ m.pointer("/mappings/properties/impl/type")+ .and_then(Value::as_str)+ .is_some_and(|t| t == "text" || t == "semantic_text")+ })+}+/// Indices under the prefix whose `field` (default `body`) is mapped as/// `semantic_text`.///@@ -693,4 +710,17 @@ mod tests {assert_eq!(got.first().unwrap(), "body");assert_eq!(got.len(), 1 + 24 - 1); // body full-weight + 23 own legs}++ #[test]+ fn symbol_impl_is_detected_and_excluded_from_file_leg_fields() {+ let m = mapping(&[("xc-code-000", &["body", "defs", "title", "impl"], false)]);+ assert!(has_symbol_impl(Some(&m)));+ assert_eq!(+ resolve_fields(Some(&m)),+ vec!["body".to_string(), "defs".into(), "title".into()],+ "impl is queried by its own BM25 leg under --fuse-symbols, never folded into file multi_match"+ );+ let no_impl = mapping(&[("xc-code-000", &["body", "defs", "title"], false)]);+ assert!(!has_symbol_impl(Some(&no_impl)));+ }}diff --git a/engine/crates/xerj-common/src/xccode/mod.rs b/engine/crates/xerj-common/src/xccode/mod.rsindex 9a1d1f2c7..90f032375 100644--- a/engine/crates/xerj-common/src/xccode/mod.rs+++ b/engine/crates/xerj-common/src/xccode/mod.rs@@ -90,6 +90,9 @@ pub struct CodeParams {/// issue #368, so this is a cap, never an opt-out).pub full: usize,pub no_symbol: bool,+ /// #1237: opt-in second BM25 leg over symbol-record `impl` fields, fused+ /// with file-level BM25 at the file level by RRF(k=60).+ pub fuse_symbols: bool,pub stale_ok: bool,pub meatl: bool,/// CLI `--json`: raw server response on stdout. MCP never sets this.@@ -110,6 +113,7 @@ impl CodeParams {mode: Mode::Bm25,full: 800,no_symbol: false,+ fuse_symbols: false,stale_ok: false,meatl: false,as_json: false,@@ -273,7 +277,30 @@ pub fn run_code_query(let (mut resp, hits) = match params.mode {Mode::Bm25 => match http.search(&pattern, &bm25_body(&query, fetch, ¶ms.lang, &fields)){- Ok(r) => (r.clone(), hit_list(&r)),+ Ok(mut r) => {+ let mut h = hit_list(&r);+ if params.fuse_symbols+ && !params.no_symbol+ && fields::has_symbol_impl(mapping.as_ref())+ {+ if let Ok(sym_resp) =+ http.search(&pattern, &symbol_bm25_body(&query, fetch, ¶ms.lang))+ {+ let sym_hits = hit_list(&sym_resp);+ if !sym_hits.is_empty() {+ h = fuse_file_and_symbol_hits(http, &pattern, h, sym_hits, fetch);+ if let Some(hits_arr) =+ r.pointer_mut("/hits/hits").and_then(Value::as_array_mut)+ {+ *hits_arr = h.clone();+ }+ rrf_scores = true;+ note = Some(format!("BM25 file+symbol RRF(k={RRF_K})"));+ }+ }+ }+ (r, h)+ }Err(e) => return CodeOutcome::refused(format!("search failed: {e}"), 2),},Mode::Semantic => {@@ -629,6 +656,234 @@ pub(crate) fn bm25_body(query: &str, k: usize, lang: &Option<String>, fields: &[serde_json::json!({ "size": k, "query": { "bool": { "must": must } } })}+/// #1237: second BM25 leg over symbol-record `impl` fields. Excludes `impl`+/// and `body` from `_source` so the symbol leg never transfers symbol body+/// text over the wire — only provenance (`ax_path`, `ax_file`, `path`) and+/// the winning symbol span (`name`, `kind`, `line`, `end_line`).+pub(crate) fn symbol_bm25_body(query: &str, k: usize, lang: &Option<String>) -> Value {+ let mut must = vec![serde_json::json!({+ "multi_match": { "query": query, "fields": ["impl"] }+ })];+ if let Some(lg) = lang {+ must.push(serde_json::json!({ "match": { "language": lg } }));+ }+ serde_json::json!({+ "size": k,+ "_source": { "excludes": ["impl", "body"] },+ "query": { "bool": { "must": must } }+ })+}++fn hit_file_key(hit: &Value) -> Option<String> {+ hit.pointer("/_source/ax_path")+ .and_then(Value::as_str)+ .or_else(|| hit.pointer("/_source/ax_file").and_then(Value::as_str))+ .or_else(|| hit.pointer("/_source/path").and_then(Value::as_str))+ .filter(|s| !s.is_empty())+ .map(str::to_owned)+}++/// #1237: roll both BM25 legs up to the file level first (each file gets its+/// best 1-indexed file-leg rank and its best 1-indexed symbol-leg rank so a+/// file with ten matching functions does not get ten RRF votes), fuse by+/// `1 / (60 + rank_file) + 1 / (60 + rank_sym)`, and stamp the winning+/// symbol's `line..=end_line` onto `_source.symbols` for passage selection.+pub(crate) fn fuse_file_and_symbol_hits(+ http: &impl XcHttp,+ pattern: &str,+ file_hits: Vec<Value>,+ sym_hits: Vec<Value>,+ limit: usize,+) -> Vec<Value> {+ struct FileEntry {+ file_rank: Option<usize>,+ sym_rank: Option<usize>,+ file_hit: Option<Value>,+ sym_hit: Option<Value>,+ win_sym: Option<(String, String, i64, Option<i64>)>,+ }++ let mut by_file: HashMap<String, FileEntry> = HashMap::new();+ let mut unkeyed: Vec<Value> = Vec::new();+ let mut next_file_rank = 0usize;++ for hit in file_hits {+ let Some(key) = hit_file_key(&hit) else {+ unkeyed.push(hit);+ continue;+ };+ let has_body = hit+ .pointer("/_source/body")+ .and_then(Value::as_str)+ .is_some();+ let entry = by_file.entry(key).or_insert_with(|| {+ next_file_rank += 1;+ FileEntry {+ file_rank: Some(next_file_rank),+ sym_rank: None,+ file_hit: None,+ sym_hit: None,+ win_sym: None,+ }+ });+ if entry.file_hit.is_none()+ || (has_body+ && entry+ .file_hit+ .as_ref()+ .and_then(|h| h.pointer("/_source/body"))+ .and_then(Value::as_str)+ .is_none())+ {+ entry.file_hit = Some(hit);+ }+ }++ let mut next_sym_rank = 0usize;+ for hit in sym_hits {+ let Some(key) = hit_file_key(&hit) else {+ continue;+ };+ let sym_span = hit.get("_source").and_then(|src| {+ let name = src.get("name")?.as_str()?.to_string();+ let line = src.get("line")?.as_i64()?;+ let kind = src+ .get("kind")+ .and_then(Value::as_str)+ .unwrap_or("")+ .to_string();+ let end_line = src+ .get("end_line")+ .and_then(Value::as_i64)+ .filter(|&e| e >= line);+ Some((name, kind, line, end_line))+ });+ let entry = by_file.entry(key).or_insert_with(|| FileEntry {+ file_rank: None,+ sym_rank: None,+ file_hit: None,+ sym_hit: None,+ win_sym: None,+ });+ if entry.sym_rank.is_none() {+ next_sym_rank += 1;+ entry.sym_rank = Some(next_sym_rank);+ entry.sym_hit = Some(hit);+ entry.win_sym = sym_span;+ }+ }++ let mut ranked: Vec<(String, f64, usize, FileEntry)> = by_file+ .into_iter()+ .map(|(key, entry)| {+ let f_score = entry+ .file_rank+ .map(|r| 1.0 / (RRF_K as f64 + r as f64))+ .unwrap_or(0.0);+ let s_score = entry+ .sym_rank+ .map(|r| 1.0 / (RRF_K as f64 + r as f64))+ .unwrap_or(0.0);+ let best_rank = entry+ .file_rank+ .unwrap_or(usize::MAX)+ .min(entry.sym_rank.unwrap_or(usize::MAX));+ (key, f_score + s_score, best_rank, entry)+ })+ .collect();++ ranked.sort_by(|a, b| {+ b.1.total_cmp(&a.1)+ .then_with(|| a.2.cmp(&b.2))+ .then_with(|| a.0.cmp(&b.0))+ });+ ranked.truncate(limit);++ let mut out = Vec::with_capacity(ranked.len());+ for (key, score, _, mut entry) in ranked {+ let has_body = entry+ .file_hit+ .as_ref()+ .and_then(|h| h.pointer("/_source/body"))+ .and_then(Value::as_str)+ .is_some();+ if !has_body {+ // File entered via the symbol leg alone: fetch its file record so+ // passage selection has `body` to slice.+ let lookup = serde_json::json!({+ "size": 1,+ "query": {+ "bool": {+ "must": [+ { "exists": { "field": "body" } },+ { "match_phrase": { "ax_path": key } }+ ]+ }+ }+ });+ let target = entry+ .sym_hit+ .as_ref()+ .and_then(|h| h.get("_index"))+ .and_then(Value::as_str)+ .unwrap_or(pattern);+ if let Ok(resp) = http.search(target, &lookup) {+ if let Some(fetched) = hit_list(&resp)+ .into_iter()+ .find(|h| hit_file_key(h).as_deref() == Some(key.as_str()))+ {+ entry.file_hit = Some(fetched);+ }+ }+ }+ let Some(mut hit) = entry.file_hit.or(entry.sym_hit) else {+ continue;+ };+ if let Some((name, kind, line, end_line)) = entry.win_sym {+ if let Some(src) = hit.get_mut("_source").and_then(Value::as_object_mut) {+ let syms = src+ .entry("symbols")+ .or_insert_with(|| Value::Array(Vec::new()));+ if let Some(arr) = syms.as_array_mut() {+ let mut updated = false;+ for s in arr.iter_mut() {+ if s.get("name").and_then(Value::as_str) == Some(name.as_str())+ && s.get("line").and_then(Value::as_i64) == Some(line)+ {+ if let (Some(obj), Some(end)) = (s.as_object_mut(), end_line) {+ obj.insert("end_line".to_string(), serde_json::json!(end));+ }+ updated = true;+ break;+ }+ }+ if !updated {+ let mut sym_obj = serde_json::Map::new();+ sym_obj.insert("name".to_string(), Value::String(name));+ sym_obj.insert("kind".to_string(), Value::String(kind));+ sym_obj.insert("line".to_string(), serde_json::json!(line));+ if let Some(end) = end_line {+ sym_obj.insert("end_line".to_string(), serde_json::json!(end));+ }+ arr.push(Value::Object(sym_obj));+ }+ }+ }+ }+ if let Some(obj) = hit.as_object_mut() {+ obj.insert("_score".to_string(), serde_json::json!(score));+ }+ out.push(hit);+ }+ for hit in unkeyed {+ if out.len() >= limit {+ break;+ }+ out.push(hit);+ }+ out+}+/// The vector-only body. Aimed ONLY at indices whose `body` is semantic_text/// (a semantic query against plain text 400s the whole wildcard).///@@ -1500,4 +1755,91 @@ mod tests {.collect();assert_eq!(files, vec!["file1", "fileX"], "fileX's slot was not burned");}++ #[test]+ fn fuse_file_and_symbol_hits_rolls_up_per_file_and_stamps_winning_symbol_span() {+ struct NoopHttp;+ impl XcHttp for NoopHttp {+ fn get_mapping(&self, _: &str) -> Result<Value, String> {+ Err("unused".into())+ }+ fn cat_indices_json(&self, _: &str) -> Result<Vec<String>, String> {+ Ok(vec![])+ }+ fn search(&self, _: &str, _: &Value) -> Result<Value, String> {+ Ok(serde_json::json!({ "hits": { "hits": [] } }))+ }+ }++ // File leg ranks monolith.rs #1 and Target.rs #2; symbol leg ranks two+ // functions in Target.rs at #1 and #2 (must roll up to ONE vote at+ // rank 1, not two votes) and monolith.rs absent from symbol leg.+ // RRF(k=60):+ // Target.rs = 1/(60+2) + 1/(60+1) = 1/62 + 1/61 = 0.032522...+ // monolith.rs = 1/(60+1) + 0 = 1/61 = 0.016393...+ let file_hits = vec![+ serde_json::json!({+ "_index": "xc-test-000",+ "_score": 12.0,+ "_source": {+ "ax_path": "src/monolith.rs",+ "ax_file": "src/monolith.rs",+ "body": "fn big() {}\n",+ "symbols": [{ "name": "big", "kind": "function", "line": 1 }]+ }+ }),+ serde_json::json!({+ "_index": "xc-test-000",+ "_score": 9.0,+ "_source": {+ "ax_path": "src/target.rs",+ "ax_file": "src/target.rs",+ "body": "fn helper() {\n let x = 1;\n}\n",+ "symbols": [{ "name": "helper", "kind": "function", "line": 1 }]+ }+ }),+ ];+ let sym_hits = vec![+ serde_json::json!({+ "_index": "xc-test-000",+ "_score": 18.0,+ "_source": {+ "ax_path": "src/target.rs",+ "ax_file": "src/target.rs",+ "name": "helper",+ "kind": "function",+ "line": 1,+ "end_line": 3+ }+ }),+ serde_json::json!({+ "_index": "xc-test-000",+ "_score": 17.0,+ "_source": {+ "ax_path": "src/target.rs",+ "ax_file": "src/target.rs",+ "name": "second_fn",+ "kind": "function",+ "line": 10,+ "end_line": 15+ }+ }),+ ];+ let fused = fuse_file_and_symbol_hits(&NoopHttp, "xc-test*", file_hits, sym_hits, 5);+ assert_eq!(fused.len(), 2);+ assert_eq!(+ fused[0].pointer("/_source/ax_path").and_then(Value::as_str),+ Some("src/target.rs")+ );+ let expected_rrf = 1.0 / 62.0 + 1.0 / 61.0;+ let got_score = fused[0].get("_score").and_then(Value::as_f64).unwrap();+ assert!((got_score - expected_rrf).abs() < 1e-12);+ assert_eq!(+ fused[0]+ .pointer("/_source/symbols/0/end_line")+ .and_then(Value::as_i64),+ Some(3),+ "winning symbol end_line stamped onto file record's symbols entry"+ );+ }}diff --git a/engine/crates/xerj-common/src/xccode/passage.rs b/engine/crates/xerj-common/src/xccode/passage.rsindex c9217ed15..312067a4f 100644--- a/engine/crates/xerj-common/src/xccode/passage.rs+++ b/engine/crates/xerj-common/src/xccode/passage.rs@@ -38,13 +38,13 @@ pub fn query_terms(query: &str) -> Vec<String> {}/// `[(name, kind, start_line, end_line)]` from the record's own `symbols`.-/// A definition runs until the next definition starts — a coarse but honest-/// bound: it never claims a range the index did not report.+/// Uses recorded `end_line` when present (#1237); otherwise falls back to+/// running until the next definition starts.fn symbol_spans(src: &Value) -> Vec<(String, String, i64, Option<i64>)> {let Some(syms) = src.get("symbols").and_then(Value::as_array) else {return Vec::new();};- let mut got: Vec<(String, String, i64)> = syms+ let mut got: Vec<(String, String, i64, Option<i64>)> = syms.iter().filter(|s| s.is_object()).filter_map(|s| {@@ -53,6 +53,10 @@ fn symbol_spans(src: &Value) -> Vec<(String, String, i64, Option<i64>)> {if name.is_empty() {return None;}+ let end_line = s+ .get("end_line")+ .and_then(Value::as_i64)+ .filter(|&e| e >= line);Some((name.to_string(),s.get("kind")@@ -60,19 +64,23 @@ fn symbol_spans(src: &Value) -> Vec<(String, String, i64, Option<i64>)> {.unwrap_or("").to_string(),line,+ end_line,))}).collect();- got.sort_by_key(|(_, _, line)| *line);+ got.sort_by_key(|(_, _, line, _)| *line);got.windows(2).map(|w| {- let (name, kind, line) = w[0].clone();- let end = w.get(1).map(|(_, _, l)| *l - 1);+ let (name, kind, line, end_line) = w[0].clone();+ let end = end_line.or_else(|| w.get(1).map(|(_, _, l, _)| *l - 1));(name, kind, line, end)}).collect::<Vec<_>>().into_iter()- .chain(got.last().map(|(n, k, l)| (n.clone(), k.clone(), *l, None)))+ .chain(+ got.last()+ .map(|(n, k, l, end_line)| (n.clone(), k.clone(), *l, *end_line)),+ ).collect()}@@ -373,4 +381,18 @@ mod tests {assert_eq!(commaus(21_461), "21,461");assert_eq!(commaus(1_234_567), "1,234,567");}++ #[test]+ fn symbol_passage_bounds_span_by_recorded_end_line() {+ let body = "fn alpha() {\n let needle = 1;\n}\n// trailing comment mentioning needle needle needle\nfn beta() {}\n";+ let src = json!({+ "symbols": [+ { "name": "alpha", "kind": "function", "line": 1, "end_line": 3 },+ { "name": "beta", "kind": "function", "line": 5, "end_line": 5 }+ ]+ });+ let (text, label) = symbol_passage(body, &src, "needle", 800).unwrap();+ assert_eq!(label, "function alpha @ line 1");+ assert_eq!(text, "fn alpha() {\n let needle = 1;\n}");+ }}