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: usage exits and init dry-run wording for the small CLI nits (#1631)
xerj-org1f2bf2a7f198
diff --git a/engine/crates/xerj-autoindex/src/cli.rs b/engine/crates/xerj-autoindex/src/cli.rsindex ac9e91bb3..f3dc4b867 100644--- a/engine/crates/xerj-autoindex/src/cli.rs+++ b/engine/crates/xerj-autoindex/src/cli.rs@@ -1666,7 +1666,15 @@ pub fn parse(args: Vec<String>) -> Result<Cmd, String> {exclude_rels: Vec::new(),})))}- _ => Ok(Cmd::Help),+ // No folder and no subcommand. This used to print the full help and+ // exit 0, so a bare `xerj autoindex` looked like a successful run.+ // `--help` / `-h` still return [`Cmd::Help`] above.+ _ => Err(+ "a folder is required (`xerj autoindex <folder>`), or use \+ `xerj autoindex map` / `xerj autoindex status`. \+ `xerj autoindex --help` prints the full usage"+ .into(),+ ),}}@@ -1675,6 +1683,23 @@ mod tests {use super::{parse, Approval, Cmd, Duration, ProgressMode, DEFAULT_MAX_MINUTES};use std::path::PathBuf;+ #[test]+ fn a_bare_autoindex_is_a_usage_error() {+ let err = parse(Vec::new()).expect_err("bare autoindex must not succeed");+ assert!(err.contains("a folder is required"), "{err}");+ assert!(matches!(+ parse(vec!["--help".into()]).expect("help still parses"),+ Cmd::Help+ ));+ assert!(matches!(+ parse(vec!["-h".into()]).expect("-h still parses"),+ Cmd::Help+ ));+ let err = parse(vec!["--url".into(), "http://127.0.0.1:9200".into()])+ .expect_err("flags without a folder are still usage");+ assert!(err.contains("a folder is required"), "{err}");+ }+/// A flag that is accepted and silently does nothing is refused, because/// the operator who passed it believes the run did something it did not.#[test]diff --git a/engine/crates/xerj-autoindex/src/def.rs b/engine/crates/xerj-autoindex/src/def.rsindex 034ce4d1c..f3e2127b7 100644--- a/engine/crates/xerj-autoindex/src/def.rs+++ b/engine/crates/xerj-autoindex/src/def.rs@@ -16,7 +16,8 @@ use std::collections::BTreeSet;use crate::esclient::Es;use crate::search::{corpus_snapshot, empty_lookup_report, field_lookup_ok, hit_location, is_identifier,- mapped_property_names, numeric_property_names, passage_text, weighted_query_fields,+ mapped_property_names, numeric_property_names, parse_count_arg, passage_text,+ weighted_query_fields,};use serde_json::{json, Value};@@ -298,7 +299,15 @@ pub fn run_def_cli() -> i32 {"--url" => url = it.next().unwrap_or_default(),"--prefix" => prefix = it.next().unwrap_or(prefix),"--api-key" => api_key = it.next(),- "-k" => k = it.next().and_then(|s| s.parse().ok()).unwrap_or(k),+ "-k" => {+ k = match parse_count_arg("-k", it.next()) {+ Ok(n) => n,+ Err(e) => {+ eprintln!("xerj def: {e}\n\n{USAGE}");+ return 2;+ }+ };+ }"--kind" => kind = it.next(),"--lang" => lang = it.next(),"--json" => as_json = true,diff --git a/engine/crates/xerj-autoindex/src/init.rs b/engine/crates/xerj-autoindex/src/init.rsindex 1a96b19e4..528bd1fb8 100644--- a/engine/crates/xerj-autoindex/src/init.rs+++ b/engine/crates/xerj-autoindex/src/init.rs@@ -47,6 +47,7 @@ config for each — with a .bak backup for any file it edits:.mcp.json register the `xerj mcp` server (Claude Codeproject scope; merged, other servers kept)+ .cursor/mcp.json the same registration for Cursor (if .cursor/).claude/skills/xerj/SKILL.md teach `xerj search` / `xerj def` (10 lines){hub_skill} .cursor/rules/xerj.mdc same teaching file for Cursor (if .cursor/){hub_rule} AGENTS.md a short XERJ section (appended if the file@@ -246,7 +247,8 @@ fn mcp_registration(bin: &str, url: &str) -> String {format!("MCP registration for other clients (restart the session after; success: `{MCP_SUCCESS_TOOL}` is in the tool list):\n\\x20 Claude Code, every project: claude mcp add --scope user xerj{env} -- {} mcp\n\- \x20 Cursor, Windsurf, Claude Desktop, Cline: copy the \"xerj\" entry from .mcp.json; the root key is \"mcpServers\"\n\+ \x20 Cursor: `.cursor/mcp.json` when that directory exists (init writes it; root key \"mcpServers\")\n\+ \x20 Windsurf, Claude Desktop, Cline: copy the \"xerj\" entry from .mcp.json; the root key is \"mcpServers\"\n\\x20 VS Code (.vscode/mcp.json): root key \"servers\", not \"mcpServers\"; the entry needs \"type\": \"stdio\"",shell_quote(bin))@@ -363,22 +365,22 @@ fn write_teaching_file(path: &Path, content: &str, dry: bool) -> Result<String,Ok(text) => text,Err(e) if e.kind() == std::io::ErrorKind::NotFound => {write_file(path, &stamped(content), dry).map_err(|e| e.to_string())?;- return Ok(report("wrote", path));+ return Ok(report("wrote", path, dry));}// Present but unreadable (not UTF-8, no permission): the user's.- Err(_) => return Ok(report("kept", path)),+ Err(_) => return Ok(report("kept", path, dry)),};match read_stamp(&existing) {Stamp::Pristine(v) if v < INIT_FILES_VERSION => {backup(path, dry)?;write_file(path, &stamped(content), dry).map_err(|e| e.to_string())?;- Ok(report("upgraded", path))+ Ok(report("upgraded", path, dry))}Stamp::Edited(v) if v < INIT_FILES_VERSION => Ok(format!("{} (edited since xerj init wrote it; not upgraded to v{INIT_FILES_VERSION})",- report("kept", path)+ report("kept", path, dry))),- _ => Ok(report("kept", path)),+ _ => Ok(report("kept", path, dry)),}}@@ -450,10 +452,39 @@ fn merged_mcp_json(existing: Option<&str>, url: &str) -> Result<String, String>}/// One detected surface, written. Returns the human line to print.-fn report(action: &str, path: &Path) -> String {+///+/// A dry run used to say `wrote` for a file it did not create. The verb+/// becomes `would write` / `would merge` / `would append` / `would upgrade`+/// so the line matches `--dry-run`'s "write nothing".+fn report(action: &str, path: &Path, dry: bool) -> String {+ let action = match (dry, action) {+ (true, "wrote") => "would write",+ (true, "merged") => "would merge",+ (true, "appended") => "would append",+ (true, "upgraded") => "would upgrade",+ _ => action,+ };format!(" {action:<8} {}", path.display())}+/// Merge the xerj server into one MCP config, or report `kept` when the+/// file already names it. Shared by Claude Code's `.mcp.json` and Cursor's+/// `.cursor/mcp.json` (same `mcpServers` shape).+fn register_mcp(path: &Path, url: &str, dry: bool) -> Result<String, String> {+ let existing = fs::read_to_string(path).ok();+ let already = existing+ .as_deref()+ .map(|t| t.contains("\"xerj\""))+ .unwrap_or(false);+ if already {+ return Ok(report("kept", path, dry));+ }+ let merged = merged_mcp_json(existing.as_deref(), url)?;+ let had = backup(path, dry)?;+ write_file(path, &merged, dry).map_err(|e| e.to_string())?;+ Ok(report(if had { "merged" } else { "wrote" }, path, dry))+}+/// Entry point for the `init` subcommand. Returns a process exit code.pub fn run_init_cli() -> i32 {let mut url = std::env::var("XERJ_URL")@@ -520,20 +551,12 @@ pub(crate) fn run_init_with(let mut out = Vec::new();// 1) MCP registration (.mcp.json, Claude Code project scope; other hosts- // read the same shape). Merge, never clobber.- let mcp_path = cwd.join(".mcp.json");- let existing = fs::read_to_string(&mcp_path).ok();- let already = existing- .as_deref()- .map(|t| t.contains("\"xerj\""))- .unwrap_or(false);- if already {- out.push(report("kept", &mcp_path));- } else {- let merged = merged_mcp_json(existing.as_deref(), url)?;- let had = backup(&mcp_path, dry)?;- write_file(&mcp_path, &merged, dry).map_err(|e| e.to_string())?;- out.push(report(if had { "merged" } else { "wrote" }, &mcp_path));+ // read the same shape). Merge, never clobber. Cursor does not read+ // that file: when the project already has `.cursor/`, write the same+ // entry to `.cursor/mcp.json`.+ out.push(register_mcp(&cwd.join(".mcp.json"), url, dry)?);+ if cwd.join(".cursor").is_dir() {+ out.push(register_mcp(&cwd.join(".cursor/mcp.json"), url, dry)?);}// 2) Claude Code skills — written whenever the project (or user) uses@@ -580,13 +603,13 @@ pub(crate) fn run_init_with(let agents = cwd.join("AGENTS.md");match fs::read_to_string(&agents) {Ok(text) if text.contains("xerj search") || text.contains("xerj def") => {- out.push(report("kept", &agents));+ out.push(report("kept", &agents, dry));}Ok(text) => {backup(&agents, dry)?;write_file(&agents, &format!("{text}{}", agents_md_section()), dry).map_err(|e| e.to_string())?;- out.push(report("appended", &agents));+ out.push(report("appended", &agents, dry));}// Unreadable but present (not UTF-8, no permission): never replace it.Err(e) if e.kind() != std::io::ErrorKind::NotFound => {@@ -602,7 +625,7 @@ pub(crate) fn run_init_with(dry,).map_err(|e| e.to_string())?;- out.push(report("wrote", &agents));+ out.push(report("wrote", &agents, dry));}}@@ -753,9 +776,25 @@ mod tests {#[test]fn dry_run_writes_nothing() {let d = tmp();- run_init_in(d.path(), "http://x:1", true).unwrap();+ let lines = run_init_in(d.path(), "http://x:1", true).unwrap();assert!(!d.path().join(".mcp.json").exists());assert!(!d.path().join("AGENTS.md").exists());+ assert!(+ lines+ .iter()+ .any(|l| l.contains("would write") && l.contains(".mcp.json")),+ "{lines:?}"+ );+ assert!(+ lines+ .iter()+ .any(|l| l.contains("would write") && l.contains("AGENTS.md")),+ "{lines:?}"+ );+ assert!(+ !lines.iter().any(|l| l.contains(" wrote")),+ "a dry run must not claim it wrote: {lines:?}"+ );}#[test]@@ -763,9 +802,21 @@ mod tests {let d = tmp();run_init_in(d.path(), "http://x:1", false).unwrap();assert!(!d.path().join(".cursor/rules/xerj.mdc").exists());+ assert!(!d.path().join(".cursor/mcp.json").exists());fs::create_dir_all(d.path().join(".cursor")).unwrap();- run_init_in(d.path(), "http://x:1", false).unwrap();+ let lines = run_init_in(d.path(), "http://x:1", false).unwrap();assert!(d.path().join(".cursor/rules/xerj.mdc").exists());+ let cursor: Value =+ serde_json::from_str(&fs::read_to_string(d.path().join(".cursor/mcp.json")).unwrap())+ .unwrap();+ assert!(cursor["mcpServers"]["xerj"]["args"][0] == "mcp");+ assert!(+ lines.iter().any(|l| {+ let l = l.replace('\\', "/");+ l.contains("wrote") && l.ends_with(".cursor/mcp.json")+ }),+ "{lines:?}"+ );}// ── the hub skill (Corpus Hub v2, plan section 9) ───────────────────@@ -840,8 +891,18 @@ mod tests {let lines = run_init_in(d.path(), "http://x:1", true).unwrap();assert!(!d.path().join(".claude/skills").exists());assert!(!d.path().join(".cursor/rules").exists());- assert!(has_report(&lines, "wrote", "skills/xerj-hub/SKILL.md"));- assert!(has_report(&lines, "wrote", "rules/xerj-hub.mdc"));+ assert!(has_report(+ &lines,+ "would write",+ "skills/xerj-hub/SKILL.md"+ ));+ assert!(has_report(&lines, "would write", "rules/xerj-hub.mdc"));+ assert!(has_report(&lines, "would write", ".cursor/mcp.json"));+ assert!(!d.path().join(".cursor/mcp.json").exists());+ assert!(+ !lines.iter().any(|l| l.contains(" wrote")),+ "a dry run must not claim it wrote: {lines:?}"+ );}/// The second run rewrites nothing: all four teaching files are `kept`.@@ -863,6 +924,7 @@ mod tests {] {assert!(has_report(&lines, "kept", tail), "{tail}: {lines:?}");}+ assert!(has_report(&lines, "kept", ".cursor/mcp.json"), "{lines:?}");}/// The reason the file exists: the decision rule, the one line, `--def`,@@ -1038,6 +1100,7 @@ mod tests {let with_hub = usage(true);for file in [".mcp.json",+ ".cursor/mcp.json",".claude/skills/xerj/SKILL.md",".claude/skills/xerj-hub/SKILL.md",".cursor/rules/xerj.mdc",diff --git a/engine/crates/xerj-autoindex/src/search.rs b/engine/crates/xerj-autoindex/src/search.rsindex 98a874168..98a7d10bd 100644--- a/engine/crates/xerj-autoindex/src/search.rs+++ b/engine/crates/xerj-autoindex/src/search.rs@@ -23,7 +23,8 @@ OPTIONS:--url <U> node endpoint (default $XERJ_URL or http://localhost:9200)--prefix <P> index prefix to search (default \"ax\" — what `xerj autoindex` writes)--api-key <K> Authorization (or $XERJ_API_KEY; --insecure nodes need none)- -k <N> number of passages to return (default 5)+ -k <N> number of passages to return (default 5). A non-number is a+ usage error, not a silent default--full <CHARS> max characters of each passage to print (default 600)--json print the raw response instead of formatted passages@@ -486,40 +487,116 @@ fn catalog_run_prefixes(es: &Es) -> Option<Vec<String>> {Some(prefixes.into_iter().collect())}-/// 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")- .ok()- .filter(|s| !s.is_empty())- .unwrap_or_default();- let mut api_key = std::env::var("XERJ_API_KEY").ok().filter(|s| !s.is_empty());+/// Default `--full` width, and the width suggested when the user asked for 0.+const DEFAULT_FULL_CHARS: usize = 600;++/// `-k` / `--full`. A value that does not parse used to be consumed and+/// dropped, so `xerj search -k abc` kept the default of 5 and never said so.+pub(crate) fn parse_count_arg(flag: &str, next: Option<String>) -> Result<usize, String> {+ match next {+ Some(v) => v+ .parse::<usize>()+ .map_err(|_| format!("{flag} must be a non-negative whole number, got '{v}'")),+ None => Err(format!("{flag} needs a number")),+ }+}++/// What `(--full N to see more)` should offer. `full * 2` when `full` is 0+/// is 0, so the hint told the reader to pass the value that hid the passage.+pub(crate) fn fuller_than(full: usize) -> usize {+ if full == 0 {+ DEFAULT_FULL_CHARS+ } else {+ full.saturating_mul(2)+ }+}++#[derive(Debug)]+struct ParsedSearch {+ url: String,+ api_key: Option<String>,+ prefix: String,+ k: usize,+ full: usize,+ as_json: bool,+ query: Option<String>,+}++#[derive(Debug)]+enum SearchCli {+ Help,+ Query(ParsedSearch),+}++fn parse_search_cli(+ args: impl Iterator<Item = String>,+ mut url: String,+ mut api_key: Option<String>,+) -> Result<SearchCli, String> {let mut prefix = "ax".to_string();let mut k: usize = 5;- let mut full: usize = 600;+ let mut full: usize = DEFAULT_FULL_CHARS;let mut as_json = false;let mut query: Option<String> = None;- // Skip argv[0] (binary) + argv[1] ("search").- let mut it = xerj_common::argv::args_after_subcommand().into_iter();+ let mut it = args;while let Some(a) = it.next() {match a.as_str() {- "-h" | "--help" => {- print!("{USAGE}");- return 0;- }+ "-h" | "--help" => return Ok(SearchCli::Help),"--url" => url = it.next().unwrap_or_default(),"--prefix" => prefix = it.next().unwrap_or(prefix),"--api-key" => api_key = it.next(),- "-k" => k = it.next().and_then(|s| s.parse().ok()).unwrap_or(k),- "--full" => full = it.next().and_then(|s| s.parse().ok()).unwrap_or(full),+ "-k" => k = parse_count_arg("-k", it.next())?,+ "--full" => full = parse_count_arg("--full", it.next())?,"--json" => as_json = true,other if !other.starts_with('-') && query.is_none() => query = Some(other.to_string()),- other => {- eprintln!("xerj search: unexpected argument '{other}'\n\n{USAGE}");- return 2;- }+ other => return Err(format!("unexpected argument '{other}'")),}}+ Ok(SearchCli::Query(ParsedSearch {+ url,+ api_key,+ prefix,+ k,+ full,+ as_json,+ query,+ }))+}++/// Entry point for the `search` subcommand. Returns a process exit code.+pub fn run_search_cli() -> i32 {+ let url = std::env::var("XERJ_URL")+ .ok()+ .filter(|s| !s.is_empty())+ .unwrap_or_default();+ let api_key = std::env::var("XERJ_API_KEY").ok().filter(|s| !s.is_empty());++ // Arguments after the subcommand, including a flag that was written before it.+ let parsed = match parse_search_cli(+ xerj_common::argv::args_after_subcommand().into_iter(),+ url,+ api_key,+ ) {+ Ok(SearchCli::Help) => {+ print!("{USAGE}");+ return 0;+ }+ Ok(SearchCli::Query(parsed)) => parsed,+ Err(e) => {+ eprintln!("xerj search: {e}\n\n{USAGE}");+ return 2;+ }+ };+ let ParsedSearch {+ mut url,+ mut api_key,+ prefix,+ k,+ full,+ as_json,+ query,+ } = parsed;let query = match query {Some(q) if !q.trim().is_empty() => q,@@ -650,7 +727,7 @@ pub fn run_search_cli() -> i32 {println!(" {l}");}if text.chars().count() > full {- println!(" … (--full {} to see more)", full * 2);+ println!(" … (--full {} to see more)", fuller_than(full));}}}@@ -666,6 +743,46 @@ mod tests {use super::*;use xerj_common::code_query::normalize_code_search_query;+ fn words(args: &[&str]) -> Vec<String> {+ args.iter().map(|s| (*s).to_string()).collect()+ }++ #[test]+ fn a_non_numeric_k_is_a_usage_error() {+ let err = parse_search_cli(+ words(&["-k", "abc", "flush"]).into_iter(),+ String::new(),+ None,+ )+ .expect_err("-k abc must not be ignored");+ assert!(err.contains("-k"), "{err}");+ assert!(err.contains("abc"), "{err}");+ assert!(parse_count_arg("--full", Some("nope".into()))+ .unwrap_err()+ .contains("nope"));+ assert!(parse_count_arg("-k", None)+ .unwrap_err()+ .contains("needs a number"));+ }++ #[test]+ fn a_zero_full_hint_offers_the_default_width() {+ assert_eq!(fuller_than(0), DEFAULT_FULL_CHARS);+ assert_ne!(fuller_than(0), 0);+ assert_eq!(fuller_than(600), 1200);+ let parsed = parse_search_cli(+ words(&["--full", "0", "rotate keys"]).into_iter(),+ String::new(),+ None,+ )+ .unwrap();+ let SearchCli::Query(parsed) = parsed else {+ panic!("expected a query");+ };+ assert_eq!(parsed.full, 0);+ assert_eq!(parsed.query.as_deref(), Some("rotate keys"));+ }+/// #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 returndiff --git a/engine/crates/xerj-server/src/main.rs b/engine/crates/xerj-server/src/main.rsindex 440095b7a..3735da84d 100644--- a/engine/crates/xerj-server/src/main.rs+++ b/engine/crates/xerj-server/src/main.rs@@ -240,10 +240,10 @@ whereprintln!("xerj v{}", env!("CARGO_PKG_VERSION"));std::process::exit(0);}- other => {- eprintln!("unknown argument: {other}. Use --help for usage.");- std::process::exit(1);- }+ // A usage error exits 2 (the same code `parse_args` uses for a+ // missing flag value). Exiting 1 here made `xerj nosuch` disagree+ // with the documented "usage is 2" rule.+ other => return Err(format!("unknown argument: {other}")),}}@@ -1508,8 +1508,20 @@ fn parse_count(flag: &str, next: Option<String>) -> Result<usize, String> {}fn parse_index_args() -> IndexCmdArgs {- // Skip argv[0] (binary) + argv[1] ("index").- let mut args = xerj_common::argv::args_after_subcommand().into_iter();+ // Arguments after "index", including a flag that was written before it.+ parse_index_args_from(xerj_common::argv::args_after_subcommand().into_iter()).unwrap_or_else(+ |e| {+ eprintln!("error: {e}. Use --help for usage.");+ std::process::exit(2);+ },+ )+}++fn parse_index_args_from<I>(args: I) -> Result<IndexCmdArgs, String>+where+ I: Iterator<Item = String>,+{+ let mut args = args;let mut index = None;let mut file = None;let mut batch = 5000usize;@@ -1532,23 +1544,14 @@ fn parse_index_args() -> IndexCmdArgs {print_index_help();std::process::exit(0);}- other => {- eprintln!("unknown argument: {other}. Use --help for usage.");- std::process::exit(1);- }+ other => return Err(format!("unknown argument: {other}")),}}- let index = index.unwrap_or_else(|| {- eprintln!("error: --index <name> is required");- std::process::exit(2);- });- let file = file.unwrap_or_else(|| {- eprintln!("error: --file <path> is required");- std::process::exit(2);- });+ let index = index.ok_or("--index <name> is required")?;+ let file = file.ok_or("--file <path> is required")?;- IndexCmdArgs {+ Ok(IndexCmdArgs {index,file,batch,@@ -1556,7 +1559,7 @@ fn parse_index_args() -> IndexCmdArgs {limit,config,data_dir,- }+ })}fn print_index_help() {@@ -2356,6 +2359,18 @@ mod decide_flag_tests {assert_eq!(args.port.as_deref(), Some("-1"), "left to the port check");}+ #[test]+ fn an_unknown_argument_is_a_usage_error_not_a_process_exit() {+ // Usage errors exit 2 via `parse_args`. This used to `process::exit(1)`+ // inside the parser, so the documented usage code never ran.+ let err = parse_args_from(argv(&["not-a-subcommand"])).unwrap_err();+ assert!(err.contains("unknown argument: not-a-subcommand"), "{err}");+ let err = super::parse_index_args_from(argv(&["--nope"])).unwrap_err();+ assert!(err.contains("unknown argument: --nope"), "{err}");+ let err = super::parse_index_args_from(argv(&["--index", "logs"])).unwrap_err();+ assert!(err.contains("--file"), "{err}");+ }+#[test]fn index_counts_refuse_a_non_number_instead_of_defaulting() {use super::parse_count;