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.

fix(cli): accept a flag written before the subcommand (#1642)

xerj-org84939481057a
diff --git a/engine/crates/xerj-autoindex/src/def.rs b/engine/crates/xerj-autoindex/src/def.rs
index cb7081943..034ce4d1c 100644
--- a/engine/crates/xerj-autoindex/src/def.rs
+++ b/engine/crates/xerj-autoindex/src/def.rs
@@ -288,7 +288,7 @@ pub fn run_def_cli() -> i32 {
let mut query: Option<String> = None;
// Skip argv[0] (binary) + argv[1] ("def").
- let mut it = std::env::args().skip(2);
+ let mut it = xerj_common::argv::args_after_subcommand().into_iter();
while let Some(a) = it.next() {
match a.as_str() {
"-h" | "--help" => {
diff --git a/engine/crates/xerj-autoindex/src/feedback.rs b/engine/crates/xerj-autoindex/src/feedback.rs
index 328042205..00bbefa8f 100644
--- a/engine/crates/xerj-autoindex/src/feedback.rs
+++ b/engine/crates/xerj-autoindex/src/feedback.rs
@@ -108,7 +108,7 @@ pub struct Draft {
/// Entry point for the `xerj feedback` subcommand (blocking; the server binary
/// calls this via `spawn_blocking`). Returns the process exit code.
pub fn run_cli() -> i32 {
- let args: Vec<String> = std::env::args().skip(2).collect();
+ let args: Vec<String> = xerj_common::argv::args_after_subcommand();
match parse(args) {
Ok(None) => {
print_help();
diff --git a/engine/crates/xerj-autoindex/src/gain.rs b/engine/crates/xerj-autoindex/src/gain.rs
index a027db724..d821afd69 100644
--- a/engine/crates/xerj-autoindex/src/gain.rs
+++ b/engine/crates/xerj-autoindex/src/gain.rs
@@ -198,7 +198,7 @@ pub fn run_gain_cli() -> i32 {
.unwrap_or_else(|| "http://localhost:9200".to_string());
let mut api_key = std::env::var("XERJ_API_KEY").ok().filter(|s| !s.is_empty());
let mut as_json = false;
- let mut it = std::env::args().skip(2);
+ let mut it = xerj_common::argv::args_after_subcommand().into_iter();
while let Some(a) = it.next() {
match a.as_str() {
"-h" | "--help" => {
diff --git a/engine/crates/xerj-autoindex/src/init.rs b/engine/crates/xerj-autoindex/src/init.rs
index 53f54f6a4..1a96b19e4 100644
--- a/engine/crates/xerj-autoindex/src/init.rs
+++ b/engine/crates/xerj-autoindex/src/init.rs
@@ -461,7 +461,7 @@ pub fn run_init_cli() -> i32 {
.filter(|s| !s.is_empty())
.unwrap_or_else(|| DEFAULT_URL.to_string());
let mut dry = false;
- let mut it = std::env::args().skip(2);
+ let mut it = xerj_common::argv::args_after_subcommand().into_iter();
while let Some(a) = it.next() {
match a.as_str() {
"-h" | "--help" => {
diff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rs
index 6d3331a55..d4d2d247b 100644
--- a/engine/crates/xerj-autoindex/src/lib.rs
+++ b/engine/crates/xerj-autoindex/src/lib.rs
@@ -1649,7 +1649,7 @@ fn route_cli_error(error: &anyhow::Error, json_output: bool) -> CliErrorRoute {
/// Entry point for the `xerj autoindex` subcommand (blocking; the server
/// binary calls this via spawn_blocking). Returns the process exit code.
pub fn run_cli() -> i32 {
- let args: Vec<String> = std::env::args().skip(2).collect();
+ let args: Vec<String> = xerj_common::argv::args_after_subcommand();
let cmd = match cli::parse(args) {
Ok(c) => c,
Err(e) => {
diff --git a/engine/crates/xerj-autoindex/src/search.rs b/engine/crates/xerj-autoindex/src/search.rs
index 1838b2992..98a874168 100644
--- a/engine/crates/xerj-autoindex/src/search.rs
+++ b/engine/crates/xerj-autoindex/src/search.rs
@@ -500,7 +500,7 @@ pub fn run_search_cli() -> i32 {
let mut query: Option<String> = None;
// Skip argv[0] (binary) + argv[1] ("search").
- let mut it = std::env::args().skip(2);
+ let mut it = xerj_common::argv::args_after_subcommand().into_iter();
while let Some(a) = it.next() {
match a.as_str() {
"-h" | "--help" => {
diff --git a/engine/crates/xerj-autoindex/src/xc.rs b/engine/crates/xerj-autoindex/src/xc.rs
index 3031ad863..c98499bd7 100644
--- a/engine/crates/xerj-autoindex/src/xc.rs
+++ b/engine/crates/xerj-autoindex/src/xc.rs
@@ -234,6 +234,7 @@ const CORPUS_USAGE: &str =
xerj corpus index <name> [--fresh] [--url URL]
xerj corpus list [--url URL]
+a flag may precede the verb (xerj corpus --url URL index <name>);
clone the repos, detect licences, write corpora/<name>/corpus.json;
--from takes the corpus name from the manifest's 'corpus' field (or the
pack's 'pack' field) unless <name> or --as overrides it; a harvested pack
@@ -1995,7 +1996,17 @@ fn run_corpus_list(args: &[String]) -> i32 {
// ── dispatch ────────────────────────────────────────────────────────────────
/// `xerj corpus <add|build|index|list> …` — returns the process exit code.
+fn corpus_verb(arg: &str) -> bool {
+ matches!(
+ arg,
+ "add" | "build" | "sign" | "keygen" | "index" | "list" | "help" | "-h" | "--help"
+ )
+}
+
pub fn run_corpus_cli(args: &[String]) -> i32 {
+ // `xerj corpus --url URL index <name>`: the verb is not the first token.
+ let promoted = xerj_common::argv::reorder_flags_before_command(args, corpus_verb);
+ let args: &[String] = promoted.as_deref().unwrap_or(args);
let Some(sub) = args.first() else {
eprintln!("{CORPUS_USAGE}");
return 2;
@@ -2027,6 +2038,14 @@ pub fn licence_map_for(root: &Path, corpus: &str) -> HashMap<String, String> {
mod tests {
use super::*;
+ #[test]
+ fn a_flag_before_the_corpus_verb_is_not_an_unknown_subcommand() {
+ // Before the hoist, `--url` was the verb and this returned 2
+ // ("unknown subcommand"). `--help` is the verb; it must run.
+ let code = run_corpus_cli(&["--url".into(), "http://127.0.0.1:9".into(), "--help".into()]);
+ assert_eq!(code, 0);
+ }
+
#[test]
fn corpus_names_are_gated_before_any_path_is_built() {
for bad in ["a/b", "*", ".x", "index", "list"] {
diff --git a/engine/crates/xerj-common/src/argv.rs b/engine/crates/xerj-common/src/argv.rs
new file mode 100644
index 000000000..242c0933e
--- /dev/null
+++ b/engine/crates/xerj-common/src/argv.rs
@@ -0,0 +1,125 @@
+//! Arguments after a flag that was written before the subcommand.
+//!
+//! `xerj --url http://127.0.0.1:9200 corpus index name` used to die in the
+//! server-flag parser (`unknown argument: --url`) because the subcommand was
+//! not argv[1]. [`reorder_flags_before_command`] moves that subcommand to
+//! the front and keeps the flags. [`install_hoist`] records the reordered
+//! list for the process; subcommands read it through [`subcommand`] and
+//! [`args_after_subcommand`].
+
+use std::sync::Mutex;
+
+static HOISTED: Mutex<Option<Vec<String>>> = Mutex::new(None);
+
+/// `Some` when leading flags were moved behind a subcommand. `None` leaves
+/// every reader on the real process arguments.
+pub fn install_hoist(argv_without_program: Option<Vec<String>>) {
+ *HOISTED.lock().unwrap_or_else(|e| e.into_inner()) = argv_without_program;
+}
+
+fn hoisted() -> Option<Vec<String>> {
+ HOISTED.lock().unwrap_or_else(|e| e.into_inner()).clone()
+}
+
+/// argv[1]: the subcommand, after a hoist when one was installed.
+pub fn subcommand() -> Option<String> {
+ if let Some(v) = hoisted() {
+ return v.into_iter().next();
+ }
+ std::env::args().nth(1)
+}
+
+/// Arguments after the subcommand word. A hoist appends the flags that
+/// preceded it, so `xerj --url U corpus index name` is seen as
+/// `index name --url U`.
+pub fn args_after_subcommand() -> Vec<String> {
+ if let Some(v) = hoisted() {
+ return v.into_iter().skip(1).collect();
+ }
+ std::env::args().skip(2).collect()
+}
+
+/// Move flags that precede a command word to the end of the list.
+///
+/// A token after a flag is that flag's value when it is not itself a
+/// command and does not start with `-`. A flag whose next token is a
+/// command is boolean (`xerj --insecure corpus list`). Returns `None` when
+/// the first token is already the command, or when no command follows the
+/// flags (a bare `xerj --insecure` stays a server start).
+pub fn reorder_flags_before_command(
+ args: &[String],
+ is_command: impl Fn(&str) -> bool,
+) -> Option<Vec<String>> {
+ let first = args.first()?;
+ if !first.starts_with('-') || is_command(first) {
+ return None;
+ }
+ let mut i = 0;
+ let mut leading = Vec::new();
+ while i < args.len() && args[i].starts_with('-') && !is_command(&args[i]) {
+ leading.push(args[i].clone());
+ i += 1;
+ if i < args.len() && !args[i].starts_with('-') && !is_command(&args[i]) {
+ leading.push(args[i].clone());
+ i += 1;
+ }
+ }
+ if leading.is_empty() || i >= args.len() || !is_command(&args[i]) {
+ return None;
+ }
+ let mut out = Vec::with_capacity(args.len());
+ out.push(args[i].clone());
+ out.extend(args[i + 1..].iter().cloned());
+ out.extend(leading);
+ Some(out)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn is_top(s: &str) -> bool {
+ matches!(s, "corpus" | "code" | "autoindex" | "def")
+ }
+
+ fn v(items: &[&str]) -> Vec<String> {
+ items.iter().map(|s| (*s).to_string()).collect()
+ }
+
+ #[test]
+ fn a_url_before_corpus_is_passed_to_the_subcommand() {
+ let got = reorder_flags_before_command(
+ &v(&["--url", "http://127.0.0.1:9200", "corpus", "index", "name"]),
+ is_top,
+ )
+ .unwrap();
+ assert_eq!(
+ got,
+ v(&["corpus", "index", "name", "--url", "http://127.0.0.1:9200"])
+ );
+ }
+
+ #[test]
+ fn a_boolean_flag_does_not_swallow_the_subcommand() {
+ let got =
+ reorder_flags_before_command(&v(&["--insecure", "corpus", "list"]), is_top).unwrap();
+ assert_eq!(got, v(&["corpus", "list", "--insecure"]));
+ }
+
+ #[test]
+ fn a_server_start_with_only_flags_is_left_alone() {
+ assert!(reorder_flags_before_command(&v(&["--insecure"]), is_top).is_none());
+ assert!(
+ reorder_flags_before_command(&v(&["--url", "http://127.0.0.1:9200"]), is_top).is_none()
+ );
+ }
+
+ #[test]
+ fn a_subcommand_already_in_front_is_left_alone() {
+ assert!(reorder_flags_before_command(
+ &v(&["corpus", "--url", "http://x", "index"]),
+ is_top
+ )
+ .is_none());
+ }
+}
diff --git a/engine/crates/xerj-common/src/lib.rs b/engine/crates/xerj-common/src/lib.rs
index 7da8b05f1..7aa309d5a 100644
--- a/engine/crates/xerj-common/src/lib.rs
+++ b/engine/crates/xerj-common/src/lib.rs
@@ -38,6 +38,7 @@
//! - [`hub`] — Corpus Hub v2 shared types: the catalogue, pack manifest,
//! definition record, and the [`hub::Answer`] every surface renders (#1374)
+pub mod argv;
pub mod calibration;
pub mod code_query;
pub mod config;
diff --git a/engine/crates/xerj-hub/src/cli.rs b/engine/crates/xerj-hub/src/cli.rs
index b0c0c92de..663332e14 100644
--- a/engine/crates/xerj-hub/src/cli.rs
+++ b/engine/crates/xerj-hub/src/cli.rs
@@ -74,7 +74,25 @@ Packs are pulled on demand and never cloned or indexed on the user's machine
(docs/CORPUS_HUB_V2_IMPLEMENTATION.md).";
/// `xerj hub <command> …`.
+fn hub_verb(arg: &str) -> bool {
+ matches!(
+ arg,
+ "build-pack"
+ | "build-catalogue"
+ | "sync"
+ | "pull"
+ | "status"
+ | "stop"
+ | "config"
+ | "help"
+ | "-h"
+ | "--help"
+ )
+}
+
pub fn run_hub_cli(args: &[String]) -> i32 {
+ let promoted = xerj_common::argv::reorder_flags_before_command(args, hub_verb);
+ let args: &[String] = promoted.as_deref().unwrap_or(args);
let Some(sub) = args.first() else {
eprintln!("{HUB_USAGE}");
return 2;
diff --git a/engine/crates/xerj-server/src/brain.rs b/engine/crates/xerj-server/src/brain.rs
index 2cbbd12f3..5ce99fa86 100644
--- a/engine/crates/xerj-server/src/brain.rs
+++ b/engine/crates/xerj-server/src/brain.rs
@@ -36,7 +36,7 @@ const BOOT_TIMEOUT: Duration = Duration::from_secs(120);
const BOOT_POLL: Duration = Duration::from_millis(150);
pub fn run_cli() -> i32 {
- let args: Vec<String> = std::env::args().skip(2).collect();
+ let args: Vec<String> = xerj_common::argv::args_after_subcommand();
let cfg = match parse(args) {
Ok(Some(cfg)) => cfg,
Ok(None) => {
diff --git a/engine/crates/xerj-server/src/main.rs b/engine/crates/xerj-server/src/main.rs
index db4621d01..61d6b7381 100644
--- a/engine/crates/xerj-server/src/main.rs
+++ b/engine/crates/xerj-server/src/main.rs
@@ -121,6 +121,30 @@ struct CliArgs {
decide_model_dir: Option<String>,
}
+/// Subcommands dispatched before the server-flag parser. A flag written
+/// before one of these is moved behind it (`xerj --url URL corpus …`).
+fn is_top_level_command(arg: &str) -> bool {
+ matches!(
+ arg,
+ "index"
+ | "search"
+ | "def"
+ | "init"
+ | "gain"
+ | "autoindex"
+ | "brain"
+ | "share"
+ | "feedback"
+ | "code"
+ | "corpus"
+ | "hub"
+ | "ask"
+ | "mcp"
+ | "__extract-pdf"
+ | xerj_autoindex::extract::xls::WORKER_ARG
+ )
+}
+
fn parse_args() -> CliArgs {
parse_args_from(std::env::args().skip(1)).unwrap_or_else(|e| {
eprintln!("error: {e}. Use --help for usage.");
@@ -253,6 +277,9 @@ fn help_text(feedback: bool) -> String {
\n\
{}\
USAGE:\n\
+ \x20\x20\x20\x20A flag may precede the subcommand: xerj --url URL corpus index <name>\n\
+ \x20\x20\x20\x20is read as xerj corpus index <name> --url URL.\n\
+ \n\
\x20\x20\x20\x20xerj [OPTIONS] start the server (options below)\n\
\x20\x20\x20\x20xerj autoindex <folder> [OPTIONS] zero-config discovery + indexing — the\n\
\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20flagship path for most agents (see xerj\n\
@@ -1443,7 +1470,7 @@ 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 = std::env::args().skip(2);
+ let mut args = xerj_common::argv::args_after_subcommand().into_iter();
let mut index = None;
let mut file = None;
let mut batch = 5000usize;
@@ -2019,8 +2046,19 @@ fn main() -> Result<()> {
#[cfg(unix)]
raise_nofile_limit();
+ // `xerj --url URL corpus index name` used to die here as an unknown
+ // server flag. Move those flags behind the subcommand before any
+ // dispatch reads argv.
+ xerj_common::argv::install_hoist(xerj_common::argv::reorder_flags_before_command(
+ &std::env::args().skip(1).collect::<Vec<_>>(),
+ is_top_level_command,
+ ));
+
// Dispatch before creating Tokio's pool so each PDF worker stays small.
- if matches!(std::env::args().nth(1).as_deref(), Some("__extract-pdf")) {
+ if matches!(
+ xerj_common::argv::subcommand().as_deref(),
+ Some("__extract-pdf")
+ ) {
std::process::exit(xerj_autoindex::extract::pdf::run_worker_cli());
}
@@ -2031,7 +2069,7 @@ fn main() -> Result<()> {
// Dispatched before the Tokio pool for the same smallness reason as the PDF
// worker above.
if matches!(
- std::env::args().nth(1).as_deref(),
+ xerj_common::argv::subcommand().as_deref(),
Some(xerj_autoindex::extract::xls::WORKER_ARG)
) {
std::process::exit(xerj_autoindex::extract::xls::run_worker_cli());
@@ -2055,8 +2093,8 @@ fn main() -> Result<()> {
// This is what makes the MCP server obtainable: before it, `xerj-mcp` was
// a workspace crate that CI built and no release shipped, so the only way
// to get it was to clone the repo and compile. Now `curl … | sh` is enough.
- if matches!(std::env::args().nth(1).as_deref(), Some("mcp")) {
- let args: Vec<String> = std::env::args().skip(2).collect();
+ if matches!(xerj_common::argv::subcommand().as_deref(), Some("mcp")) {
+ let args: Vec<String> = xerj_common::argv::args_after_subcommand();
let rt = build_runtime(2)?;
return rt.block_on(xerj_mcp::run(&args));
}
@@ -2529,7 +2567,7 @@ mod runtime_tests {
async fn async_main() -> Result<()> {
// Subcommand dispatch — check argv[1] before any other parsing.
- let argv1 = std::env::args().nth(1);
+ let argv1 = xerj_common::argv::subcommand();
if matches!(argv1.as_deref(), Some("index")) {
let cmd = parse_index_args();
return run_cli_index(cmd).await;
@@ -2603,7 +2641,7 @@ async fn async_main() -> Result<()> {
// runtime like `def`. Routed through the hub CLI so `--def <SYMBOL>`
// answers from the `-defs` index; every other invocation delegates
// unchanged to `xc::run_code_cli` (Corpus Hub v2, §3).
- let args: Vec<String> = std::env::args().skip(2).collect();
+ let args: Vec<String> = xerj_common::argv::args_after_subcommand();
let code = tokio::task::spawn_blocking(move || xerj_hub::cli::run_code(&args))
.await
.unwrap_or(1);
@@ -2613,7 +2651,7 @@ async fn async_main() -> Result<()> {
// Reference-coding corpus lifecycle (issue #977, previously
// xc-corpus.sh/xc-index.sh): git + autoindex + ES-compat client, all
// synchronous — off the runtime like `autoindex`.
- let args: Vec<String> = std::env::args().skip(2).collect();
+ let args: Vec<String> = xerj_common::argv::args_after_subcommand();
let code = tokio::task::spawn_blocking(move || xerj_autoindex::xc::run_corpus_cli(&args))
.await
.unwrap_or(1);
@@ -2623,7 +2661,7 @@ async fn async_main() -> Result<()> {
// Corpus Hub v2 (discussion #1374): pull pre-indexed, signed packs and
// build them (CI). Synchronous (git + blocking HTTP) — off the runtime
// like `corpus`.
- let args: Vec<String> = std::env::args().skip(2).collect();
+ let args: Vec<String> = xerj_common::argv::args_after_subcommand();
let code = tokio::task::spawn_blocking(move || xerj_hub::cli::run_hub_cli(&args))
.await
.unwrap_or(1);
@@ -2633,7 +2671,7 @@ async fn async_main() -> Result<()> {
// Corpus Hub v2 answer flow (plan §5): route the question to a hub
// corpus, answer from its pack (pulling it the first time). Blocking
// HTTP + process spawn — off the runtime like `hub`.
- let args: Vec<String> = std::env::args().skip(2).collect();
+ let args: Vec<String> = xerj_common::argv::args_after_subcommand();
let code = tokio::task::spawn_blocking(move || xerj_hub::cli::run_ask(&args))
.await
.unwrap_or(1);
diff --git a/engine/crates/xerj-server/src/share.rs b/engine/crates/xerj-server/src/share.rs
index 9f8444be2..6adafed36 100644
--- a/engine/crates/xerj-server/src/share.rs
+++ b/engine/crates/xerj-server/src/share.rs
@@ -63,7 +63,7 @@ const TUNNEL_URL_TIMEOUT: Duration = Duration::from_secs(45);
const TUNNEL_CONNECT_TIMEOUT: Duration = Duration::from_secs(20);
pub fn run_cli() -> i32 {
- let args: Vec<String> = std::env::args().skip(2).collect();
+ let args: Vec<String> = xerj_common::argv::args_after_subcommand();
let cfg = match parse(args, std::env::var("XERJ_API_KEY").ok()) {
Ok(Some(cfg)) => cfg,
Ok(None) => {