Skip to content

armgit / xerj

Public Imported from GitHub
0

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.

xerj def / xerj_def: carry the index_stale hint like search (Refs #2426) (#2829)

xerj-orgb736b533701d
diff --git a/engine/crates/xerj-autoindex/src/def.rs b/engine/crates/xerj-autoindex/src/def.rs
index 9c0639551..006db8dbd 100644
--- a/engine/crates/xerj-autoindex/src/def.rs
+++ b/engine/crates/xerj-autoindex/src/def.rs
@@ -569,7 +569,7 @@ pub fn run_def_cli() -> i32 {
}
}
- let es = match Es::new(&url, api_key) {
+ let es = match Es::new(&url, api_key.clone()) {
Ok(es) => es,
Err(e) => {
eprintln!("xerj def: could not build client for {url}: {e}");
@@ -608,6 +608,10 @@ pub fn run_def_cli() -> i32 {
k,
raw_mapping.as_ref(),
);
+ // Same catalog + mtime check as `xerj search` (#2345), run beside the
+ // query: a definition from an index older than the folder can be stale
+ // or missing (#2426), and the lookup should say so.
+ let stale = crate::search::spawn_staleness_check(&url, api_key.as_deref(), &prefix);
let mut resp = match es.search(&pattern, &body) {
Ok(v) => v,
Err(e) => {
@@ -617,8 +621,12 @@ pub fn run_def_cli() -> i32 {
};
let hits = finalize_definition_response(&mut resp, &query, k);
+ let hint = stale.join().ok().flatten();
if as_json {
+ if let Some(hint) = &hint {
+ crate::staleness::attach(&mut resp, hint);
+ }
println!(
"{}",
serde_json::to_string_pretty(&resp).unwrap_or_default()
@@ -626,6 +634,10 @@ pub fn run_def_cli() -> i32 {
return 0;
}
+ if let Some(hint) = &hint {
+ println!("{}", hint.cli_line_for("def"));
+ }
+
if hits.is_empty() {
let snap = corpus_snapshot(&es, &prefix);
let (lines, exit) = empty_lookup_report("def", &prefix, &query, false, &snap);
diff --git a/engine/crates/xerj-autoindex/src/search.rs b/engine/crates/xerj-autoindex/src/search.rs
index f42ac9769..b1c9036f2 100644
--- a/engine/crates/xerj-autoindex/src/search.rs
+++ b/engine/crates/xerj-autoindex/src/search.rs
@@ -972,7 +972,7 @@ fn parse_search_cli(
/// Entry point for the `search` subcommand. Returns a process exit code.
/// Start the staleness check on its own thread so it overlaps the search.
/// The check uses its own blocking client with a short timeout.
-fn spawn_staleness_check(
+pub(crate) fn spawn_staleness_check(
url: &str,
api_key: Option<&str>,
prefix: &str,
diff --git a/engine/crates/xerj-autoindex/src/staleness.rs b/engine/crates/xerj-autoindex/src/staleness.rs
index 03b8bd710..129cb9e4d 100644
--- a/engine/crates/xerj-autoindex/src/staleness.rs
+++ b/engine/crates/xerj-autoindex/src/staleness.rs
@@ -74,7 +74,12 @@ pub struct StalenessHint {
impl StalenessHint {
/// The line `xerj search` prints before its passages.
pub fn cli_line(&self) -> String {
- format!("xerj search: {}", self.reason)
+ self.cli_line_for("search")
+ }
+
+ /// The same line for another subcommand, e.g. `xerj def` (#2426).
+ pub fn cli_line_for(&self, command: &str) -> String {
+ format!("xerj {command}: {}", self.reason)
}
}
@@ -898,6 +903,12 @@ mod tests {
assert_eq!(found.change, "newer");
assert_eq!(found.code, "index_stale");
assert!(line.starts_with("xerj search: "), "{line}");
+ // #2426: `xerj def` prints the same warning under its own name.
+ let def_line = found.cli_line_for("def");
+ assert_eq!(
+ def_line.strip_prefix("xerj def: "),
+ line.strip_prefix("xerj search: ")
+ );
assert!(line.contains("docs/page.md"), "{line}");
assert!(line.contains("2026-10-23T23:46:52Z"), "{line}");
assert!(line.contains("run-20261023T234652Z-2c98-0000"), "{line}");
diff --git a/engine/crates/xerj-mcp/src/def.rs b/engine/crates/xerj-mcp/src/def.rs
index a7e88bcf9..050cee691 100644
--- a/engine/crates/xerj-mcp/src/def.rs
+++ b/engine/crates/xerj-mcp/src/def.rs
@@ -19,7 +19,11 @@ pub(crate) fn spec() -> Value {
"may carry fields._passage instead. hits.total counts engine matches before deduplication. ",
"No match is a successful empty hits list. Unlike xerj_hub_def, this queries the ",
"configured node, not a Hub pack. Optional max_tokens caps the response; see its ",
- "tokenizer and locator-only rule."
+ "tokenizer and locator-only rule. ",
+ "If this prefix was autoindexed from a folder on this machine and a file there is ",
+ "newer than the last run, or an indexed file has been removed, the response adds ",
+ "`_xerj.hints` code `index_stale` with the last index time and a reindex command, ",
+ "the same check as xerj_search: a definition from that index can be stale or missing."
),
"inputSchema": {
"type": "object",
diff --git a/engine/crates/xerj-mcp/src/lib.rs b/engine/crates/xerj-mcp/src/lib.rs
index 90a9e1107..037df1f2b 100644
--- a/engine/crates/xerj-mcp/src/lib.rs
+++ b/engine/crates/xerj-mcp/src/lib.rs
@@ -2072,7 +2072,16 @@ async fn call_tool(ctx: &Ctx, msg: &Value) -> Value {
// the response hits are penalized and trimmed back to `page`.
let mut demote_page: Option<usize> = None;
let result = match name {
- "xerj_def" => return def::run(ctx, &args).await,
+ "xerj_def" => {
+ // Same staleness hint as xerj_search (#2426): an index older than
+ // the folder can return a definition that moved or was removed.
+ let result = def::run(ctx, &args).await;
+ if result.get("isError") == Some(&Value::Bool(true)) {
+ return result;
+ }
+ let hint = search_staleness(ctx, name, &args).await;
+ return apply_staleness(result, hint);
+ }
// Keep the batch state machine off the shared dispatcher future's
// stack: single-item tools must not inherit its larger frame.
"xerj_batch_search" => return Box::pin(batch::run(ctx, &args)).await,
@@ -3552,7 +3561,15 @@ fn search_match_query(name: &str, args: &Value) -> Option<String> {
}
}
-/// Catalog + mtime check for `xerj_search`, after the search has returned.
+/// Tools whose results come from autoindexed prefixes and carry the
+/// `index_stale` hint: passages (`xerj_search`, #2345) and definitions
+/// (`xerj_def`, #2426).
+fn staleness_checked(name: &str) -> bool {
+ matches!(name, "xerj_search" | "xerj_def")
+}
+
+/// Catalog + mtime check for `xerj_search` and `xerj_def`, after the lookup
+/// has returned.
///
/// The walk uses a blocking HTTP client, so it runs on a blocking thread.
/// It starts only once the search result is in hand: a second connection
@@ -3564,7 +3581,7 @@ async fn search_staleness(
name: &str,
args: &Value,
) -> Option<xerj_autoindex::staleness::StalenessHint> {
- if name != "xerj_search" {
+ if !staleness_checked(name) {
return None;
}
let prefix = xerj_autoindex::search::prefix_from_scope(
@@ -6335,6 +6352,42 @@ mod tests {
assert_eq!(kept, err);
}
+ /// #2426: `xerj_def` answered from an index older than the folder with
+ /// no warning, while `xerj_search` on the same prefix carried
+ /// `index_stale`. Both lookups now share the check; other tools do not.
+ #[test]
+ fn a_definition_lookup_carries_the_same_staleness_hint_as_search() {
+ assert!(staleness_checked("xerj_search"));
+ assert!(staleness_checked("xerj_def"));
+ for other in ["xerj_code_search", "xerj_hub_def", "xerj_hybrid_search"] {
+ assert!(!staleness_checked(other), "{other}");
+ }
+ let spec = def::spec();
+ let description = spec["description"].as_str().unwrap();
+ assert!(description.contains("index_stale"), "{description}");
+
+ let hint = xerj_autoindex::staleness::StalenessHint {
+ code: "index_stale",
+ reason: "The index for prefix `ax` was last built at 2026-10-23T23:46:52Z. `src/chart.ts` is newer than that index, so a page on disk can be missing from these results. Reindex with: xerj autoindex /repo --prefix ax".into(),
+ indexed_at: "2026-10-23T23:46:52Z".into(),
+ root: "/repo".into(),
+ run_id: String::new(),
+ prefix: "ax".into(),
+ path: "src/chart.ts".into(),
+ change: "newer",
+ };
+ let def_hit = r#"{"hits":{"total":{"value":1},"hits":[{"_index":"ax-code","_source":{"ax_path":"src/chart.ts","line":12,"code":"export function svgTrend("}}]}}"#;
+ let merged = apply_staleness(tool_text(def_hit, false), Some(hint));
+ let parsed: Value =
+ serde_json::from_str(merged["content"][0]["text"].as_str().unwrap()).unwrap();
+ assert_eq!(parsed["_xerj"]["hints"][0]["code"], "index_stale");
+ assert_eq!(parsed["_xerj"]["hints"][0]["path"], "src/chart.ts");
+ assert_eq!(
+ parsed["hits"]["hits"][0]["_source"]["code"],
+ "export function svgTrend("
+ );
+ }
+
/// A process with no hub signing key must not advertise tools that can
/// only answer with the no-key message. The count `--help` prints is that
/// same list, so the two cannot disagree.
diff --git a/engine/crates/xerj-mcp/tests/local_def.rs b/engine/crates/xerj-mcp/tests/local_def.rs
index dc4a271f2..32a427453 100644
--- a/engine/crates/xerj-mcp/tests/local_def.rs
+++ b/engine/crates/xerj-mcp/tests/local_def.rs
@@ -73,7 +73,12 @@ async fn local_def_mapping_guards_scope_auth_and_legacy_passages() {
)
.await;
assert_eq!(response["hits"]["hits"], json!([legacy]));
- let requests = requests.lock().unwrap();
+ let all = requests.lock().unwrap();
+ // #2426: a definition lookup reads the autoindex catalog once for
+ // the staleness hint, like search; the lookup itself is unchanged.
+ let catalog = "/autoindex-catalog/_search";
+ assert_eq!(all.iter().filter(|r| r.0 == catalog).count(), 1);
+ let requests: Vec<_> = all.iter().filter(|r| r.0 != catalog).collect();
assert_eq!(requests.len(), 2);
assert_eq!(requests[0].0, "/project-*/_mapping");
assert_eq!(requests[1].0, "/project-*/_search");
diff --git a/landing/docs/agents/schemas/mcp-tools.json b/landing/docs/agents/schemas/mcp-tools.json
index cd3375804..9c93bea26 100644
--- a/landing/docs/agents/schemas/mcp-tools.json
+++ b/landing/docs/agents/schemas/mcp-tools.json
@@ -2,7 +2,7 @@
"tools": [
{
"name": "xerj_def",
- "description": "Find a symbol's definition in local autoindexed data, like `xerj def --json`. Lexical ranking, not neural: shares the CLI's mapping-aware query, preferred-kind and public-declaration ranking, location deduplication and bounded candidate window. Returns ES JSON with declarations in hits.hits[]._source.code and locations in ax_path/path plus line/start_line (page/cell for documents); older file-level hits may carry fields._passage instead. hits.total counts engine matches before deduplication. No match is a successful empty hits list. Unlike xerj_hub_def, this queries the configured node, not a Hub pack. Optional max_tokens caps the response; see its tokenizer and locator-only rule.",
+ "description": "Find a symbol's definition in local autoindexed data, like `xerj def --json`. Lexical ranking, not neural: shares the CLI's mapping-aware query, preferred-kind and public-declaration ranking, location deduplication and bounded candidate window. Returns ES JSON with declarations in hits.hits[]._source.code and locations in ax_path/path plus line/start_line (page/cell for documents); older file-level hits may carry fields._passage instead. hits.total counts engine matches before deduplication. No match is a successful empty hits list. Unlike xerj_hub_def, this queries the configured node, not a Hub pack. Optional max_tokens caps the response; see its tokenizer and locator-only rule. If this prefix was autoindexed from a folder on this machine and a file there is newer than the last run, or an indexed file has been removed, the response adds `_xerj.hints` code `index_stale` with the last index time and a reindex command, the same check as xerj_search: a definition from that index can be stale or missing.",
"inputSchema": {
"type": "object",
"properties": {
diff --git a/scripts/mcp-def-smoke.py b/scripts/mcp-def-smoke.py
index 23d04c8ab..36b47e1f3 100644
--- a/scripts/mcp-def-smoke.py
+++ b/scripts/mcp-def-smoke.py
@@ -15,6 +15,7 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
def main():
binary = sys.argv[1]
requests = []
+ catalog_reads = []
mapping = {"project-code": {"mappings": {"properties": {
"name": {"type": "keyword"}, "kind": {"type": "keyword"},
"language": {"type": "keyword"}, "code": {"type": "text"},
@@ -47,7 +48,11 @@ def main():
def do_POST(self):
body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
- requests.append((self.path, body))
+ if self.path == "/autoindex-catalog/_search":
+ # Staleness-hint catalog read (#2426), made by both CLI and MCP.
+ catalog_reads.append(self.path)
+ else:
+ requests.append((self.path, body))
self.respond({"hits": {"total": {"value": len(hits)}, "hits": hits}})
with ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:
@@ -63,6 +68,7 @@ def main():
for symbol, filters in [("Cache", {}), ("cache entries", {}),
("Cache", {"kind": "struct", "lang": "rust"})]:
requests.clear()
+ catalog_reads.clear()
cli_args = ["def", "--url", url, "--api-key", "fixture",
"--prefix", "project", "-k", "2", "--json",
"--disable-feedback", symbol]
@@ -82,6 +88,7 @@ def main():
assert reply["result"]["isError"] is False, reply
mcp = json.loads(reply["result"]["content"][0]["text"])
assert len(requests) == 2 and requests[0] == requests[1], requests
+ assert len(catalog_reads) == 2, catalog_reads
assert requests[0][0] == "/project-*/_search", requests
assert cli == mcp, (cli, mcp)
assert [h["_id"] for h in mcp["hits"]["hits"]] == ["real", "alias"], mcp