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
feat(hub): the gRPC XerjHub service, a thin adapter over the /_hub/v1 code (plan §7)
xerj-orgc08400027f88
diff --git a/docs/hub-v2-grpc-mcp-notes.md b/docs/hub-v2-grpc-mcp-notes.mdindex be037c87b..8dfebea11 100644--- a/docs/hub-v2-grpc-mcp-notes.md+++ b/docs/hub-v2-grpc-mcp-notes.md@@ -144,7 +144,14 @@ its own wire form (`HubAnswer` for gRPC, rendered text + `Answer` JSON for MCP).`XERJ_HUB_URL` overrides the hosted base URL for both. This mirrors how the CLIand the `xerj_code_search` MCP tool already share `xccode::run_code_query`.-## Step-7 wiring checklist (not done here)+## Step-7 wiring checklist++Status: items 1, 2 and 4's gRPC tests are implemented in+`engine/crates/xerj-server/src/grpc_hub.rs` (the service is a thin adapter over+`xerj_api::hub_api::{def_answer, ask_answer, catalogue_signed}` — the same+`def_core`/`code_core` the `/_hub/v1` routes run, and for `Ask` the+`xerj_hub::ask::ask` flow itself with a read-only backend). Item 3 (MCP) ships+separately.1. Implement the `XerjHub` trait in `engine/crates/xerj-server/src/grpc.rs`,converting `HubAnswer` ↔ `hub::Answer` per the tables above.diff --git a/engine/Cargo.lock b/engine/Cargo.lockindex 0f92e77cf..19dfa7353 100644--- a/engine/Cargo.lock+++ b/engine/Cargo.lock@@ -7762,6 +7762,7 @@ dependencies = ["tokio-stream","tonic","tonic-build",+ "tower 0.4.13","tracing","tracing-subscriber","xerj-ai",diff --git a/engine/crates/xerj-api/src/hub_api.rs b/engine/crates/xerj-api/src/hub_api.rsindex a31b22a8b..b4935abfd 100644--- a/engine/crates/xerj-api/src/hub_api.rs+++ b/engine/crates/xerj-api/src/hub_api.rs@@ -523,6 +523,9 @@ struct CatalogueData {bytes: Bytes,etag: String,index: Result<CatalogueIndex, String>,+ /// The whole catalogue, term sketches included, when it parses: what the+ /// gRPC `Ask` routes a question with (`ask_answer`).+ parsed: Option<Arc<Catalogue>>,}struct CatalogueIndex {@@ -539,7 +542,7 @@ struct CorpusRule {impl CatalogueData {fn from_bytes(bytes: Bytes) -> Self {let etag = format!("\"{}\"", hex(&Sha256::digest(&bytes)));- let index = serde_json::from_slice::<Catalogue>(&bytes)+ let parsed = serde_json::from_slice::<Catalogue>(&bytes).map_err(|e| e.to_string()).and_then(|c| {if c.format_version != CATALOGUE_FORMAT_VERSION {@@ -548,23 +551,32 @@ impl CatalogueData {c.format_version));}- Ok(CatalogueIndex {- corpora: c- .corpora- .into_iter()- .map(|e| {- (- e.slug,- CorpusRule {- licence_spdx: e.licence_spdx,- licence_class: e.licence_class,- },- )- })- .collect(),- })+ Ok(c)});- Self { bytes, etag, index }+ let index = parsed+ .as_ref()+ .map_err(Clone::clone)+ .map(|c| CatalogueIndex {+ corpora: c+ .corpora+ .iter()+ .map(|e| {+ (+ e.slug.clone(),+ CorpusRule {+ licence_spdx: e.licence_spdx.clone(),+ licence_class: e.licence_class,+ },+ )+ })+ .collect(),+ });+ Self {+ bytes,+ etag,+ index,+ parsed: parsed.ok().map(Arc::new),+ }}}@@ -1118,7 +1130,7 @@ impl XcHttp for InProcessNode {/// finishes — the cap bounds blocking threads, not just waiting requests.async fn run_query<T, F>(shared: &Arc<HubShared>,- headers: &HeaderMap,+ auth: Option<HeaderValue>,work: F,) -> Result<T, Response>where@@ -1141,7 +1153,7 @@ where// silently widen the caller to the whole `xc-*` namespace.let node = InProcessNode::new(&shared.app,- headers.get(header::AUTHORIZATION).cloned(),+ auth,shared.tuning.response_cap_bytes,index_guard::current(),);@@ -1425,12 +1437,20 @@ enum Outcome {Failed(String),}-fn respond(outcome: Result<Outcome, Response>) -> Response {+/// A blocking query's outcome as the answer, or the response that refuses it.+fn settle(outcome: Result<Outcome, Response>) -> Result<Answer, Response> {match outcome {- Ok(Outcome::Done(answer)) => Json(*answer).into_response(),- Ok(Outcome::NotLoaded) => not_loaded(),- Ok(Outcome::NotServed) => unknown_corpus(),- Ok(Outcome::Failed(detail)) => unavailable(&detail),+ Ok(Outcome::Done(answer)) => Ok(*answer),+ Ok(Outcome::NotLoaded) => Err(not_loaded()),+ Ok(Outcome::NotServed) => Err(unknown_corpus()),+ Ok(Outcome::Failed(detail)) => Err(unavailable(&detail)),+ Err(resp) => Err(resp),+ }+}++fn respond(answer: Result<Answer, Response>) -> Response {+ match answer {+ Ok(answer) => Json(answer).into_response(),Err(resp) => resp,}}@@ -1454,12 +1474,35 @@ async fn def_route(Ok(k) => k,Err(why) => return bad_request(why),};- let rule = match shared.resolve_corpus(&slug).await {- Ok(rule) => rule,- Err(resp) => return resp,- };+ respond(+ def_core(+ &shared,+ slug,+ &symbol,+ k,+ headers.get(header::AUTHORIZATION).cloned(),+ )+ .await,+ )+}++/// `def` for one corpus: the body of `GET /_hub/v1/def/{slug}/{symbol}` after+/// its query string was read, shared with the gRPC `XerjHub.Def` RPC+/// ([`def_answer`]) so both surfaces return the same [`Answer`] and refuse the+/// same requests. `auth` is the caller's `Authorization` value, forwarded to+/// the in-process node.+async fn def_core(+ shared: &Arc<HubShared>,+ slug: String,+ symbol: &str,+ k: usize,+ auth: Option<HeaderValue>,+) -> Result<Answer, Response> {+ let symbol = check_text(symbol, "symbol")?;+ let k = k.clamp(1, MAX_K);+ let rule = shared.resolve_corpus(&slug).await?;let after_check = shared.tuning.after_ledger_check;- let outcome = run_query(&shared, &headers, move |node| {+ let outcome = run_query(shared, auth, move |node| {let root = hub_root();let facts = match corpus_facts(&root, &slug, &rule) {Ok(f) => f,@@ -1512,7 +1555,7 @@ async fn def_route(Outcome::Done(Box::new(answer))}).await;- respond(outcome)+ settle(outcome)}/// `GET /_hub/v1/code/{slug}?q=&k=&max_tokens=&mode=`.@@ -1542,13 +1585,58 @@ async fn code_route(Ok(m) => m,Err(why) => return bad_request(why),};- let rule = match shared.resolve_corpus(&slug).await {- Ok(rule) => rule,- Err(resp) => return resp,- };+ respond(+ code_core(+ &shared,+ slug,+ &query,+ CodeOpts {+ k,+ max_tokens,+ mode,+ },+ headers.get(header::AUTHORIZATION).cloned(),+ )+ .await,+ )+}++/// What a `code` query asks for besides the corpus and the question.+#[derive(Clone, Copy, Debug)]+struct CodeOpts {+ k: usize,+ max_tokens: Option<u64>,+ mode: Mode,+}++/// `code` for one corpus: the body of `GET /_hub/v1/code/{slug}` after its+/// query string was read, shared with the gRPC `XerjHub.Ask` RPC (through+/// [`ask_answer`]) so both surfaces refuse the same requests.+async fn code_core(+ shared: &Arc<HubShared>,+ slug: String,+ query: &str,+ opts: CodeOpts,+ auth: Option<HeaderValue>,+) -> Result<Answer, Response> {+ let query = check_text(query, "q")?;+ let CodeOpts {+ k,+ max_tokens,+ mode,+ } = opts;+ let k = k.clamp(1, MAX_K);+ if let Some(m) = max_tokens {+ if !(1..=MAX_TOKENS_CAP).contains(&m) {+ return Err(bad_request(format!(+ "`max_tokens` must be an integer from 1 to {MAX_TOKENS_CAP}, got [{m}]"+ )));+ }+ }+ let rule = shared.resolve_corpus(&slug).await?;let width = passage_width(max_tokens);let after_check = shared.tuning.after_ledger_check;- let outcome = run_query(&shared, &headers, move |node| {+ let outcome = run_query(shared, auth, move |node| {let root = hub_root();let facts = match corpus_facts(&root, &slug, &rule) {Ok(f) => f,@@ -1618,7 +1706,7 @@ async fn code_route(}}).await;- respond(outcome)+ settle(outcome)}/// `GET /_hub/v1/search?q=&k=`.@@ -1652,7 +1740,8 @@ async fn search_route();}let blocking_shared = shared.clone();- let outcome = run_query(&shared, &headers, move |node| {+ let auth = headers.get(header::AUTHORIZATION).cloned();+ let outcome = run_query(&shared, auth, move |node| {// A failed read of the mappings is an outage, not an empty node.let fields = blocking_shared.search_fields_blocking(node)?;if fields.is_empty() {@@ -1700,6 +1789,447 @@ async fn search_route(}}+// ─────────────────────────────────────────────────────────────────────────────+// The same answers for a surface that is not HTTP (gRPC `XerjHub`, plan §7)+// ─────────────────────────────────────────────────────────────────────────────+//+// The gRPC service is a thin adapter: it converts its request into the+// arguments below and the [`Answer`] that comes back into its own wire form.+// Every check and every query is the HTTP route's own code (`def_core`,+// `code_core`, `resolve_corpus`, the catalogue cache, the in-process node and+// its guards), so the two surfaces cannot drift apart: the same corpus is+// refused for the same reason on both, and `Def` returns the same `Answer`+// field for field as `GET /_hub/v1/def/{slug}/{symbol}`.++/// Why a hub request was refused, independent of the surface it arrived on:+/// the status the `/_hub/v1` route answers with and the reason it puts in the+/// body. A non-HTTP surface maps the status to its own error codes.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct HubRefusal {+ pub status: StatusCode,+ pub reason: String,+ /// The `Retry-After` value, when the route sends one (`429`, a busy `503`).+ pub retry_after: Option<String>,+}++impl HubRefusal {+ fn new(status: StatusCode, reason: impl Into<String>) -> Self {+ Self {+ status,+ reason: reason.into(),+ retry_after: None,+ }+ }+}++/// The refusal an error [`Response`] built by this module carries.+async fn refusal(resp: Response) -> HubRefusal {+ let status = resp.status();+ let retry_after = resp+ .headers()+ .get(header::RETRY_AFTER)+ .and_then(|v| v.to_str().ok())+ .map(str::to_string);+ let body = axum::body::to_bytes(resp.into_body(), 64 * 1024)+ .await+ .unwrap_or_default();+ let reason = serde_json::from_slice::<Value>(&body)+ .ok()+ .and_then(|v| {+ v.pointer("/error/reason")+ .and_then(Value::as_str)+ .map(str::to_string)+ })+ .unwrap_or_else(|| status.canonical_reason().unwrap_or("refused").to_string());+ HubRefusal {+ status,+ reason,+ retry_after,+ }+}++impl HubShared {+ /// Count one request from `client` (an IP address, as text) against the same+ /// per-address budget the HTTP routes use ([`RATE_LIMIT`] per+ /// [`RATE_WINDOW`]); `Err` is the `429` refusal.+ pub fn admit(&self, client: &str) -> Result<(), HubRefusal> {+ self.limiter+ .admit(&client_bucket(client), Instant::now())+ .map_err(|retry_after| HubRefusal {+ status: StatusCode::TOO_MANY_REQUESTS,+ reason: format!(+ "more than {RATE_LIMIT} requests in {} seconds from this address; retry in \+ {retry_after}s",+ RATE_WINDOW.as_secs()+ ),+ retry_after: Some(retry_after.to_string()),+ })+ }+}++/// `GET /_hub/v1/def/{slug}/{symbol}?k=` for a caller that is not HTTP: the+/// same `def_core` the route runs. `k == 0` means [`DEFAULT_K`]; anything+/// larger than [`MAX_K`] is clamped. `auth` is the caller's `Authorization`+/// value (`ApiKey …`), forwarded to the in-process node exactly as the route+/// forwards its header. Run it under the caller's visibility rule+/// (`index_guard::scoped`): it is captured here, as on the HTTP path.+pub async fn def_answer(+ shared: &Arc<HubShared>,+ slug: &str,+ symbol: &str,+ k: usize,+ auth: Option<HeaderValue>,+) -> Result<Answer, HubRefusal> {+ let k = if k == 0 { DEFAULT_K } else { k };+ match def_core(shared, slug.to_string(), symbol, k, auth).await {+ Ok(answer) => Ok(answer),+ Err(resp) => Err(refusal(resp).await),+ }+}++/// The catalogue file and its detached signature.+pub struct SignedCatalogue {+ /// The file's exact bytes — what `GET /_hub/v1/catalogue` serves and what+ /// the signature covers.+ pub bytes: Bytes,+ /// The raw ed25519 signature from `<hub.catalogue_path>.sig` (lower-case hex+ /// on disk, decoded here); empty when the node has no signature file, in+ /// which case the client must treat the catalogue as unverified.+ pub signature: Vec<u8>,+}++/// A detached signature file is 128 hex characters; anything near this size is+/// not one.+const MAX_SIGNATURE_FILE_BYTES: u64 = 1024;++/// `GET /_hub/v1/catalogue` for a caller that is not HTTP, plus the signature+/// the static site serves beside it. The path is the node's configuration, never+/// anything a request supplies.+pub async fn catalogue_signed(shared: &Arc<HubShared>) -> Result<SignedCatalogue, HubRefusal> {+ let data = match shared.catalogue().await {+ Ok(d) => d,+ Err(e) => return Err(refusal(e.into_response()).await),+ };+ let sig_path = format!("{}.sig", shared.app.config.hub.catalogue_path.trim());+ let signature = tokio::task::spawn_blocking(move || read_signature(FsPath::new(&sig_path)))+ .await+ .unwrap_or_default();+ Ok(SignedCatalogue {+ bytes: data.bytes.clone(),+ signature,+ })+}++/// Decode the hex signature at `path`; empty when it is absent, oversized or+/// not hex (logged — a node that serves a broken signature should be told).+fn read_signature(path: &FsPath) -> Vec<u8> {+ let Ok(meta) = std::fs::metadata(path) else {+ return Vec::new();+ };+ if !meta.is_file() || meta.len() > MAX_SIGNATURE_FILE_BYTES {+ tracing::warn!(path = %path.display(), "hub catalogue signature file is not usable");+ return Vec::new();+ }+ let text = std::fs::read_to_string(path).unwrap_or_default();+ let hex = text.trim();+ let decoded: Option<Vec<u8>> = hex+ .len()+ .is_multiple_of(2)+ .then(|| {+ (0..hex.len())+ .step_by(2)+ .map(|i| {+ hex.get(i..i + 2)+ .and_then(|b| u8::from_str_radix(b, 16).ok())+ })+ .collect()+ })+ .flatten();+ decoded.unwrap_or_else(|| {+ tracing::warn!(path = %path.display(), "hub catalogue signature is not hex");+ Vec::new()+ })+}++/// A question for [`ask_answer`] — the gRPC `HubAskRequest`, decoded.+#[derive(Debug, Clone)]+pub struct HubAsk {+ pub question: String,+ /// `None`: route by the catalogue's term sketches.+ pub corpus: Option<String>,+ /// `None`: decide from the question, as `xerj ask` does.+ pub mode: Option<AnswerMode>,+ /// A soft budget for the rendered answer; `None` = none.+ pub max_tokens: Option<u64>,+}++/// Distinct files a `files` answer lists at most (the `xerj ask --files` value).+const FILES_K: usize = 10;++/// Answer a question from the corpora restored on THIS node, through the one+/// answer flow `xerj ask` runs ([`xerj_hub::ask::ask`]): the same mode+/// detection, the same router (term sketches and exact-symbol evidence over this+/// node's catalogue), the same licence warnings and the same token cap. Only the+/// backend differs: [`NodeBackend`] answers through `def_core` / `code_core`,+/// the code behind `GET /_hub/v1/def` and `/_hub/v1/code`.+///+/// Read-only by construction: the flow runs with `offline` and `no_fetch`, no+/// hosted client, and a backend that refuses to pull — so a request can never+/// download, restore, evict or delete a pack, start a process, or reach the+/// network. An `excluded` corpus is removed from the catalogue before routing,+/// so it can neither be routed to nor named (`404`, the same as an unknown+/// corpus); the corpus's own ledger is checked again by the cores.+pub async fn ask_answer(+ shared: &Arc<HubShared>,+ ask: HubAsk,+ auth: Option<HeaderValue>,+) -> Result<Answer, HubRefusal> {+ use xerj_hub::ask::{+ self as flow, AskArgs, AskDeps, HostedSwitch, ModeRequest, EXIT_NEEDS_DECISION, EXIT_USAGE,+ };++ let question = match check_text(&ask.question, "question") {+ Ok(q) => q,+ Err(resp) => return Err(refusal(resp).await),+ };+ if let Some(corpus) = &ask.corpus {+ if !valid_slug(corpus) {+ return Err(refusal(unknown_corpus()).await);+ }+ }+ if let Some(m) = ask.max_tokens {+ if !(1..=MAX_TOKENS_CAP).contains(&m) {+ return Err(HubRefusal::new(+ StatusCode::BAD_REQUEST,+ format!("`max_tokens` must be an integer from 1 to {MAX_TOKENS_CAP}, got [{m}]"),+ ));+ }+ }+ let data = match shared.catalogue().await {+ Ok(d) => d,+ Err(e) => return Err(refusal(e.into_response()).await),+ };+ let Some(full) = data.parsed.clone() else {+ tracing::warn!("hub catalogue does not parse");+ return Err(HubRefusal::new(+ StatusCode::SERVICE_UNAVAILABLE,+ "the hub catalogue cannot be read right now",+ ));+ };+ let routable = Catalogue {+ format_version: full.format_version,+ generated_at: full.generated_at.clone(),+ corpora: full+ .corpora+ .iter()+ .filter(|e| e.licence_class != LicenceClass::Excluded)+ .cloned()+ .collect(),+ };+ let mode = match ask.mode {+ None => ModeRequest::Auto,+ Some(AnswerMode::How) => ModeRequest::How,+ Some(AnswerMode::Files) => ModeRequest::Files,+ // `mode = def` names no symbol of its own: it is the one the question+ // names (`what is the value of X`), else the whole question.+ Some(AnswerMode::Def) => ModeRequest::Def(+ flow::detect_mode(&question, &ModeRequest::Auto)+ .1+ .unwrap_or_else(|| question.clone()),+ ),+ };+ let mut args = AskArgs::new(question);+ args.corpus = ask.corpus;+ args.mode = mode;+ args.offline = true;+ args.no_fetch = true;+ args.hosted = HostedSwitch::Off;+ args.json = true;+ args.max_tokens = ask.max_tokens.map(|m| m as usize);++ let root = routing_root(&shared.app).map_err(|e| {+ tracing::warn!(error = %e, "hub routing directory");+ HubRefusal::new(+ StatusCode::SERVICE_UNAVAILABLE,+ "the hub could not answer this request",+ )+ })?;+ let backend = NodeBackend {+ shared: shared.clone(),+ rt: tokio::runtime::Handle::current(),+ auth,+ // Captured on the caller's task: a task-local does not follow the+ // `spawn_blocking` below (see `run_query`).+ visibility: index_guard::current(),+ refused: std::sync::Mutex::new(None),+ };+ let job = tokio::task::spawn_blocking(move || {+ let outcome = flow::ask(+ &args,+ &AskDeps {+ // No pack cache and no project on the serving side: an empty+ // directory whose `.git` marker stops the dependency walk, so+ // the server's own working directory never steers routing.+ hub_home: &root,+ cwd: &root,+ catalogue: &routable,+ hosted: None,+ backend: &backend,+ },+ );+ let refused = backend.refused.lock().ok().and_then(|mut r| r.take());+ (outcome, refused)+ });+ let (outcome, refused) = match job.await {+ Ok(done) => done,+ Err(e) => {+ tracing::warn!(error = %e, "hub ask task failed");+ return Err(HubRefusal::new(+ StatusCode::INTERNAL_SERVER_ERROR,+ "the hub could not answer this request",+ ));+ }+ };+ if let Some(answer) = outcome.answer {+ // A miss is an answer (no hits), never an error.+ return Ok(answer);+ }+ if let Some(r) = refused {+ return Err(r);+ }+ let said = outcome.stderr.join("; ");+ Err(match outcome.exit {+ // `select_corpus`: a corpus the catalogue does not list (or lists as+ // excluded — removed above). Same words as the HTTP routes' 404.+ EXIT_USAGE => refusal(unknown_corpus()).await,+ EXIT_NEEDS_DECISION => HubRefusal::new(+ StatusCode::CONFLICT,+ format!(+ "{said}; candidates: {}",+ outcome.stdout.lines().collect::<Vec<_>>().join("; ")+ ),+ ),+ _ => HubRefusal::new(StatusCode::NOT_FOUND, said),+ })+}++/// `<data_dir>/hub-routing`, an empty directory holding only a `.git` marker:+/// the `cwd` and `hub_home` [`ask_answer`] hands the answer flow. The router+/// reads lockfiles from `cwd` up to the first `.git`, and the pack cache from+/// `hub_home/packs`; here there must be neither.+fn routing_root(app: &AppState) -> std::io::Result<PathBuf> {+ let root = PathBuf::from(&app.config.server.data_dir).join("hub-routing");+ std::fs::create_dir_all(root.join(".git"))?;+ Ok(root)+}++/// The answer flow's [`xerj_hub::ask::Backend`] on a serving node: "the local+/// pack" is the corpus restored on this node, answered through `def_core` /+/// `code_core`. It never pulls.+struct NodeBackend {+ shared: Arc<HubShared>,+ rt: tokio::runtime::Handle,+ auth: Option<HeaderValue>,+ visibility: Option<Arc<dyn IndexVisibility>>,+ /// The refusal behind the last failed answer, so the caller can report the+ /// route's own status rather than the flow's prose.+ refused: std::sync::Mutex<Option<HubRefusal>>,+}++impl xerj_hub::ask::Backend for NodeBackend {+ /// Whether the corpus is restored here is decided by the cores themselves+ /// (`404 corpus_not_loaded` when its ledger or its indices are missing), the+ /// same check the HTTP routes make, so it is not made twice.+ fn local_pack_ready(&self, _slug: &str) -> Result<bool, String> {+ Ok(true)+ }++ fn answer_local(&self, req: &xerj_hub::ask::Request<'_>) -> Result<Answer, String> {+ let shared = self.shared.clone();+ let auth = self.auth.clone();+ let slug = req.slug.to_string();+ let question = req.question.to_string();+ let symbol = req.symbol.map(str::to_string);+ let mode = req.mode;+ let k = req.k;+ let work = async move {+ match (mode, symbol) {+ (AnswerMode::Def, Some(symbol)) => {+ def_core(&shared, slug, &symbol, k.unwrap_or(DEFAULT_K), auth).await+ }+ _ => {+ let k = k.unwrap_or(if mode == AnswerMode::Files {+ FILES_K+ } else {+ DEFAULT_K+ });+ let opts = CodeOpts {+ k,+ max_tokens: None,+ mode: Mode::Bm25,+ };+ code_core(&shared, slug, &question, opts, auth)+ .await+ .map(|a| {+ if mode == AnswerMode::Files {+ files_answer(a)+ } else {+ a+ }+ })+ }+ }+ };+ // A blocking-pool thread (see `ask_answer`), so `block_on` is legal.+ let result = self+ .rt+ .block_on(index_guard::scoped_opt(self.visibility.clone(), work));+ match result {+ Ok(answer) => Ok(answer),+ Err(resp) => {+ let r = self.rt.block_on(refusal(resp));+ let reason = r.reason.clone();+ if let Ok(mut slot) = self.refused.lock() {+ *slot = Some(r);+ }+ Err(reason)+ }+ }+ }++ fn pull_now(+ &self,+ entry: &xerj_common::hub::CatalogueEntry,+ ) -> Result<(), xerj_hub::ask::PullFailure> {+ Err(xerj_hub::ask::PullFailure {+ code: xerj_hub::ask::EXIT_NO_ANSWER,+ message: format!(+ "'{}' is not loaded on this node; a hub node never pulls on a request's behalf",+ xerj_hub::ask::printable(&entry.slug)+ ),+ })+ }++ fn pull_in_background(&self, _slug: &str) -> Result<xerj_hub::ask::BackgroundPull, String> {+ Err("a hub node never pulls on a request's behalf".to_string())+ }+}++/// A `how` answer reshaped as the `files` answer `xerj ask --files` prints: one+/// hit per distinct file, best first, carrying the corpus licence.+fn files_answer(mut answer: Answer) -> Answer {+ let mut seen = std::collections::HashSet::new();+ let spdx = answer.licence_spdx.clone();+ answer.hits.retain(|h| seen.insert(h.file.clone()));+ for hit in &mut answer.hits {+ hit.kind = "file".to_string();+ hit.text = format!("licence: {spdx}");+ hit.value = None;+ }+ answer.mode = AnswerMode::Files;+ answer+}+// ─────────────────────────────────────────────────────────────────────────────// Facts about a loaded corpus// ─────────────────────────────────────────────────────────────────────────────diff --git a/engine/crates/xerj-server/Cargo.toml b/engine/crates/xerj-server/Cargo.tomlindex a11e0edde..9c935402f 100644--- a/engine/crates/xerj-server/Cargo.toml+++ b/engine/crates/xerj-server/Cargo.toml@@ -111,6 +111,9 @@ protox = { workspace = true }# HTTPS round-trip test against the in-process rustls listener.reqwest = { workspace = true }tempfile = { workspace = true }+# `oneshot` against the ES router: the XerjHub test compares a gRPC `Def` with+# the HTTP `/_hub/v1/def` route field by field.+tower = { workspace = true }# HTTP/2 *as a client*, so `tests/http2_small_data_frames.rs` can choose the# DATA-frame size — the one thing no ordinary HTTP client exposes, and the# whole subject of #485. It also pins the workspace floor at the h2 releasediff --git a/engine/crates/xerj-server/src/grpc.rs b/engine/crates/xerj-server/src/grpc.rsindex cec0e55a9..badba13dd 100644--- a/engine/crates/xerj-server/src/grpc.rs+++ b/engine/crates/xerj-server/src/grpc.rs@@ -1,4 +1,6 @@-//! Real tonic gRPC server for the `XerjSearch` service (default `:8081`).+//! Real tonic gRPC server for the `XerjSearch` service (default `:8081`), and+//! the Corpus Hub `XerjHub` service on the same listener behind the same+//! interceptor (`grpc_hub.rs`).//!//! Replaces the v0.1 placeholder (which only bound the port and dropped//! connections). The service is a thin adapter over the same `Engine`/`Index`@@ -475,10 +477,15 @@ wherelet interceptor = GrpcAuth {state: state.clone(),};+ let hub = pb::xerj_hub_server::XerjHubServer::with_interceptor(+ crate::grpc_hub::HubService::new(state.clone()),+ interceptor.clone(),+ );let svc = XerjSearchServer::with_interceptor(GrpcService::new(state), interceptor);- info!("gRPC XerjSearch listening on {addr}");+ info!("gRPC XerjSearch + XerjHub listening on {addr}");tonic::transport::Server::builder().add_service(svc)+ .add_service(hub).serve_with_incoming_shutdown(incoming, shutdown).await.context("gRPC transport error")?;diff --git a/engine/crates/xerj-server/src/grpc_hub.rs b/engine/crates/xerj-server/src/grpc_hub.rsindex 297bddb72..09c158ae1 100644--- a/engine/crates/xerj-server/src/grpc_hub.rs+++ b/engine/crates/xerj-server/src/grpc_hub.rs@@ -1,29 +1,219 @@-//! Corpus Hub v2 — the gRPC `XerjHub` wire mapping (plan §7,-//! `docs/CORPUS_HUB_V2_IMPLEMENTATION.md`; contract in+//! Corpus Hub v2 — the gRPC `XerjHub` service (plan §7,+//! `docs/CORPUS_HUB_V2_IMPLEMENTATION.md`; wire contract and mapping in//! `docs/hub-v2-grpc-mcp-notes.md`).//!-//! The one place the [`Answer`] ↔ [`pb::HubAnswer`] conversion is written.-//! The proto field numbers are frozen (`HubAnswer` 1–11, `HubHit` 1–7); this-//! module only decides the value forms, as the notes fix them:+//! A thin adapter, and nothing else. Each RPC converts its request into the+//! arguments of a function in `xerj_api::hub_api` and the [`Answer`] that comes+//! back into a [`pb::HubAnswer`]://!-//! * enums travel as their **serde** strings — `licence_class` kebab-case-//! (`adapt-with-attribution` | `approach-only` | `excluded`), `answered_from`-//! and `mode` snake_case (`local_pack` | `hosted` | `local_index`;-//! `def` | `how` | `files`) — never the human `AnsweredFrom::label()`;-//! * `Option<String>` ↔ proto3 `string` is `None` ↔ `""` (`value`,-//! `licence_warning`);-//! * an enum string this build does not know is refused on the way in, not-//! defaulted.+//! | RPC | runs | which is also |+//! |---|---|---|+//! | `Def` | [`hub_api::def_answer`] | `GET /_hub/v1/def/{slug}/{symbol}` (the same `def_core`) |+//! | `Ask` | [`hub_api::ask_answer`] | `xerj ask`'s flow (`xerj_hub::ask::ask`) over the cores behind `/_hub/v1/def` and `/_hub/v1/code` |+//! | `Catalogue` | [`hub_api::catalogue_signed`] | `GET /_hub/v1/catalogue`, plus the detached `.sig` |//!-//! The `XerjHub` service that uses it is wired in a follow-up change; until-//! then only the tests call it.+//! So every check the HTTP routes make — the catalogue lookup, the licence+//! decision (an `excluded` corpus is never served; an `approach-only` one tags+//! every hit with its licence warning), the 512-byte input cap, the `k` clamp,+//! the in-process node pinned to one corpus build, the `xc-*` visibility guard,+//! the query-concurrency cap and timeout, the per-address rate limit — applies+//! here unchanged, because it is the same code.+//!+//! Read-only: none of the three RPCs writes, pulls, evicts or deletes anything+//! (`ask_answer` runs the flow offline with a backend that refuses to pull).+//!+//! # Authentication+//!+//! The service sits behind the same [`super::grpc`] interceptor as+//! `XerjSearch`: an RPC without a valid key (when auth is on) never reaches it.+//! The caller's principal then becomes the engine visibility rule the hub's+//! in-process node runs under, exactly as `authz_middleware` installs it for+//! the HTTP routes, so a key scoped to `tenant-a-*` is refused a corpus here+//! as it is there. `hub.public` does not open these RPCs: it is an HTTP-route+//! setting, and the gRPC listener always authenticates.+//!+//! # The proto mapping (frozen; see the notes)+//!+//! Enums travel as their serde strings (`licence_class` kebab-case,+//! `answered_from` / `mode` snake_case); `Option<String>` ↔ proto3 `string` is+//! `None` ↔ `""`. [`answer_to_pb`] / [`answer_from_pb`] are the only place the+//! conversion is written.++use std::sync::Arc;use serde::de::DeserializeOwned;use serde::Serialize;+use tonic::{Request, Response, Status};-use xerj_common::hub::{Answer, Hit};+use xerj_api::auth::Principal;+use xerj_api::hub_api::{self, HubAsk, HubRefusal, HubShared};+use xerj_api::AppState;+use xerj_common::hub::{Answer, AnswerMode, Hit};+use xerj_engine::index_guard;use crate::grpc::pb;+use pb::xerj_hub_server::XerjHub;++/// The `XerjHub` service. Holds its own [`HubShared`] (query slots, rate-limit+/// budget, catalogue cache), as each HTTP router does.+#[derive(Clone)]+pub struct HubService {+ shared: Arc<HubShared>,+}++impl HubService {+ pub fn new(state: AppState) -> Self {+ Self {+ shared: HubShared::new(state),+ }+ }++ /// Who is calling and from where, with the rate limit counted. The visibility+ /// rule is `None` for the superuser (open mode, the admin key), exactly as+ /// `authz_middleware` installs none for it.+ #[allow(clippy::result_large_err)] // `Err` is the RPC's own status+ fn admit<T>(&self, request: &Request<T>) -> Result<Caller, Status> {+ let principal = request+ .extensions()+ .get::<Principal>()+ .cloned()+ .unwrap_or(Principal::Denied);+ if matches!(principal, Principal::Denied) {+ return Err(Status::unauthenticated(+ "missing or invalid API key in authorization metadata",+ ));+ }+ if principal.is_share_guest() {+ return Err(Status::permission_denied(+ "a share link reads the index it was issued for, not the hub",+ ));+ }+ let client = request+ .remote_addr()+ .map(|a| a.ip().to_string())+ .unwrap_or_else(|| "unknown".to_string());+ self.shared.admit(&client).map_err(refusal_status)?;+ let visibility =+ (!principal.is_superuser()).then(|| xerj_api::authz::visibility_for(&principal));+ // The in-process node forwards the caller's credential the way the HTTP+ // route forwards its header; it has no auth layer of its own, so this is+ // informational, never a grant.+ let auth = request+ .metadata()+ .get("authorization")+ .and_then(|v| v.to_str().ok())+ .and_then(|v| axum::http::HeaderValue::from_str(v).ok());+ Ok(Caller { visibility, auth })+ }+}++struct Caller {+ visibility: Option<Arc<dyn index_guard::IndexVisibility>>,+ auth: Option<axum::http::HeaderValue>,+}++#[tonic::async_trait]+impl XerjHub for HubService {+ async fn ask(+ &self,+ request: Request<pb::HubAskRequest>,+ ) -> Result<Response<pb::HubAnswer>, Status> {+ let caller = self.admit(&request)?;+ let req = request.into_inner();+ let ask = ask_from_pb(req)?;+ let answer = index_guard::scoped_opt(+ caller.visibility,+ hub_api::ask_answer(&self.shared, ask, caller.auth),+ )+ .await+ .map_err(refusal_status)?;+ Ok(Response::new(answer_to_pb(&answer)))+ }++ async fn def(+ &self,+ request: Request<pb::HubDefRequest>,+ ) -> Result<Response<pb::HubAnswer>, Status> {+ let caller = self.admit(&request)?;+ let req = request.into_inner();+ let answer = index_guard::scoped_opt(+ caller.visibility,+ hub_api::def_answer(+ &self.shared,+ &req.slug,+ &req.symbol,+ req.k as usize,+ caller.auth,+ ),+ )+ .await+ .map_err(refusal_status)?;+ Ok(Response::new(answer_to_pb(&answer)))+ }++ async fn catalogue(+ &self,+ request: Request<pb::HubCatalogueRequest>,+ ) -> Result<Response<pb::HubCatalogueResponse>, Status> {+ self.admit(&request)?;+ let signed = hub_api::catalogue_signed(&self.shared)+ .await+ .map_err(refusal_status)?;+ Ok(Response::new(pb::HubCatalogueResponse {+ catalogue_json: signed.bytes.to_vec(),+ signature: signed.signature,+ }))+ }+}++// ── request decoding ─────────────────────────────────────────────────────────++/// `HubAskRequest` → [`HubAsk`]: `corpus` and `mode` empty = auto, `max_tokens`+/// 0 = none. The question, the corpus and the budget are validated by+/// `ask_answer` itself (the HTTP limits); only the mode's spelling is checked+/// here, because it is this surface's own string.+#[allow(clippy::result_large_err)]+fn ask_from_pb(req: pb::HubAskRequest) -> Result<HubAsk, Status> {+ let mode = if req.mode.is_empty() {+ None+ } else {+ Some(enum_from::<AnswerMode>(&req.mode).map_err(|_| {+ Status::invalid_argument(format!(+ "mode must be def, how or files (or empty for auto), got [{}]",+ hub_api::truncate_chars(&req.mode, 32)+ ))+ })?)+ };+ Ok(HubAsk {+ question: req.question,+ corpus: (!req.corpus.is_empty()).then_some(req.corpus),+ mode,+ max_tokens: (req.max_tokens > 0).then_some(u64::from(req.max_tokens)),+ })+}++/// The route's HTTP status as a gRPC code, with its reason, and `Retry-After`+/// carried as `retry-after` metadata.+fn refusal_status(r: HubRefusal) -> Status {+ use tonic::Code;+ let code = match r.status.as_u16() {+ 400 => Code::InvalidArgument,+ 401 => Code::Unauthenticated,+ 403 => Code::PermissionDenied,+ 404 => Code::NotFound,+ // `Ask` with more than one candidate corpus: re-ask naming one.+ 409 => Code::FailedPrecondition,+ 429 => Code::ResourceExhausted,+ 503 => Code::Unavailable,+ 504 => Code::DeadlineExceeded,+ _ => Code::Internal,+ };+ let mut status = Status::new(code, r.reason);+ if let Some(v) = r.retry_after.and_then(|v| v.parse().ok()) {+ status.metadata_mut().insert("retry-after", v);+ }+ status+}// ── the frozen mapping: Answer ↔ HubAnswer ───────────────────────────────────@@ -47,6 +237,7 @@ fn opt_out(v: &Option<String>) -> String {}/// `""` → `None` on the way in.+#[cfg_attr(not(test), allow(dead_code))] // the decode half; the server only encodesfn opt_in(s: &str) -> Option<String> {(!s.is_empty()).then(|| s.to_string())}@@ -81,7 +272,9 @@ pub fn answer_to_pb(a: &Answer) -> pb::HubAnswer {}/// [`pb::HubAnswer`] → [`Answer`]: what a Rust gRPC client decodes with. An-/// enum string this build does not know is an error, not a default.+/// enum string this build does not know is an error, not a default. The server+/// only encodes; the decode half is the client's, pinned here by the tests.+#[cfg_attr(not(test), allow(dead_code))]pub fn answer_from_pb(p: &pb::HubAnswer) -> Result<Answer, String> {Ok(Answer {corpus: p.corpus.clone(),@@ -113,7 +306,7 @@ pub fn answer_from_pb(p: &pb::HubAnswer) -> Result<Answer, String> {#[cfg(test)]mod tests {use super::*;- use xerj_common::hub::{AnswerMode, AnsweredFrom, LicenceClass};+ use xerj_common::hub::{AnsweredFrom, LicenceClass};fn hit(value: Option<&str>, warning: Option<&str>) -> Hit {Hit {@@ -229,4 +422,540 @@ mod tests {p.answered_from = "hosted hub".into(); // the label, not the wire formassert!(answer_from_pb(&p).is_err());}++ #[test]+ fn ask_requests_decode_empty_as_auto_and_refuse_a_bad_mode() {+ let ask = ask_from_pb(pb::HubAskRequest {+ question: "q".into(),+ corpus: String::new(),+ mode: String::new(),+ max_tokens: 0,+ })+ .unwrap();+ assert_eq!((ask.corpus, ask.mode, ask.max_tokens), (None, None, None));+ let ask = ask_from_pb(pb::HubAskRequest {+ question: "q".into(),+ corpus: "mini-c".into(),+ mode: "files".into(),+ max_tokens: 200,+ })+ .unwrap();+ assert_eq!(ask.corpus.as_deref(), Some("mini-c"));+ assert_eq!(ask.mode, Some(AnswerMode::Files));+ assert_eq!(ask.max_tokens, Some(200));+ let err = ask_from_pb(pb::HubAskRequest {+ question: "q".into(),+ corpus: String::new(),+ mode: "semantic".into(),+ max_tokens: 0,+ })+ .unwrap_err();+ assert_eq!(err.code(), tonic::Code::InvalidArgument);+ }++ #[test]+ fn refusals_keep_their_meaning_as_grpc_codes() {+ use axum::http::StatusCode;+ let r = |status: StatusCode| HubRefusal {+ status,+ reason: "why".into(),+ retry_after: Some("3".into()),+ };+ assert_eq!(+ refusal_status(r(StatusCode::NOT_FOUND)).code(),+ tonic::Code::NotFound+ );+ assert_eq!(+ refusal_status(r(StatusCode::BAD_REQUEST)).code(),+ tonic::Code::InvalidArgument+ );+ assert_eq!(+ refusal_status(r(StatusCode::CONFLICT)).code(),+ tonic::Code::FailedPrecondition+ );+ let limited = refusal_status(r(StatusCode::TOO_MANY_REQUESTS));+ assert_eq!(limited.code(), tonic::Code::ResourceExhausted);+ assert_eq!(limited.metadata().get("retry-after").unwrap(), "3");+ assert_eq!(limited.message(), "why");+ }++ // ── end to end: a real node, a restored fixture corpus, a real listener ──++ mod e2e {+ use super::super::*;+ use crate::grpc::pb::xerj_hub_client::XerjHubClient;+ use axum::body::Body;+ use serde_json::{json, Value};+ use std::sync::OnceLock;+ use tower::ServiceExt;+ use xerj_common::hub::{Catalogue, CatalogueEntry, LicenceClass, CATALOGUE_FORMAT_VERSION};++ const PIN_SHA: &str = "0774d05537f9762f838f7ab541b7765f1a729cb5";+ const PIN_DATE: &str = "2026-10-02";+ const ADMIN_KEY: &str = "grpc-hub-test-admin-key";+ /// 64 bytes, hex: what a detached `.sig` file holds.+ const SIG_HEX: &str = "0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20\+ 2122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f40";++ struct Fixture {+ catalogue: std::path::PathBuf,+ }++ /// The ledger root is process-global (`XERJ_CODE_HOME`): one fixture,+ /// exported once, as `xerj-api/tests/hub_api.rs` does.+ fn fixture() -> &'static Fixture {+ static FX: OnceLock<Fixture> = OnceLock::new();+ FX.get_or_init(|| {+ let dir = tempfile::tempdir().unwrap().keep();+ let home = dir.join("code-home");+ let led = |slug: &str, spdx: &str, class: &str| {+ xerj_common::xccode::state::write_hubpack_state(+ &home,+ slug,+ "http://x",+ &format!("xc-{slug}-b1"),+ PIN_SHA,+ PIN_DATE,+ spdx,+ class,+ )+ .unwrap();+ };+ led("mini-c", "MIT", "adapt-with-attribution");+ led("mini-gpl", "GPL-3.0-only", "approach-only");+ led("mini-closed", "LicenseRef-Closed", "excluded");+ let entry =+ |slug: &str, spdx: &str, class: LicenceClass, terms: &[&str]| CatalogueEntry {+ slug: slug.into(),+ domain: "DEV".into(),+ topics: vec![],+ ask_for: format!("fixture corpus {slug}"),+ pin_sha: PIN_SHA.into(),+ pin_date: PIN_DATE.into(),+ refresh_cadence_days: 7,+ licence_spdx: spdx.into(),+ licence_class: class,+ pack_bytes: 1024,+ pack_url: String::new(),+ pack_sha256: "0".repeat(64),+ sig_url: String::new(),+ dependency_names: vec![],+ quality_grade: None,+ term_sketch: xerj_hub::sketch::build(terms.iter().map(|t| t.to_string())),+ };+ let cat = Catalogue {+ format_version: CATALOGUE_FORMAT_VERSION,+ generated_at: "2026-10-14T00:00:00Z".into(),+ corpora: vec![+ entry(+ "mini-c",+ "MIT",+ LicenceClass::AdaptWithAttribution,+ &["MINI_LIMIT", "mini_hash", "frobnicate", "hash"],+ ),+ entry(+ "mini-gpl",+ "GPL-3.0-only",+ LicenceClass::ApproachOnly,+ &["GPL_LIMIT", "copyleft"],+ ),+ entry(+ "mini-closed",+ "LicenseRef-Closed",+ LicenceClass::Excluded,+ &["CLOSED_LIMIT", "secret"],+ ),+ entry(+ "filler-a",+ "MIT",+ LicenceClass::AdaptWithAttribution,+ &["alpha"],+ ),+ entry(+ "filler-b",+ "MIT",+ LicenceClass::AdaptWithAttribution,+ &["bravo"],+ ),+ ],+ };+ let catalogue = dir.join("catalogue.json");+ std::fs::write(&catalogue, serde_json::to_vec(&cat).unwrap()).unwrap();+ std::fs::write(dir.join("catalogue.json.sig"), format!("{SIG_HEX}\n")).unwrap();+ std::env::set_var("XERJ_CODE_HOME", &home);+ Fixture { catalogue }+ })+ }++ fn state(dir: &std::path::Path) -> AppState {+ let fx = fixture();+ let mut config = xerj_common::config::Config::default();+ config.server.data_dir = dir.to_string_lossy().into_owned();+ config.storage.wal_sync = xerj_common::config::WalSync::Async;+ config.hub.catalogue_path = fx.catalogue.to_string_lossy().into_owned();+ config.auth.enabled = true;+ config.auth.admin_api_key = ADMIN_KEY.into();+ let metrics = xerj_common::metrics::Metrics::new().unwrap();+ let engine = xerj_engine::Engine::new(config.clone()).unwrap();+ AppState::new(config, engine, metrics)+ }++ async fn http(+ app: &axum::Router,+ method: &str,+ path: &str,+ body: Option<String>,+ ) -> (u16, Value) {+ let mut b = axum::http::Request::builder()+ .method(method)+ .uri(path)+ .header("authorization", format!("ApiKey {ADMIN_KEY}"));+ if body.is_some() {+ b = b.header(+ "content-type",+ if path.ends_with("_bulk") {+ "application/x-ndjson"+ } else {+ "application/json"+ },+ );+ }+ let req = b+ .body(body.map(Body::from).unwrap_or_else(Body::empty))+ .unwrap();+ let resp = app.clone().oneshot(req).await.unwrap();+ let status = resp.status().as_u16();+ let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)+ .await+ .unwrap();+ (+ status,+ serde_json::from_slice(&bytes).unwrap_or(Value::Null),+ )+ }++ async fn seed(+ app: &axum::Router,+ slug: &str,+ defs: &[(&str, &str, u32, &str, Option<&str>)],+ ) {+ let index = format!("xc-{slug}-b1-defs");+ let mapping = json!({ "mappings": { "properties": {+ "symbol": {"type": "keyword"}, "symbol_text": {"type": "text"},+ "kind": {"type": "keyword"}, "lang": {"type": "keyword"},+ "file": {"type": "keyword"}, "line": {"type": "integer"},+ "text": {"type": "text"}, "value": {"type": "keyword"}+ }}});+ let (st, v) = http(app, "PUT", &format!("/{index}"), Some(mapping.to_string())).await;+ assert!(st < 300, "create {index}: {v}");+ let mut nd = String::new();+ for (symbol, file, line, text, value) in defs {+ nd.push_str("{\"index\":{}}\n");+ nd.push_str(+ &json!({"symbol": symbol, "symbol_text": symbol, "kind": "define",+ "lang": "c", "file": file, "line": line, "text": text, "value": value})+ .to_string(),+ );+ nd.push('\n');+ }+ let (st, v) = http(+ app,+ "POST",+ &format!("/{index}/_bulk?refresh=true"),+ Some(nd),+ )+ .await;+ assert!(st < 300 && v["errors"] == json!(false), "bulk {index}: {v}");+ let docs = format!("xc-{slug}-b1-docs");+ let (st, v) = http(+ app,+ "POST",+ &format!("/{docs}/_bulk?refresh=true"),+ Some(format!(+ "{{\"index\":{{}}}}\n{}\n",+ json!({"ax_path": format!("{slug}/hash.c"), "title": "hash.c",+ "body": "unsigned mini_hash(const char *s) { frobnicate the buffer; }"})+ )),+ )+ .await;+ assert!(st < 300, "bulk {docs}: {v}");+ }++ fn keyed<T>(msg: T) -> tonic::Request<T> {+ let mut r = tonic::Request::new(msg);+ r.metadata_mut().insert(+ "authorization",+ format!("ApiKey {ADMIN_KEY}").parse().unwrap(),+ );+ r+ }++ /// One test, scenarios in order: they share the process-global ledger+ /// root and one node.+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]+ async fn xerj_hub_rpcs_answer_exactly_like_the_http_routes() {+ let fx = fixture();+ let data = tempfile::tempdir().unwrap();+ let state = state(data.path());+ let app = xerj_api::router::build_es_compat_router(state.clone());+ seed(+ &app,+ "mini-c",+ &[(+ "MINI_LIMIT",+ "limits.h",+ 5,+ "#define MINI_LIMIT 128",+ Some("128"),+ )],+ )+ .await;+ seed(+ &app,+ "mini-gpl",+ &[("GPL_LIMIT", "gpl.h", 3, "#define GPL_LIMIT 7", Some("7"))],+ )+ .await;+ seed(+ &app,+ "mini-closed",+ &[(+ "CLOSED_LIMIT",+ "c.h",+ 1,+ "#define CLOSED_LIMIT 1",+ Some("1"),+ )],+ )+ .await;++ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();+ listener.set_nonblocking(true).unwrap();+ let port = listener.local_addr().unwrap().port();+ let (tx, rx) = tokio::sync::oneshot::channel::<()>();+ let server = tokio::spawn(crate::grpc::serve_grpc_on(+ listener,+ state.clone(),+ async move {+ let _ = rx.await;+ },+ ));+ let url = format!("http://127.0.0.1:{port}");+ let mut client = None;+ for _ in 0..50 {+ if let Ok(c) = XerjHubClient::connect(url.clone()).await {+ client = Some(c);+ break;+ }+ tokio::time::sleep(std::time::Duration::from_millis(20)).await;+ }+ let mut client = client.expect("gRPC client connects");++ // No credential: the shared interceptor refuses before the service.+ let err = client+ .def(tonic::Request::new(pb::HubDefRequest {+ slug: "mini-c".into(),+ symbol: "MINI_LIMIT".into(),+ k: 0,+ }))+ .await+ .unwrap_err();+ assert_eq!(err.code(), tonic::Code::Unauthenticated);++ // Def == GET /_hub/v1/def, field by field.+ let grpc = client+ .def(keyed(pb::HubDefRequest {+ slug: "mini-c".into(),+ symbol: "MINI_LIMIT".into(),+ k: 0,+ }))+ .await+ .expect("Def answers")+ .into_inner();+ let (st, body) = http(&app, "GET", "/_hub/v1/def/mini-c/MINI_LIMIT", None).await;+ assert_eq!(st, 200, "{body}");+ let via_http: Answer = serde_json::from_value(body).unwrap();+ assert_eq!(+ grpc,+ answer_to_pb(&via_http),+ "gRPC Def and the HTTP route agree on every field"+ );+ let a = answer_from_pb(&grpc).unwrap();+ assert_eq!(a.corpus, "mini-c");+ assert_eq!(a.hits.len(), 1);+ assert_eq!(a.hits[0].value.as_deref(), Some("128"));+ assert_eq!((a.hits[0].file.as_str(), a.hits[0].line), ("limits.h", 5));+ assert_eq!(grpc.answered_from, "hosted");+ assert_eq!(grpc.mode, "def");+ assert_eq!(+ grpc.hits[0].licence_warning, "",+ "a permissive corpus carries no warning"+ );++ // Approach-only: every hit carries the read-do-not-copy warning.+ let gpl = client+ .def(keyed(pb::HubDefRequest {+ slug: "mini-gpl".into(),+ symbol: "GPL_LIMIT".into(),+ k: 0,+ }))+ .await+ .unwrap()+ .into_inner();+ assert_eq!(gpl.licence_class, "approach-only");+ assert!(!gpl.hits.is_empty());+ for h in &gpl.hits {+ assert_eq!(+ h.licence_warning,+ "approach-only licence (GPL-3.0-only): read, do not copy"+ );+ }++ // Excluded: never served, by Def or by Ask, named or routed.+ for err in [+ client+ .def(keyed(pb::HubDefRequest {+ slug: "mini-closed".into(),+ symbol: "CLOSED_LIMIT".into(),+ k: 0,+ }))+ .await+ .unwrap_err(),+ client+ .ask(keyed(pb::HubAskRequest {+ question: "CLOSED_LIMIT".into(),+ corpus: "mini-closed".into(),+ mode: String::new(),+ max_tokens: 0,+ }))+ .await+ .unwrap_err(),+ ] {+ assert_eq!(err.code(), tonic::Code::NotFound, "{err:?}");+ assert!(+ !err.message().contains("closed"),+ "a refusal names nothing: {err:?}"+ );+ }+ let routed = client+ .ask(keyed(pb::HubAskRequest {+ question: "what is the value of CLOSED_LIMIT".into(),+ corpus: String::new(),+ mode: String::new(),+ max_tokens: 0,+ }))+ .await;+ assert!(+ routed.is_err(),+ "an excluded corpus is never routed to: {routed:?}"+ );++ // Limits: the HTTP routes' own.+ let err = client+ .def(keyed(pb::HubDefRequest {+ slug: "mini-c".into(),+ symbol: "x".repeat(600),+ k: 0,+ }))+ .await+ .unwrap_err();+ assert_eq!(err.code(), tonic::Code::InvalidArgument);+ let err = client+ .def(keyed(pb::HubDefRequest {+ slug: "../etc".into(),+ symbol: "MINI_LIMIT".into(),+ k: 0,+ }))+ .await+ .unwrap_err();+ assert_eq!(err.code(), tonic::Code::NotFound);+ let err = client+ .ask(keyed(pb::HubAskRequest {+ question: "q".into(),+ corpus: String::new(),+ mode: "semantic".into(),+ max_tokens: 0,+ }))+ .await+ .unwrap_err();+ assert_eq!(err.code(), tonic::Code::InvalidArgument);++ // Ask, corpus omitted: routed by the sketch, answered in def mode.+ let ask = client+ .ask(keyed(pb::HubAskRequest {+ question: "what is the value of MINI_LIMIT".into(),+ corpus: String::new(),+ mode: String::new(),+ max_tokens: 0,+ }))+ .await+ .expect("Ask answers")+ .into_inner();+ assert_eq!(ask.corpus, "mini-c", "the corpus is always named");+ assert_eq!(ask.mode, "def");+ assert_eq!(ask.hits[0].value, "128");+ assert_eq!(ask.answered_from, "hosted");++ // Ask, named corpus, a how question: passages from the docs index.+ let how = client+ .ask(keyed(pb::HubAskRequest {+ question: "frobnicate".into(),+ corpus: "mini-c".into(),+ mode: "how".into(),+ max_tokens: 0,+ }))+ .await+ .expect("Ask how answers")+ .into_inner();+ assert_eq!(how.mode, "how");+ assert!(+ how.hits.iter().any(|h| h.file.contains("hash.c")),+ "{how:?}"+ );++ // Ask on an approach-only corpus: the flow's warning line as well.+ let ask_gpl = client+ .ask(keyed(pb::HubAskRequest {+ question: "GPL_LIMIT".into(),+ corpus: "mini-gpl".into(),+ mode: "def".into(),+ max_tokens: 0,+ }))+ .await+ .unwrap()+ .into_inner();+ assert!(+ ask_gpl+ .warnings+ .iter()+ .any(|w| w.starts_with("approach-only licence (GPL-3.0-only)")),+ "{ask_gpl:?}"+ );+ assert!(ask_gpl.hits.iter().all(|h| !h.licence_warning.is_empty()));++ // Catalogue: the file's exact bytes and the decoded detached signature.+ let cat = client+ .catalogue(keyed(pb::HubCatalogueRequest {}))+ .await+ .unwrap()+ .into_inner();+ assert_eq!(cat.catalogue_json, std::fs::read(&fx.catalogue).unwrap());+ assert_eq!(cat.signature.len(), 64);+ assert_eq!(cat.signature[0], 1);+ assert_eq!(cat.signature[63], 0x40);++ // Nothing above wrote to the node: same indices, same counts.+ let (_, indices) = http(+ &app,+ "GET",+ "/_cat/indices/xc-*?format=json&h=index,docs.count",+ None,+ )+ .await;+ assert_eq!(indices.as_array().map(Vec::len), Some(6), "{indices}");++ let _ = tx.send(());+ let _ = server.await;+ }+ }}diff --git a/engine/crates/xerj-server/src/main.rs b/engine/crates/xerj-server/src/main.rsindex fd58538bd..39154fe69 100644--- a/engine/crates/xerj-server/src/main.rs+++ b/engine/crates/xerj-server/src/main.rs@@ -96,9 +96,6 @@ mod brain;#[cfg(all(target_os = "linux", feature = "debug-profiling"))]mod debug_profiling;mod grpc;-// Corpus Hub v2: the XerjHub wire mapping. The service that calls it lands in-// the next step-7 slice; until then only its tests do.-#[cfg_attr(not(test), allow(dead_code))]mod grpc_hub;mod ingest_memory_trace;mod share;diff --git a/engine/proto/xerj.proto b/engine/proto/xerj.protoindex 009c8d77d..21e31d3e7 100644--- a/engine/proto/xerj.proto+++ b/engine/proto/xerj.proto@@ -93,9 +93,9 @@ message HealthResponse {// below records its live field-number range in a comment; new fields may only// be appended with the next free number.//-// The service trait and client are generated by build.rs (tonic/prost) but the-// server impl and `add_service` registration in grpc.rs/main.rs are DEFERRED to-// step 5/7 — the generated-but-unimplemented scaffolding is intentional here.+// The service trait and client are generated by build.rs (tonic/prost); the+// server impl is engine/crates/xerj-server/src/grpc_hub.rs, registered in+// grpc.rs next to XerjSearch behind the same interceptor.// ===========================================================================service XerjHub {rpc Ask(HubAskRequest) returns (HubAnswer);