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(hub): route questions that name their corpus; make xerj_hub_ask answer in one call (#1731)
xerj-orgd769d34af2bb
diff --git a/engine/crates/xerj-hub/src/ask.rs b/engine/crates/xerj-hub/src/ask.rsindex 09a5eee2c..b3d5fdb98 100644--- a/engine/crates/xerj-hub/src/ask.rs+++ b/engine/crates/xerj-hub/src/ask.rs@@ -273,9 +273,10 @@ pub struct AskDeps<'a> {// ── step 1: mode ─────────────────────────────────────────────────────────────/// Decide the answer mode and the symbol (for `Def`). `--def` / `--how` /-/// `--files` win; otherwise a question that is one identifier, or that matches-/// `what is the (exact )?value of (\w+)`, is a definition lookup, and anything-/// else is a how-does-it-work question.+/// `--files` win; otherwise a question that is one identifier, that matches+/// `what is the (exact )?value of (\w+)`, or that asks `what is <SYMBOL>` /+/// `what's <SYMBOL>` about a code-shaped name ([`looks_like_code_symbol`]), is a+/// definition lookup, and anything else is a how-does-it-work question.pub fn detect_mode(question: &str, requested: &ModeRequest) -> (AnswerMode, Option<String>) {match requested {ModeRequest::Def(sym) => (AnswerMode::Def, Some(sym.clone())),@@ -307,6 +308,7 @@ fn is_identifier(s: &str) -> bool {/// The symbol in `what is the (exact )?value of (\w+)`, matched anywhere in the/// question and case-insensitively on the fixed words (a sentence starts with a/// capital); the symbol keeps its own case.+/// Failing that, the code-shaped symbol in `what is <SYMBOL>` / `what's <SYMBOL>`.fn value_of_symbol(q: &str) -> Option<String> {// ASCII lowercasing keeps every byte offset, so `pos` indexes `q` too.let lower = q.to_ascii_lowercase();@@ -321,9 +323,38 @@ fn value_of_symbol(q: &str) -> Option<String> {}}}+ // `what is LZ4_VERSION_RELEASE in lz4?` — the plain form, but only for a+ // name that is visibly code: `what is compression` stays a how question.+ for lead in ["what is ", "what's "] {+ if let Some(pos) = lower.find(lead) {+ let sym: String = q[pos + lead.len()..]+ .chars()+ .skip_while(|c| *c == '`')+ .take_while(|c| c.is_alphanumeric() || *c == '_')+ .collect();+ if looks_like_code_symbol(&sym) {+ return Some(sym);+ }+ }+ }None}+/// A word that can only be a code identifier, not prose: an identifier with an+/// underscore (`LZ4_VERSION_RELEASE`, `max_len`), or mixed case past its first+/// letter (`HashMap`, `readFile`). `LZ4`, `Snappy` and `compression` are not —+/// they read as names or words, and a def lookup on them would miss.+fn looks_like_code_symbol(s: &str) -> bool {+ if !is_identifier(s) {+ return false;+ }+ let has_word_char = s.chars().any(|c| c.is_ascii_alphanumeric());+ let underscored = s.contains('_') && has_word_char;+ let mixed_case = s.chars().any(|c| c.is_ascii_lowercase())+ && s.chars().skip(1).any(|c| c.is_ascii_uppercase());+ underscored || mixed_case+}+// ── step 4/5: the pull policy ────────────────────────────────────────────────/// Whether the hub may pull a corpus on the caller's behalf.@@ -2050,6 +2081,36 @@ mod tests {}}+ /// FTX shell-less trial (2026-10-17): an agent asked `What is+ /// LZ4_VERSION_RELEASE in lz4?` — a definition question in the plain form —+ /// and got a how-mode search. A code-shaped name after `what is` / `what's` is+ /// a definition lookup; a word or a product name is not.+ #[test]+ fn mode_is_def_for_what_is_a_code_shaped_symbol() {+ let auto = ModeRequest::Auto;+ for (q, sym) in [+ ("What is LZ4_VERSION_RELEASE in lz4?", "LZ4_VERSION_RELEASE"),+ ("what is ZSTD_CLEVEL_DEFAULT", "ZSTD_CLEVEL_DEFAULT"),+ ("what's `max_len` in quinn?", "max_len"),+ ("In std, what is HashMap?", "HashMap"),+ ] {+ assert_eq!(+ detect_mode(q, &auto),+ (AnswerMode::Def, Some(sym.to_string())),+ "{q}"+ );+ }+ for q in [+ "what is compression",+ "What is LZ4?",+ "what is Snappy's framing format",+ "what is the difference between lz4 and zstd",+ "what is _",+ ] {+ assert_eq!(detect_mode(q, &auto), (AnswerMode::How, None), "{q:?}");+ }+ }+#[test]fn mode_is_how_for_prose_and_flags_force_the_rest() {let auto = ModeRequest::Auto;@@ -2831,6 +2892,69 @@ mod tests {);}+ /// FTX shell-less trial (2026-10-17): `xerj_hub_ask` with no `corpus` refused+ /// "What is LZ4_VERSION_RELEASE in lz4?" and "How does snappy's decompressor+ /// …?" with "no hub corpus matches" — while listing the very corpus the+ /// question named as the closest. Neighbouring compression corpora share the+ /// question's words (zstd's sources even mention lz4), so the sketch alone was+ /// never decisive. The corpus the question names is.+ #[test]+ fn a_question_that_names_its_corpus_is_answered_from_it() {+ let rig = Rig::new();+ let shared = &[+ "lz4",+ "snappy",+ "decompressor",+ "literal",+ "copy",+ "element",+ ];+ let cat = catalogue(vec![+ entry("lz4", 1024, LicenceClass::AdaptWithAttribution, shared),+ entry("snappy", 1024, LicenceClass::AdaptWithAttribution, shared),+ entry("zstd", 1024, LicenceClass::AdaptWithAttribution, shared),+ ]);+ for (q, slug, mode) in [+ (+ "What is LZ4_VERSION_RELEASE in lz4?",+ "lz4",+ AnswerMode::Def,+ ),+ (+ "How does snappy's decompressor tell a literal element from a copy element?",+ "snappy",+ AnswerMode::How,+ ),+ ] {+ let backend = FakeBackend::new(true);+ let out = rig.run(&args(q, None), &cat, None, &backend);+ assert_eq!(out.exit, EXIT_OK, "{q}: {:?}", out.stderr);+ let ans = out.answer.expect("an answer");+ assert_eq!(ans.corpus, slug, "{q}");+ assert_eq!(ans.mode, mode, "{q}");+ assert_eq!(+ backend.calls(),+ [format!("ready:{slug}"), format!("answer_local:{slug}")],+ "{q}"+ );+ }++ // Two corpora named: the asker picks, exactly as with two sketch matches.+ let out = rig.run(+ &args("is lz4 or zstd faster at decompressing?", None),+ &cat,+ None,+ &FakeBackend::new(true),+ );+ assert_eq!(out.exit, EXIT_NEEDS_DECISION, "{out:?}");+ assert!(+ out.stdout.contains("lz4") && out.stdout.contains("zstd"),+ "{}",+ out.stdout+ );+ assert!(!out.stdout.contains("snappy"), "{}", out.stdout);+ }+#[test]fn no_corpus_names_the_three_closest_so_the_asker_can_pick_one() {let rig = Rig::new();diff --git a/engine/crates/xerj-hub/src/router.rs b/engine/crates/xerj-hub/src/router.rsindex bc530039f..5f9f986f7 100644--- a/engine/crates/xerj-hub/src/router.rs+++ b/engine/crates/xerj-hub/src/router.rs@@ -47,6 +47,8 @@ pub enum EvidenceSource {Hosted,/// The corpus's term sketch matched some of the question's tokens.Sketch,+ /// The question names this corpus by its slug (`… in lz4?`, `snappy's …`).+ Named,}/// One corpus proposed for a question, with the score it earned on its source's@@ -94,6 +96,12 @@ const CONFIDENT_MIN: f32 = 0.6;const DOMINANCE: f32 = 1.5;/// A slug must reach this to be an `Ambiguous` candidate.const CANDIDATE_MIN: f32 = 0.3;+/// Score a corpus named in the question earns (it outranks everything: the+/// asker said which corpus they mean).+const NAMED_SCORE: f32 = 1.0;+/// Slugs shorter than this are never matched as a name (too likely to be a+/// stray word or abbreviation).+const NAMED_MIN_LEN: usize = 2;/// Route a question to a corpus.///@@ -216,7 +224,54 @@ pub fn route_ranked(}}- decide(evidence, cached)+ // 4. The corpus the question names. Asking "what is X in lz4?" names the+ // corpus outright; the sketch alone could not see that, because the+ // question's other words (and the name itself — zstd's sources mention+ // lz4) also hit the neighbouring corpora. One named corpus decides; several+ // ("lz4 or zstd?") are the candidates, in the order the evidence ranks them.+ let named = named_slugs(question, cat);+ for slug in &named {+ evidence.push(Evidence {+ slug: slug.clone(),+ score: NAMED_SCORE,+ source: EvidenceSource::Named,+ });+ }++ let (routing, ranked) = decide(evidence, cached);+ match named.len() {+ 0 => (routing, ranked),+ 1 => (Routing::Confident(named[0].clone()), ranked),+ _ => {+ let in_order: Vec<String> = ranked+ .iter()+ .filter(|(slug, _)| named.contains(slug))+ .map(|(slug, _)| slug.clone())+ .collect();+ (Routing::Ambiguous(in_order), ranked)+ }+ }+}++/// The catalogue slugs `question` names as a whole word, case-insensitively,+/// in catalogue order. A word is a run of slug characters (`a-z`, `0-9`, `.`,+/// `_`, `-`) with sentence punctuation (`.`, `-`) trimmed from its ends, so+/// `in lz4?`, `LZ4.`, `snappy's` and `c-ares` all name their corpus while+/// `lz4frame` and `liblz4` do not.+pub fn named_slugs(question: &str, cat: &Catalogue) -> Vec<String> {+ let lower = question.to_ascii_lowercase();+ let words: HashSet<&str> = lower+ .split(|c: char| !(c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-')))+ .map(|w| w.trim_matches(|c| c == '.' || c == '-'))+ .filter(|w| w.len() >= NAMED_MIN_LEN)+ .collect();+ let mut out: Vec<String> = Vec::new();+ for entry in &cat.corpora {+ if words.contains(entry.slug.as_str()) && !out.contains(&entry.slug) {+ out.push(entry.slug.clone());+ }+ }+ out}/// Merge evidence by slug (max score), apply the cached bonus, and reach a@@ -783,6 +838,53 @@ mod tests {// --- tokenizer --------------------------------------------------------+ #[test]+ fn named_slugs_match_whole_words_only() {+ let cat = catalogue(vec![+ entry("lz4", &[], &[]),+ entry("c-ares", &[], &[]),+ entry("snappy", &[], &[]),+ entry("h2", &[], &[]),+ ]);+ let names = |q: &str| named_slugs(q, &cat);+ assert_eq!(names("What is LZ4_VERSION_RELEASE in lz4?"), ["lz4"]);+ assert_eq!(names("Does LZ4. handle it"), ["lz4"]);+ assert_eq!(names("how does snappy's decoder work"), ["snappy"]);+ assert_eq!(names("c-ares resolver timeouts"), ["c-ares"]);+ assert_eq!(names("lz4 vs snappy"), ["lz4", "snappy"]);+ // Part of a longer word or identifier is not the name.+ assert!(names("liblz4 and lz4frame and LZ4_compress").is_empty());+ assert!(names("snappyish ares").is_empty());+ }++ #[test]+ fn a_named_corpus_decides_even_against_a_dependency() {+ let cat = catalogue(vec![+ entry("alpha", &["widgetlib"], &["frobnicate", "wizzle"]),+ entry("beta", &[], &["frobnicate", "wizzle"]),+ entry("gamma", &[], &["server"]),+ ]);+ let proj = empty_project();+ fs::write(+ proj.path().join("Cargo.lock"),+ "[[package]]\nname = \"widgetlib\"\nversion = \"1.0\"\n",+ )+ .unwrap();+ let (routing, ranked) =+ route_ranked("how does beta frobnicate", proj.path(), &cat, None, &[]);+ assert_eq!(routing, Routing::Confident("beta".to_string()));+ assert!(ranked.iter().any(|(s, _)| s == "beta"), "{ranked:?}");+ // Two named: ambiguous between exactly those two.+ let both = route("alpha or beta?", empty_project().path(), &cat, None, &[]);+ match both {+ Routing::Ambiguous(mut slugs) => {+ slugs.sort();+ assert_eq!(slugs, ["alpha", "beta"]);+ }+ other => panic!("expected Ambiguous, got {other:?}"),+ }+ }+#[test]fn tokenizer_keeps_identifiers_and_lowercases() {let toks = tokenize("How does LZ4_compress handle a 64 byte block?");diff --git a/engine/crates/xerj-mcp/src/hub.rs b/engine/crates/xerj-mcp/src/hub.rsindex 9b2180316..b5c490923 100644--- a/engine/crates/xerj-mcp/src/hub.rs+++ b/engine/crates/xerj-mcp/src/hub.rs@@ -269,6 +269,10 @@ async fn run(ctx: &Ctx, mut a: AskArgs) -> Value {}}+/// The re-ask hint as the CLI words it, and as a tool caller needs it.+const CLI_CORPUS_HINT: &str = "re-run with --corpus <slug>";+const MCP_CORPUS_HINT: &str = "call xerj_hub_ask again with the `corpus` argument";+/// An [`AskOutcome`] as a tool result. An answer — including one with no hits/// (a miss is an answer, not an error) — carries the Answer JSON as structured/// content. More than one candidate corpus is not an error either: the text@@ -276,7 +280,8 @@ async fn run(ctx: &Ctx, mut a: AskArgs) -> Value {fn outcome_result(o: AskOutcome) -> Value {let mut text = String::new();for line in &o.stderr {- text.push_str(line);+ // The flow's hints name the CLI flag; a tool caller sets an argument.+ text.push_str(&line.replace(CLI_CORPUS_HINT, MCP_CORPUS_HINT));text.push('\n');}text.push_str(&o.stdout);@@ -389,4 +394,34 @@ mod tests {};assert_eq!(outcome_result(failed)["isError"], true);}++ /// FTX shell-less trial (2026-10-17): the "nothing matches" and "more than one+ /// corpus" hints told a tool caller to "re-run with --corpus <slug>", a CLI+ /// flag it has no way to pass. The tool result names the argument instead.+ #[test]+ fn the_reask_hint_names_the_tool_argument_not_the_cli_flag() {+ for (exit, line) in [+ (+ 1,+ "closest corpora: lz4, snappy; re-run with --corpus <slug> to ask one of them",+ ),+ (+ EXIT_NEEDS_DECISION,+ "more than one corpus matches; re-run with --corpus <slug>",+ ),+ ] {+ let r = outcome_result(AskOutcome {+ exit,+ stdout: String::new(),+ stderr: vec![line.into()],+ answer: None,+ });+ let text = r["content"][0]["text"].as_str().unwrap();+ assert!(!text.contains("--corpus"), "{text}");+ assert!(+ text.contains("xerj_hub_ask again with the `corpus` argument"),+ "{text}"+ );+ }+ }}