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(mcp): cite the matched source line on xerj_search hits (#2269)
xerj-orgdfab1d7f4720
diff --git a/AGENTS.md b/AGENTS.mdindex c17e054cd..3e3b32db9 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -181,7 +181,10 @@ each a *thin proxy*: they build exactly the request the ES-compatible surface al(`xerj_plan` is `POST /_ask`, the deterministic rule-based planner) and hand backwhatever the engine returned, errors and refusals verbatim — no capability oftheir own, so anything you can do over MCP you can also do with `curl`, and vice-versa. `xerj_map` (#1055) reads the autoindex catalog and returns its per-index+versa. `xerj_search` adds `match_line` and capped `match_lines` on each hit: the+absolute 1-based source line of the best-scoring query term inside the passage.+Cite `ax_path:match_line`. Both fields are omitted when no term is located or the+passage start line is unknown. `start_line` stays the passage start. `xerj_map` (#1055) reads the autoindex catalog and returns its per-indexfield map, trimmed to a byte cap but otherwise verbatim. `xerj_code_search`(#977) is deliberately not a thin proxy: it runsthe `xerj code` reference-coding pipeline ([`tools/xerj-code/`](tools/xerj-code/))diff --git a/engine/crates/xerj-autoindex/src/search.rs b/engine/crates/xerj-autoindex/src/search.rsindex 58d89d5f0..97c36efe7 100644--- a/engine/crates/xerj-autoindex/src/search.rs+++ b/engine/crates/xerj-autoindex/src/search.rs@@ -193,6 +193,15 @@ pub(crate) fn hit_location(hit: &Value) -> String {.or_else(|| src.get("path")).and_then(Value::as_str).unwrap_or("?");+ // #2266: the line of the matched term, when the response was annotated.+ // `start_line` / `line` stay the passage or declaration start.+ if let Some(n) = hit+ .get("match_line")+ .and_then(Value::as_u64)+ .filter(|n| *n > 0)+ {+ return xerj_common::xccode::passage::cite_path_line(path, n);+ }if let Some(n) = src.get("line").or_else(|| src.get("start_line"))@@ -793,6 +802,10 @@ pub fn run_search_cli() -> i32 {if let Some(hits) = resp.pointer_mut("/hits/hits").and_then(Value::as_array_mut) {rank_plain_search_hits(hits, code_corpus, k);}+ // Same annotation `xerj_search` adds (#2266), so `--json` and the printed+ // header cite the matched line. `xerj code --json` is the raw server+ // body and does not share this hit post-pass.+ xerj_common::xccode::passage::annotate_search_match_lines(&mut resp, &query);if as_json {println!("{}",@@ -1275,6 +1288,30 @@ mod tests {assert_eq!(hit_location(&hit), "guide.md:169");}+ /// #2266: once the response carries `match_line`, the header cites that+ /// line. `start_line` stays the passage start for hits that have no match.+ #[test]+ fn hit_location_cites_match_line_ahead_of_the_passage_start() {+ let mut hit = json!({+ "_source": {+ "ax_path": "guide.md",+ "ax_locator": "s2",+ "start_line": 169+ },+ "fields": { "_passage": [{+ "field": "body",+ "ordinal": 0,+ "text": "Intro.\nThe token is required when unbound."+ }] }+ });+ assert_eq!(hit_location(&hit), "guide.md:169");+ let mut resp = json!({ "hits": { "hits": [hit] } });+ xerj_common::xccode::passage::annotate_search_match_lines(&mut resp, "unbound");+ hit = resp["hits"]["hits"][0].clone();+ assert_eq!(hit["match_line"], 170);+ assert_eq!(hit_location(&hit), "guide.md:170");+ }+/// #1934: two JSONL rows both printed as `xerj-prs.jsonl:1` because the/// passage ordinal counts lines inside the row's own `body`. A data row/// is cited by its locator; whole files, code and sections keep lines.diff --git a/engine/crates/xerj-common/src/xccode/passage.rs b/engine/crates/xerj-common/src/xccode/passage.rsindex 37355a992..8f7d20e89 100644--- a/engine/crates/xerj-common/src/xccode/passage.rs+++ b/engine/crates/xerj-common/src/xccode/passage.rs@@ -8,7 +8,7 @@//! `{name, kind, line}` for every definition; using them turns a guess into//! a lookup.-use serde_json::Value;+use serde_json::{json, Value};/// Query terms: identifiers of >= 3 chars (`[A-Za-z_][A-Za-z0-9_]{2,}`)./// Hand-rolled scanner — the ASCII class is the contract, and it must stop@@ -293,6 +293,471 @@ pub(crate) fn commaus(n: usize) -> String {out}+// ── match line (#2266) ──────────────────────────────────────────────────────+//+// `start_line` is the first line of the passage (or of the section the+// passage was cut from). Agents asked to cite `file:line` were counting+// lines inside the snippet by hand. `match_line` is the absolute 1-based+// source line of the best-scoring query term in that snippet.++/// How many matched lines `match_lines` keeps. The best line is always one+/// of them: when more lines match, the highest scores stay (ties keep the+/// earlier line) and the survivors are written back in source order.+pub const MATCH_LINES_CAP: usize = 8;++/// Absolute source lines of the query terms inside one passage.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct MatchedLines {+ /// Best-scoring line. Equal scores take the earliest line.+ pub match_line: u64,+ /// Every matched line, source order, at most [`MATCH_LINES_CAP`].+ pub match_lines: Vec<u64>,+}++/// Locate query terms in `passage` and report absolute source lines.+///+/// `origin_line` is the 1-based file line of `passage`'s first line.+/// `terms` are already lowercased (as [`query_terms`] emits them). Matching+/// is case-insensitive and whole-word: a character continues a word when it+/// is alphanumeric or `_`, the same boundary the highlighter uses+/// (`is_word_char` / `next_term_match` in+/// `engine/crates/xerj-engine/src/index.rs`). A line's score sums, per term,+/// `occurrences * 1/(1+n)²` where `n` is how often that term occurs in the+/// passage — the rarity weight `select_lexical_passage` uses so a repeated+/// function word cannot outrank one distinctive hit+/// (`engine/crates/xerj-engine/src/index.rs`, the weighting note above+/// `apply_lexical_passages`).+///+/// Returns `None` when `origin_line` is 0, `terms` is empty, or no term+/// occurs as a whole word. Callers omit the field rather than emit a line+/// they could not find.+pub fn matched_source_lines(+ passage: &str,+ origin_line: u64,+ terms: &[String],+) -> Option<MatchedLines> {+ if origin_line == 0 || terms.is_empty() || passage.is_empty() {+ return None;+ }+ let lines: Vec<String> = passage.lines().map(str::to_lowercase).collect();+ if lines.is_empty() {+ return None;+ }+ let weights: Vec<i64> = terms+ .iter()+ .map(|term| {+ let total: i64 = lines.iter().map(|line| whole_word_count(line, term)).sum();+ rarity_weight(total)+ })+ .collect();+ let mut scored: Vec<(u64, i64)> = Vec::new();+ for (i, line) in lines.iter().enumerate() {+ let Some(line_no) = origin_line.checked_add(i as u64) else {+ break;+ };+ let score: i64 = terms+ .iter()+ .zip(&weights)+ .map(|(term, weight)| whole_word_count(line, term).saturating_mul(*weight))+ .sum();+ if score > 0 {+ scored.push((line_no, score));+ }+ }+ if scored.is_empty() {+ return None;+ }+ // Higher score wins; equal scores take the earlier line (`max_by` keeps+ // the last maximum, so the line number is ordered descending).+ let (match_line, _) = scored+ .iter()+ .copied()+ .max_by(|a, b| a.1.cmp(&b.1).then(b.0.cmp(&a.0)))?;+ if scored.len() > MATCH_LINES_CAP {+ scored.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));+ scored.truncate(MATCH_LINES_CAP);+ scored.sort_by_key(|row| row.0);+ }+ Some(MatchedLines {+ match_line,+ match_lines: scored.into_iter().map(|row| row.0).collect(),+ })+}++/// `n/(1+n)²` scaled into integers. A term that never occurs scores 0 and+/// cannot mark a line. The peak is one occurrence (`SCALE/4`); more copies+/// of the same word are worth strictly less in total, which is the bound+/// the lexical passage picker relies on.+fn rarity_weight(occurrences: i64) -> i64 {+ if occurrences <= 0 {+ return 0;+ }+ const SCALE: i64 = 1_000_000;+ let n = occurrences.min(10_000);+ let denom = (1 + n).saturating_mul(1 + n);+ SCALE / denom+}++/// Whole-word hits of `needle` in an already-lowercased `hay`.+///+/// The boundary is the highlighter's: the character on either side must not+/// be alphanumeric or `_`, so `form` does not match inside `format` and+/// `or` does not match inside `for`.+fn whole_word_count(hay: &str, needle: &str) -> i64 {+ if needle.is_empty() {+ return 0;+ }+ let mut count = 0i64;+ let mut from = 0usize;+ while from < hay.len() {+ let Some(pos) = hay[from..].find(needle) else {+ break;+ };+ let abs = from + pos;+ let end = abs + needle.len();+ let before_ok = hay[..abs]+ .chars()+ .next_back()+ .is_none_or(|c| !is_match_word_char(c));+ let after_ok = hay[end..]+ .chars()+ .next()+ .is_none_or(|c| !is_match_word_char(c));+ if before_ok && after_ok {+ count += 1;+ }+ let step = hay[abs..].chars().next().map_or(1, char::len_utf8);+ from = abs + step;+ }+ count+}++fn is_match_word_char(c: char) -> bool {+ c.is_alphanumeric() || c == '_'+}++/// Terms to hunt for in a passage. A plain string uses [`query_terms`]. A+/// JSON query object (the DSL `xerj_search` forwards) contributes the text+/// of its `match` / `multi_match` / `query_string` / `term` clauses. A+/// `semantic` or `knn` clause has no lexical line — its passage `ordinal`+/// is a chunk index — so the term list is empty and the caller omits+/// `match_line`.+pub fn match_query_terms(query: &str) -> Vec<String> {+ let trimmed = query.trim();+ if trimmed.starts_with('{') || trimmed.starts_with('[') {+ if let Ok(value) = serde_json::from_str::<Value>(trimmed) {+ if json_is_nonlexical(&value) {+ return Vec::new();+ }+ let mut text = String::new();+ collect_dsl_text(&value, &mut text);+ return dedup_terms(&text);+ }+ }+ dedup_terms(trimmed)+}++fn dedup_terms(text: &str) -> Vec<String> {+ let mut out = Vec::new();+ for term in query_terms(text) {+ if !out.iter().any(|seen| seen == &term) {+ out.push(term);+ }+ }+ out+}++fn json_is_nonlexical(value: &Value) -> bool {+ match value {+ Value::Object(map) => {+ map.keys().any(|k| k == "semantic" || k == "knn")+ || map.values().any(json_is_nonlexical)+ }+ Value::Array(items) => items.iter().any(json_is_nonlexical),+ _ => false,+ }+}++fn collect_dsl_text(value: &Value, out: &mut String) {+ let Value::Object(map) = value else {+ if let Value::Array(items) = value {+ for item in items {+ collect_dsl_text(item, out);+ }+ }+ return;+ };+ for (key, val) in map {+ match key.as_str() {+ "match"+ | "match_phrase"+ | "match_phrase_prefix"+ | "multi_match"+ | "simple_query_string"+ | "query_string" => absorb_query_clause(val, out),+ "term" => absorb_term_clause(val, out),+ _ => collect_dsl_text(val, out),+ }+ }+}++fn absorb_query_clause(val: &Value, out: &mut String) {+ match val {+ Value::String(s) => push_term_text(out, s),+ Value::Object(map) => {+ if let Some(q) = map.get("query").and_then(Value::as_str) {+ push_term_text(out, q);+ }+ for (key, inner) in map {+ if matches!(+ key.as_str(),+ "query" | "fields" | "type" | "operator" | "analyzer" | "boost"+ ) {+ continue;+ }+ match inner {+ Value::String(s) => push_term_text(out, s),+ Value::Object(obj) => {+ if let Some(q) = obj.get("query").and_then(Value::as_str) {+ push_term_text(out, q);+ }+ }+ _ => {}+ }+ }+ }+ _ => {}+ }+}++fn absorb_term_clause(val: &Value, out: &mut String) {+ let Value::Object(map) = val else {+ return;+ };+ for (key, inner) in map {+ if key == "boost" {+ continue;+ }+ match inner {+ Value::String(s) => push_term_text(out, s),+ Value::Object(obj) => {+ if let Some(s) = obj.get("value").and_then(Value::as_str) {+ push_term_text(out, s);+ }+ }+ _ => {}+ }+ }+}++fn push_term_text(out: &mut String, text: &str) {+ out.push(' ');+ out.push_str(text);+}++/// Stamp `match_line` / `match_lines` onto each hit of an ES search+/// response. Returns whether any hit gained the fields. A hit whose passage+/// does not contain a term, or whose passage start line is not known, is+/// left untouched — a missing field, not a guessed line.+pub fn annotate_search_match_lines(resp: &mut Value, query: &str) -> bool {+ let terms = match_query_terms(query);+ if terms.is_empty() {+ return false;+ }+ let Some(hits) = resp.pointer_mut("/hits/hits").and_then(Value::as_array_mut) else {+ return false;+ };+ let mut changed = false;+ for hit in hits {+ if stamp_match_line(hit, &terms) {+ changed = true;+ }+ }+ changed+}++/// [`annotate_search_match_lines`] on a response body. Unchanged responses+/// (non-JSON, no hits, nothing located) come back byte-identical.+pub fn annotate_search_response(text: &str, query: &str) -> String {+ let Ok(mut resp) = serde_json::from_str::<Value>(text) else {+ return text.to_string();+ };+ if !annotate_search_match_lines(&mut resp, query) {+ return text.to_string();+ }+ serde_json::to_string(&resp).unwrap_or_else(|_| text.to_string())+}++fn stamp_match_line(hit: &mut Value, terms: &[String]) -> bool {+ let found = passage_text_and_origin(hit)+ .and_then(|(text, origin)| matched_source_lines(&text, origin, terms));+ let Some(found) = found else {+ return false;+ };+ let Some(obj) = hit.as_object_mut() else {+ return false;+ };+ let lines = Value::Array(+ found+ .match_lines+ .iter()+ .copied()+ .map(|n| json!(n))+ .collect(),+ );+ let same = obj.get("match_line").and_then(Value::as_u64) == Some(found.match_line)+ && obj.get("match_lines") == Some(&lines);+ if same {+ return false;+ }+ obj.insert("match_line".to_string(), json!(found.match_line));+ obj.insert("match_lines".to_string(), lines);+ true+}++/// Passage text plus the file line of its first line.+///+/// `start_line` is the file line of line 0 of the stored field, and a+/// lexical window's `ordinal` counts lines into that field, so the snippet+/// starts at `start_line + ordinal`. `line` on a `code` passage is the same+/// kind of origin. A whole-file `body` window has no `start_line`; its+/// `ordinal` is already the file line (`start_offset` marks it as lexical,+/// the same guard `lexical_passage_line` uses). A `defs` / `title` / `name`+/// list is not source text. A data-row locator (`b<offset>`, `r<N>`, … —+/// `record_locator` in `engine/crates/xerj-autoindex/src/search.rs`) makes+/// `ordinal` a line of the row, not of the file, so it is only used as an+/// offset from a stored `start_line` or `line`. A PDF `page` or notebook+/// `cell` with no stored line is not a line.+fn passage_text_and_origin(hit: &Value) -> Option<(String, u64)> {+ let src = hit.get("_source");+ let start_line = stored_positive(src, "start_line");+ let line = stored_positive(src, "line");+ let data_row = src+ .and_then(|s| s.get("ax_locator"))+ .and_then(Value::as_str)+ .is_some_and(locator_is_data_row);+ let page_or_cell = src.is_some_and(value_has_page_or_cell);++ if let Some(first) = hit.pointer("/fields/_passage/0") {+ let field = first.get("field").and_then(Value::as_str);+ if is_synthetic_passage_field(field) {+ return code_anchored_at_line(src, line);+ }+ if let Some(text) = slice_text(first) {+ let page_or_cell = page_or_cell || value_has_page_or_cell(first);+ return origin_of_slice(first, start_line, line, data_row, page_or_cell)+ .map(|origin| (text, origin));+ }+ }+ if let Some(start) = start_line {+ if let Some(text) = source_text(src, &["body", "text"]) {+ return Some((text, start));+ }+ }+ code_anchored_at_line(src, line)+}++fn code_anchored_at_line(src: Option<&Value>, line: Option<u64>) -> Option<(String, u64)> {+ let line = line?;+ let text = source_text(src, &["code"])?;+ Some((text, line))+}++fn source_text(src: Option<&Value>, keys: &[&str]) -> Option<String> {+ let src = src?;+ for key in keys {+ if let Some(text) = src.get(*key).and_then(Value::as_str) {+ if !text.is_empty() {+ return Some(text.to_string());+ }+ }+ }+ None+}++fn stored_positive(src: Option<&Value>, key: &str) -> Option<u64> {+ src?.get(key).and_then(Value::as_u64).filter(|n| *n > 0)+}++fn slice_text(passage: &Value) -> Option<String> {+ match passage {+ Value::String(s) if !s.is_empty() => Some(s.clone()),+ Value::Object(obj) => obj+ .get("text")+ .or_else(|| obj.get("passage"))+ .or_else(|| obj.get("snippet"))+ .and_then(Value::as_str)+ .filter(|s| !s.is_empty())+ .map(str::to_string),+ _ => None,+ }+}++fn is_synthetic_passage_field(field: Option<&str>) -> bool {+ matches!(field, Some("defs" | "defs_expanded" | "title" | "name"))+}++fn value_has_page_or_cell(value: &Value) -> bool {+ ["page", "cell"].iter().any(|key| {+ value+ .get(*key)+ .and_then(Value::as_u64)+ .is_some_and(|n| n > 0)+ })+}++/// A locator whose passage ordinal counts lines of the record, not of the+/// file. Same shapes as `record_locator` in xerj-autoindex's search command.+fn locator_is_data_row(loc: &str) -> bool {+ let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());+ let yaml = loc+ .strip_prefix('d')+ .is_some_and(|rest| match rest.split_once('e') {+ Some((doc, elem)) => digits(doc) && digits(elem),+ None => digits(rest),+ });+ let row = ["b", "r", "row"]+ .iter()+ .any(|prefix| loc.strip_prefix(prefix).is_some_and(digits));+ let sheet_row = loc.rsplit_once("!r").is_some_and(|(_, n)| digits(n));+ let element = loc.rsplit_once(":e").is_some_and(|(_, n)| digits(n));+ row || yaml || sheet_row || element+}++fn origin_of_slice(+ passage: &Value,+ start_line: Option<u64>,+ line: Option<u64>,+ data_row: bool,+ page_or_cell: bool,+) -> Option<u64> {+ let ordinal = passage.get("ordinal").and_then(Value::as_u64);+ let field = passage.get("field").and_then(Value::as_str);+ let lexical = passage.get("start_offset").is_some();+ if data_row {+ let base = start_line.or(line)?;+ return base.checked_add(ordinal.unwrap_or(0));+ }+ if let Some(start) = start_line {+ return start.checked_add(ordinal.unwrap_or(0));+ }+ if let Some(line) = line {+ return match field {+ Some("code") => line.checked_add(ordinal.unwrap_or(0)),+ Some("body" | "text" | "content") if lexical => ordinal.and_then(|o| o.checked_add(1)),+ _ if ordinal.unwrap_or(0) == 0 => Some(line),+ _ => None,+ };+ }+ if page_or_cell {+ return None;+ }+ if lexical {+ return ordinal.and_then(|o| o.checked_add(1));+ }+ None+}+#[cfg(test)]mod tests {use super::*;@@ -448,4 +913,200 @@ mod tests {assert_eq!(label, "function alpha @ line 1");assert_eq!(text, "fn alpha() {\n let needle = 1;\n}");}++ fn prose_hit(start: u64, ordinal: u64, text: &str) -> Value {+ json!({+ "_source": { "ax_path": "guide.md", "start_line": start, "ax_locator": "s2" },+ "fields": { "_passage": [{+ "field": "body",+ "ordinal": ordinal,+ "start_offset": 0,+ "text": text+ }] }+ })+ }++ fn stamped(hit: Value, query: &str) -> Value {+ let mut resp = json!({ "hits": { "hits": [hit] } });+ annotate_search_match_lines(&mut resp, query);+ resp["hits"]["hits"][0].clone()+ }++ #[test]+ fn match_on_the_first_line_is_the_passage_start() {+ let hit = stamped(+ prose_hit(169, 0, "Slot filling binds the token.\nLater prose."),+ "slot filling",+ );+ assert_eq!(hit["match_line"], 169);+ assert_eq!(hit["match_lines"], json!([169]));+ }++ #[test]+ fn match_on_a_later_line_is_start_line_plus_the_offset() {+ let hit = stamped(+ prose_hit(+ 169,+ 0,+ "Intro paragraph about the form.\n\nThe token is required when unbound.",+ ),+ "unbound token",+ );+ assert_eq!(hit["match_line"], 171, "{hit}");+ assert_eq!(hit["match_lines"], json!([171]));+ }++ /// A window that does not start at the section's first line: `ordinal`+ /// is the line offset inside the field `start_line` names.+ #[test]+ fn passage_ordinal_shifts_the_window_off_start_line() {+ let hit = stamped(+ prose_hit(10, 5, "preamble\nSlot filling lives here."),+ "slot",+ );+ assert_eq!(hit["match_line"], 16, "{hit}");+ }++ #[test]+ fn multi_term_picks_the_best_score_then_the_earliest_line() {+ let passage = "\+alpha only\n\+alpha beta\n\+alpha beta\n\+the the the the";+ let terms = match_query_terms("alpha beta the");+ let found = matched_source_lines(passage, 1, &terms).unwrap();+ // Both content terms beat the line that only has one, and beat a+ // line that repeats a common word. The two equal lines take the first.+ assert_eq!(found.match_line, 2, "{found:?} terms={terms:?}");+ // The repeated "the" is a real hit, and it does not win.+ assert_eq!(found.match_lines, vec![1, 2, 3, 4]);++ // Case fold, and `form` is not a hit inside `format`.+ let folded =+ matched_source_lines("format\nThe Form field", 40, &match_query_terms("form")).unwrap();+ assert_eq!(folded.match_line, 41);++ let inside = matched_source_lines("format only", 1, &match_query_terms("form"));+ assert!(inside.is_none(), "{inside:?}");+ }++ #[test]+ fn no_match_or_unknown_start_line_omits_the_field() {+ let missing = stamped(+ prose_hit(169, 0, "nothing about this topic"),+ "slot filling",+ );+ assert!(missing.get("match_line").is_none(), "{missing}");+ assert!(missing.get("match_lines").is_none(), "{missing}");++ let no_line = json!({+ "_source": { "ax_path": "guide.md" },+ "fields": { "_passage": [{ "field": "body", "ordinal": 4, "text": "slot filling" }] }+ });+ let unknown = stamped(no_line, "slot");+ assert!(+ unknown.get("match_line").is_none(),+ "a section-relative ordinal is not a file line: {unknown}"+ );++ let row = json!({+ "_source": { "ax_path": "rows.jsonl", "ax_locator": "b68801" },+ "fields": { "_passage": [{+ "field": "body", "ordinal": 0, "start_offset": 0, "text": "slot filling"+ }] }+ });+ let data_row = stamped(row, "slot");+ assert!(+ data_row.get("match_line").is_none(),+ "a row ordinal is not a file line: {data_row}"+ );++ let pdf = json!({+ "_source": { "ax_path": "paper.pdf", "page": 4 },+ "fields": { "_passage": [{+ "field": "body", "ordinal": 0, "start_offset": 0, "page": 4, "text": "slot filling"+ }] }+ });+ assert!(stamped(pdf, "slot").get("match_line").is_none());++ // Semantic ordinals are chunk indexes. No line is better than a wrong one.+ let mut semantic = json!({ "hits": { "hits": [prose_hit(8, 0, "slot filling")] } });+ let query = r#"{"query":{"semantic":{"field":"body","query":"slot filling"}}}"#;+ assert!(!annotate_search_match_lines(&mut semantic, query));+ assert!(semantic["hits"]["hits"][0].get("match_line").is_none());+ }++ #[test]+ fn a_whole_file_lexical_ordinal_is_the_file_line() {+ let hit = json!({+ "_source": { "ax_path": "src/lib.rs", "ax_locator": "code" },+ "fields": { "_passage": [{+ "field": "body",+ "ordinal": 41,+ "start_offset": 900,+ "text": "fn helper() {\n slot()\n}"+ }] }+ });+ let stamped = stamped(hit, "slot");+ assert_eq!(stamped["match_line"], 43, "{stamped}");+ }++ /// Text chunks (`extract/txt.rs`) store `start_line` on a `b<byte>` locator.+ /// The locator marks a byte offset; the line is still a file line, and the+ /// passage ordinal is an offset into that chunk.+ #[test]+ fn a_text_chunk_uses_its_stored_start_line() {+ let hit = json!({+ "_source": {+ "ax_path": "notes.txt",+ "ax_locator": "b120",+ "start_line": 40+ },+ "fields": { "_passage": [{+ "field": "text",+ "ordinal": 2,+ "text": "preface\nmore\nslot filling"+ }] }+ });+ assert_eq!(stamped(hit, "slot")["match_line"], 44);+ }++ #[test]+ fn a_declaration_without_a_passage_is_anchored_at_line() {+ let hit = json!({+ "_source": {+ "ax_path": "src/lib.rs",+ "line": 8,+ "code": "fn alpha() {\n slot()\n}"+ }+ });+ assert_eq!(stamped(hit, "slot")["match_line"], 9);+ }++ #[test]+ fn match_lines_are_capped_and_keep_the_best_line() {+ let passage = std::iter::repeat_n("slot here", 20)+ .collect::<Vec<_>>()+ .join("\n");+ let found = matched_source_lines(&passage, 1, &match_query_terms("slot")).unwrap();+ assert_eq!(found.match_line, 1);+ assert_eq!(found.match_lines.len(), MATCH_LINES_CAP);+ assert_eq!(found.match_lines[0], 1);+ assert_eq!(*found.match_lines.last().unwrap(), MATCH_LINES_CAP as u64);+ }++ #[test]+ fn a_dsl_match_clause_supplies_the_terms() {+ let hit = prose_hit(3, 0, "preface\nslot filling example");+ let stamped = stamped(hit, r#"{"match":{"body":"slot filling"}}"#);+ assert_eq!(stamped["match_line"], 4, "{stamped}");+ }++ #[test]+ fn unchanged_responses_stay_byte_identical() {+ let raw = r#"{"hits":{"hits":[]}}"#;+ assert_eq!(annotate_search_response(raw, "slot"), raw);+ assert_eq!(annotate_search_response("not json", "slot"), "not json");+ }}diff --git a/engine/crates/xerj-mcp/src/def.rs b/engine/crates/xerj-mcp/src/def.rsindex c7c217804..355069904 100644--- a/engine/crates/xerj-mcp/src/def.rs+++ b/engine/crates/xerj-mcp/src/def.rs@@ -85,6 +85,7 @@ pub(crate) async fn run(ctx: &Ctx, args: &Value) -> Value {Some(body),None,None,+ None,).await;if result["isError"] == true {diff --git a/engine/crates/xerj-mcp/src/lib.rs b/engine/crates/xerj-mcp/src/lib.rsindex fe6c8d5e1..387f19a82 100644--- a/engine/crates/xerj-mcp/src/lib.rs+++ b/engine/crates/xerj-mcp/src/lib.rs@@ -521,7 +521,9 @@ fn initialize_result(msg: &Value) -> Value {"XERJ tools proxy to a running XERJ engine (ES-compatible). Use \xerj_search for retrieval — pass `query` as a plain string for \definition-first code search (ranks the defining file first, \- returns the matching passage instead of whole files), or as an \+ returns the matching passage instead of whole files, and adds \+ `match_line` for the source line of the match inside that passage), \+ or as an \ES query-DSL object for structured queries, \xerj_semantic_search for meaning-based recall over a semantic_text \field (embedding is server-side, no key), xerj_vector_search for \@@ -768,6 +770,12 @@ pub fn tool_specs_with(include_hub: bool) -> Value {hits LOCALLY (zero tokens, nothing leaves the node) and adds a \`_p_relevant` probability per hit — see that argument's description \for its honest ceiling. \+ Each hit carries `match_line` when a query term sits in the passage: \+ the absolute 1-based source line of the best-scoring match (a tie \+ takes the earliest line), and `match_lines` for every matched line \+ (capped). Cite `path:match_line`. Both are omitted when no term is \+ located or the passage start line is unknown. `start_line` remains \+ the passage start. \Pass `max_tokens` to cap the response at a token budget (never exceeded; \see that argument for the tokenizer and the locator-only rule).","inputSchema": {@@ -1937,7 +1945,17 @@ async fn call_tool(ctx: &Ctx, msg: &Value) -> Value {match result {Ok((method, path, body)) => {- engine_request(ctx, method, &path, body, budget, demote_page).await+ let match_query = search_match_query(name, &args);+ engine_request(+ ctx,+ method,+ &path,+ body,+ budget,+ demote_page,+ match_query.as_deref(),+ )+ .await}Err(msg) => tool_text(msg, true),}@@ -3077,6 +3095,20 @@ fn error_detail(err: &reqwest::Error) -> String {out}+/// The query `xerj_search` should locate inside each passage (#2266).+/// Other tools do not get the annotation: a semantic/vector ordinal is a+/// chunk index, and `xerj_def` already returns the declaration's `line`.+fn search_match_query(name: &str, args: &Value) -> Option<String> {+ if name != "xerj_search" {+ return None;+ }+ match args.get("query") {+ Some(Value::String(q)) if !q.trim().is_empty() => Some(q.clone()),+ Some(v @ (Value::Object(_) | Value::Array(_))) => Some(v.to_string()),+ _ => None,+ }+}+async fn engine_request(ctx: &Ctx,method: Method,@@ -3084,6 +3116,7 @@ async fn engine_request(body: Option<Value>,budget: Option<usize>,demote_page: Option<usize>,+ match_query: Option<&str>,) -> Value {let url = format!("{}{}", ctx.base_url, path);let mut req = match method {@@ -3107,6 +3140,12 @@ async fn engine_request(Some(page) => apply_search_path_demotion(&text, page),None => text,};+ let text = match match_query {+ Some(query) if !query.trim().is_empty() => {+ xerj_common::xccode::passage::annotate_search_response(&text, query)+ }+ _ => text,+ };match budget {Some(max_tokens) => {tool_text(token_budget::budget_json_response(&text, max_tokens), false)@@ -5145,6 +5184,21 @@ mod tests {}let at = |name: &str| names.iter().position(|n| *n == name).unwrap();assert!(at("xerj_plan") < at("xerj_field_report"));+ let search = specs+ .as_array()+ .unwrap()+ .iter()+ .find(|t| t["name"] == "xerj_search")+ .unwrap();+ let desc = search["description"].as_str().unwrap();+ assert!(+ desc.contains("match_line") && desc.contains("match_lines"),+ "xerj_search must tell the agent where the matched line is: {desc}"+ );+ assert!(+ desc.contains("omitted when no term is located"),+ "a missing match_line is not a line number: {desc}"+ );assert!(at("xerj_field_report") < at("xerj_corpus_feedback"));assert!(at("xerj_corpus_feedback") < at("xerj_hub_find"));let field = specsdiff --git a/engine/crates/xerj-mcp/src/token_budget.rs b/engine/crates/xerj-mcp/src/token_budget.rsindex cba0c0579..662ff633a 100644--- a/engine/crates/xerj-mcp/src/token_budget.rs+++ b/engine/crates/xerj-mcp/src/token_budget.rs@@ -206,6 +206,14 @@ fn locator_stub(hit: &Value) -> Value {}}}+ // #2266: the citation line is computed on the hit, not stored. A locator+ // that drops it puts the agent back to counting lines in a passage the+ // budget just removed.+ for k in ["match_line", "match_lines"] {+ if let Some(v) = hit.get(k).filter(|v| !v.is_null()) {+ stub.insert(k.to_string(), v.clone());+ }+ }Value::Object(stub)}@@ -689,6 +697,51 @@ mod tests {);}+ /// #2266: `match_line` is how an agent cites the hit. A budget that keeps+ /// the passage keeps the field; a budget that reduces the hit to a+ /// locator keeps it there too.+ #[test]+ fn match_line_survives_token_budget_trimming() {+ let passage = "intro\nslot filling binds the token\noutro";+ // Fat stored body so the full hit cannot fit a locator-sized budget.+ // The stub copies match_line and drops the body.+ let body = format!("{passage}\n{}", "filler word ".repeat(400));+ let hit = json!({+ "_index": "docs",+ "_id": "guide",+ "_score": 3.0,+ "_source": {+ "ax_path": "guide.md",+ "start_line": 169,+ "body": body+ },+ "match_line": 170,+ "match_lines": [170],+ "fields": { "_passage": [{ "field": "body", "ordinal": 0, "text": passage }] }+ });+ let resp = search_response(vec![hit.clone()]);++ let kept: Value = serde_json::from_str(&budget_json_response(&resp, 100_000)).unwrap();+ assert_eq!(kept["hits"]["hits"][0]["match_line"], 170);+ assert_eq!(kept["hits"]["hits"][0]["match_lines"], json!([170]));++ let tight: Value = serde_json::from_str(&budget_json_response(&resp, 200)).unwrap();+ assert_eq!(tight["_token_budget"]["hits_full"], 0, "{tight}");+ let stubs = tight["_token_budget"]["hits_locator_only"]+ .as_array()+ .unwrap();+ assert_eq!(stubs.len(), 1, "{stubs:?}");+ assert_eq!(stubs[0]["match_line"], 170, "{stubs:?}");+ assert_eq!(stubs[0]["match_lines"], json!([170]));+ assert_eq!(stubs[0]["ax_path"], "guide.md");+ assert_eq!(stubs[0]["start_line"], 169);+ assert!(stubs[0].get("body").is_none(), "locator drops the passage");+ assert!(+ stubs[0].get("fields").is_none(),+ "locator drops the passage"+ );+ }+/// xerj_semantic_search / xerj_vector_search shape: hits whose `_source`/// is a prose chunk (no file/line), so no span, no dedup — pure budget.#[test]diff --git a/landing/docs/agents/schemas/mcp-tools.json b/landing/docs/agents/schemas/mcp-tools.jsonindex 70b9f55d8..424ae46a4 100644--- a/landing/docs/agents/schemas/mcp-tools.json+++ b/landing/docs/agents/schemas/mcp-tools.json@@ -47,7 +47,7 @@},{"name": "xerj_search",- "description": "Full-text / keyword / structured search over a XERJ index. Proxies POST /{index}/_search. Pass `prefix` (a `xerj search --prefix` value, resolved by that command) or `index` (a name or pattern) — not both; with neither, searches `ax-*`. Pass `query` as a PLAIN STRING for the definition-first code search (ranks the file that defines a symbol above files that merely mention it — the right default for code), or as an ES query-DSL object (e.g. {\"term\":{\"status\":\"open\"}}, or a bool clause) for structured queries. Omit `query` for match_all. Optional `rerank` adds a second stage that re-judges the top hits with an external relevance model — read that argument's description before using it: it needs a provider the operator configured, and it sends document text off the machine. Optional `judge` re-judges the returned hits LOCALLY (zero tokens, nothing leaves the node) and adds a `_p_relevant` probability per hit — see that argument's description for its honest ceiling. Pass `max_tokens` to cap the response at a token budget (never exceeded; see that argument for the tokenizer and the locator-only rule).",+ "description": "Full-text / keyword / structured search over a XERJ index. Proxies POST /{index}/_search. Pass `prefix` (a `xerj search --prefix` value, resolved by that command) or `index` (a name or pattern) — not both; with neither, searches `ax-*`. Pass `query` as a PLAIN STRING for the definition-first code search (ranks the file that defines a symbol above files that merely mention it — the right default for code), or as an ES query-DSL object (e.g. {\"term\":{\"status\":\"open\"}}, or a bool clause) for structured queries. Omit `query` for match_all. Optional `rerank` adds a second stage that re-judges the top hits with an external relevance model — read that argument's description before using it: it needs a provider the operator configured, and it sends document text off the machine. Optional `judge` re-judges the returned hits LOCALLY (zero tokens, nothing leaves the node) and adds a `_p_relevant` probability per hit — see that argument's description for its honest ceiling. Each hit carries `match_line` when a query term sits in the passage: the absolute 1-based source line of the best-scoring match (a tie takes the earliest line), and `match_lines` for every matched line (capped). Cite `path:match_line`. Both are omitted when no term is located or the passage start line is unknown. `start_line` remains the passage start. Pass `max_tokens` to cap the response at a token budget (never exceeded; see that argument for the tokenizer and the locator-only rule).","inputSchema": {"type": "object","properties": {diff --git a/landing/docs/cli.html b/landing/docs/cli.htmlindex 93f59dc2b..070366a2b 100644--- a/landing/docs/cli.html+++ b/landing/docs/cli.html@@ -514,10 +514,12 @@ Grok CLI | ~/.grok/config.toml or .grok/config.toml<p>Codex, the Grok CLI, Kilo Code, Continue, Goose, Amp, VS Code and Copilot, Zed, OpenClaw and DeepSeek Harness do not use the JSON shape above; <a href="https://github.com/xerj-org/xerj#supported-agents">the README carries the exact snippet for each</a>. Aider is absent because it has no MCP client support, T3 Code hosts an MCP endpoint rather than consuming one, and Grok Bot has no documented local stdio registration.</p>- <p>Twenty-one tools are served (eighteen in a build with no hub key, which omits the three hub tools). Eleven are thin proxies over an endpoint the engine already exposes — nothing is added, and engine errors come back verbatim: <code class="inline">xerj_search</code>, <code class="inline">xerj_semantic_search</code>, <code class="inline">xerj_vector_search</code>, <code class="inline">xerj_hybrid_search</code>, <code class="inline">xerj_memory_store</code>, <code class="inline">xerj_memory_recall</code>, <code class="inline">xerj_brain_overview</code>, <code class="inline">xerj_brain_ego</code>, <code class="inline">xerj_brain_link</code>, <code class="inline">xerj_brain_unlink</code>, <code class="inline">xerj_plan</code> (<code class="inline">POST /_ask</code>). Two are not plain proxies: <code class="inline">xerj_map</code> returns the autoindex catalog's per-index field map (trimmed to a byte cap), and <code class="inline">xerj_code_search</code> runs the <code class="inline">xerj code</code> pipeline and returns its rendered text. <code class="inline">xerj_field_report</code> files an agent field report (a GitHub PR first, the <code class="inline">/api/field-report</code> endpoint when GitHub is unavailable; it sends by default). <code class="inline">xerj_index_budget</code> counts a folder and estimates its index against the node's disk budget before <code class="inline">xerj autoindex</code> hashes anything (it does not index), <code class="inline">xerj_autoindex_remove</code> drops one autoindexed folder after listing it and deletes nothing unless <code class="inline">confirm</code> is true, and <code class="inline">xerj_corpus_feedback</code> rates a hub corpus. The three Corpus Hub tools, <code class="inline">xerj_hub_ask</code>, <code class="inline">xerj_hub_def</code> and <code class="inline">xerj_hub_find</code>, run the <a href="#ask"><code class="inline">xerj ask</code></a> flow, but never download a pack and never fetch the catalogue: run <code class="inline">xerj hub sync</code> and <code class="inline">xerj hub pull <slug></code> in a shell first (details on the <a href="/docs/corpus-hub#mcp">Corpus Hub page</a>). Two caveats the tool descriptions carry themselves: <code class="inline">xerj_semantic_search</code> embeds server-side with the <em>lexical</em> feature-hashing embedder unless the node runs <code class="inline">--embed-mode neural</code>, and the <code class="inline">xerj_brain_*</code> tools work a deterministic link index, not a graph database.</p>+ <p>Twenty-one tools are served (eighteen in a build with no hub key, which omits the three hub tools). Eleven are thin proxies over an endpoint the engine already exposes, and engine errors come back verbatim: <code class="inline">xerj_search</code>, <code class="inline">xerj_semantic_search</code>, <code class="inline">xerj_vector_search</code>, <code class="inline">xerj_hybrid_search</code>, <code class="inline">xerj_memory_store</code>, <code class="inline">xerj_memory_recall</code>, <code class="inline">xerj_brain_overview</code>, <code class="inline">xerj_brain_ego</code>, <code class="inline">xerj_brain_link</code>, <code class="inline">xerj_brain_unlink</code>, <code class="inline">xerj_plan</code> (<code class="inline">POST /_ask</code>). Two are not plain proxies: <code class="inline">xerj_map</code> returns the autoindex catalog's per-index field map (trimmed to a byte cap), and <code class="inline">xerj_code_search</code> runs the <code class="inline">xerj code</code> pipeline and returns its rendered text. <code class="inline">xerj_field_report</code> files an agent field report (a GitHub PR first, the <code class="inline">/api/field-report</code> endpoint when GitHub is unavailable; it sends by default). <code class="inline">xerj_index_budget</code> counts a folder and estimates its index against the node's disk budget before <code class="inline">xerj autoindex</code> hashes anything (it does not index), <code class="inline">xerj_autoindex_remove</code> drops one autoindexed folder after listing it and deletes nothing unless <code class="inline">confirm</code> is true, and <code class="inline">xerj_corpus_feedback</code> rates a hub corpus. The three Corpus Hub tools, <code class="inline">xerj_hub_ask</code>, <code class="inline">xerj_hub_def</code> and <code class="inline">xerj_hub_find</code>, run the <a href="#ask"><code class="inline">xerj ask</code></a> flow, but never download a pack and never fetch the catalogue: run <code class="inline">xerj hub sync</code> and <code class="inline">xerj hub pull <slug></code> in a shell first (details on the <a href="/docs/corpus-hub#mcp">Corpus Hub page</a>). Two caveats the tool descriptions carry themselves: <code class="inline">xerj_semantic_search</code> embeds server-side with the <em>lexical</em> feature-hashing embedder unless the node runs <code class="inline">--embed-mode neural</code>, and the <code class="inline">xerj_brain_*</code> tools work a deterministic link index, not a graph database.</p><p><code class="inline">xerj_def</code> finds local definitions with the query, lexical ranking and location deduplication of <code class="inline">xerj def --json</code>. For example, <code class="inline">{"symbol":"Cache","prefix":"project","kind":"struct","lang":"rust","k":5}</code> searches <code class="inline">project-*</code>. Use <code class="inline">index</code> instead of <code class="inline">prefix</code> for an explicit index; non-empty scope arguments cannot be combined, and with neither it searches <code class="inline">ax-*</code>. <code class="inline">symbol</code> also accepts capability phrases. <code class="inline">k</code> is 1–50 (default 5); optional <code class="inline">max_tokens</code> caps the response. Declarations are in <code class="inline">hits.hits[]._source.code</code>, locations in <code class="inline">ax_path</code>/<code class="inline">path</code> and <code class="inline">line</code>/<code class="inline">start_line</code>; older file hits may use <code class="inline">fields._passage</code>. <code class="inline">hits.total</code> counts engine matches before deduplication; no match is a successful empty hit list. As in the CLI, kind/language filters are ignored when no target index maps the field or any maps it as numeric. This queries the configured node; <code class="inline">xerj_hub_def</code> instead searches a named Hub pack.</p>+ <p><code class="inline">xerj_search</code> hits carry <code class="inline">match_line</code> and capped <code class="inline">match_lines</code> when a query term can be located in the passage: the absolute 1-based source line of the best-scoring match (a tie takes the earliest line). Cite <code class="inline">path:match_line</code>. Both fields are omitted when no term is in the passage or the passage start line is unknown. <code class="inline">start_line</code> remains the passage start.</p>+<p>Machine-readable schemas for all twenty-one: <a href="/docs/agents/schemas/mcp-tools.json">/docs/agents/schemas/mcp-tools.json</a>, generated from a live <code class="inline">tools/list</code> and gated against the binary in CI.</p><p class="source-note">Source · engine/crates/xerj-server/src/main.rs · engine/crates/xerj-mcp/src/lib.rs</p>