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.

feat(hub): Corpus Hub v2 keystone — pack build/pull + def mode (plan §2+§3)

xerj-org04a7f69e18f2
diff --git a/engine/Cargo.lock b/engine/Cargo.lock
index fd8c8035b..cf32b18e5 100644
--- a/engine/Cargo.lock
+++ b/engine/Cargo.lock
@@ -7649,6 +7649,7 @@ name = "xerj-hub"
version = "1.0.0-rc.95"
dependencies = [
"anyhow",
+ "axum",
"base64 0.23.1",
"chrono",
"reqwest",
@@ -7657,9 +7658,12 @@ dependencies = [
"sha2 0.10.9",
"tar",
"tempfile",
+ "tokio",
"toml",
+ "xerj-api",
"xerj-autoindex",
"xerj-common",
+ "xerj-engine",
"zstd",
]
@@ -7766,6 +7770,7 @@ dependencies = [
"xerj-console-api",
"xerj-engine",
"xerj-fts",
+ "xerj-hub",
"xerj-logs",
"xerj-mcp",
"xerj-query",
diff --git a/engine/crates/xerj-common/src/xccode/state.rs b/engine/crates/xerj-common/src/xccode/state.rs
index 30d9f6c2b..e84e90839 100644
--- a/engine/crates/xerj-common/src/xccode/state.rs
+++ b/engine/crates/xerj-common/src/xccode/state.rs
@@ -20,6 +20,13 @@ use serde_json::{json, Value};
use super::STALE_DAYS;
+/// The `source` value a Corpus-Hub-v2 pack writes into its state file
+/// ([`write_hubpack_state`]). A ledger carrying this came from a pulled,
+/// pre-indexed pack, not from a local clone-and-index — the distinction the
+/// staleness rule keys on (a hub pack is re-pinned by CI, so its freshness is
+/// the catalogue's job, not a 30-day local refusal).
+pub const SOURCE_HUBPACK: &str = "hubpack";
+
/// One parsed state file. Every field optional; unknown fields ignored.
#[derive(Debug, Clone, Default)]
pub struct CorpusState {
@@ -34,6 +41,20 @@ pub struct CorpusState {
pub build: Option<String>,
pub index_prefix: Option<String>,
pub state_dir: Option<String>,
+ /// `"hubpack"` when the index came from a Corpus-Hub-v2 pack
+ /// ([`write_hubpack_state`]); absent for a locally indexed corpus. Additive
+ /// field — older readers ignore it, older files leave it `None`.
+ pub source: Option<String>,
+ /// The pack's pinned commit (hub packs only). Carried so the `def`/`code`
+ /// answer can name the exact source revision without re-reading the pack.
+ pub pin_sha: Option<String>,
+ /// `YYYY-MM-DD` the pin was taken (hub packs only).
+ pub pin_date: Option<String>,
+ /// SPDX id of the pack's licence (hub packs only).
+ pub licence_spdx: Option<String>,
+ /// The pack's licence class, kebab-case (hub packs only) —
+ /// `adapt-with-attribution` / `approach-only` / `excluded`.
+ pub licence_class: Option<String>,
}
impl CorpusState {
@@ -49,6 +70,11 @@ impl CorpusState {
build: s("build"),
index_prefix: s("index_prefix"),
state_dir: s("state_dir"),
+ source: s("source"),
+ pin_sha: s("pin_sha"),
+ pin_date: s("pin_date"),
+ licence_spdx: s("licence_spdx"),
+ licence_class: s("licence_class"),
}
}
@@ -56,6 +82,12 @@ impl CorpusState {
pub fn name(&self, fallback: &str) -> String {
self.corpus.clone().unwrap_or_else(|| fallback.to_string())
}
+
+ /// True when this ledger came from a hub pack ([`SOURCE_HUBPACK`]). A hub
+ /// pack is never refused for age — its freshness is the catalogue's job.
+ pub fn is_hubpack(&self) -> bool {
+ self.source.as_deref() == Some(SOURCE_HUBPACK)
+ }
}
/// Read `{root}/state/{corpus}.json`. Missing → the actionable refusal that
@@ -100,6 +132,13 @@ pub fn check_fresh(
return Ok(None);
};
let age = Utc::now().signed_duration_since(dt).num_days();
+ // A hub pack is re-pinned by CI, not re-indexed locally, so a 30-day-old
+ // local copy is not a stale local index — its freshness is the catalogue's
+ // job (plan §2, the staleness-rule change). Report the age (the footer and
+ // a newer-pin warning still use it) but never refuse it.
+ if st.is_hubpack() {
+ return Ok(Some(age));
+ }
if age > STALE_DAYS && !stale_ok {
let corpus = st.name("");
return Err(format!(
@@ -209,11 +248,70 @@ pub fn write_state(
obj.insert("index_prefix".into(), json!(ip));
obj.insert("state_dir".into(), json!(sd));
}
+ persist_state(root, corpus, &state)
+}
+
+/// Write the ledger for a corpus restored from a Corpus-Hub-v2 pack
+/// (plan §2, `xerj hub pull`). It reuses the same atomic writer and the same
+/// base schema as [`write_state`] so `xerj code <corpus>` finds it unchanged,
+/// and adds the hub fields: `source: "hubpack"` (never refused for age — see
+/// [`check_fresh`]), the pack's `pin_sha`/`pin_date` and its licence, so a
+/// `def`/`code` answer can name the exact pinned source and its licence
+/// without re-reading the pack.
+///
+/// `index_prefix` is the pack's `xc-<slug>-b<build>`; the verified-build token
+/// is derived from it so the query path pins that one build (no
+/// "no verified build recorded" widening). `autoindex_exit: 0` /
+/// `salvaged: false` mark the pack complete (a CI-built pack is verified), so
+/// no incomplete-coverage warning fires.
+#[allow(clippy::too_many_arguments)]
+pub fn write_hubpack_state(
+ root: &Path,
+ corpus: &str,
+ url: &str,
+ index_prefix: &str,
+ pin_sha: &str,
+ pin_date: &str,
+ licence_spdx: &str,
+ licence_class: &str,
+) -> std::io::Result<()> {
+ let mut state = json!({
+ "corpus": corpus,
+ "indexed_at": Utc::now().format(STAMP_FORMAT).to_string(),
+ "prefix": format!("xc-{corpus}"),
+ "url": url,
+ "autoindex_exit": 0,
+ "salvaged": false,
+ "index_prefix": index_prefix,
+ "source": SOURCE_HUBPACK,
+ "pin_sha": pin_sha,
+ "pin_date": pin_date,
+ "licence_spdx": licence_spdx,
+ "licence_class": licence_class,
+ });
+ // The verified-build token is the part of the prefix after `xc-<corpus>-`
+ // (e.g. `xc-lz4-b1` -> `b1`); recording it keeps parity with a locally
+ // indexed corpus's ledger. Absent only if the prefix is not the usual
+ // shape — the query still pins the exact `index_prefix` either way.
+ if let Some(build) = index_prefix.strip_prefix(&format!("xc-{corpus}-")) {
+ if !build.is_empty() {
+ state
+ .as_object_mut()
+ .unwrap()
+ .insert("build".into(), json!(build));
+ }
+ }
+ persist_state(root, corpus, &state)
+}
+
+/// Atomic write of a ledger `Value` to `{root}/state/{corpus}.json` (tmp +
+/// rename): a reader sees the old build or the new one, never half. Compact
+/// separators, trailing newline — the script's exact bytes.
+fn persist_state(root: &Path, corpus: &str, state: &Value) -> std::io::Result<()> {
let dir = root.join("state");
std::fs::create_dir_all(&dir)?;
let path = dir.join(format!("{corpus}.json"));
let tmp = dir.join(format!(".{corpus}.json.tmp"));
- // Compact separators, trailing newline — the script's exact bytes.
std::fs::write(&tmp, format!("{state}\n"))?;
std::fs::rename(&tmp, &path)
}
@@ -453,4 +551,57 @@ mod tests {
let st = load_state(root.path(), "kv").unwrap();
assert_eq!(st.index_prefix.as_deref(), Some("xc-kv-b20260921"));
}
+
+ #[test]
+ fn hubpack_state_carries_source_pin_and_licence_and_pins_the_build() {
+ let root = tempfile::tempdir().unwrap();
+ write_hubpack_state(
+ root.path(),
+ "lz4",
+ "http://localhost:9400",
+ "xc-lz4-b1",
+ "0774d05537f9762f838f7ab541b7765f1a729cb5",
+ "2026-10-02",
+ "BSD-2-Clause",
+ "adapt-with-attribution",
+ )
+ .unwrap();
+ let st = load_state(root.path(), "lz4").unwrap();
+ assert!(st.is_hubpack(), "source must be hubpack: {:?}", st.source);
+ assert_eq!(st.source.as_deref(), Some("hubpack"));
+ assert_eq!(st.index_prefix.as_deref(), Some("xc-lz4-b1"));
+ // The verified build is pinned (no namespace widening at query time).
+ assert_eq!(query_prefix(&st), "xc-lz4-b1");
+ assert_eq!(st.build.as_deref(), Some("b1"));
+ assert_eq!(
+ st.pin_sha.as_deref(),
+ Some("0774d05537f9762f838f7ab541b7765f1a729cb5")
+ );
+ assert_eq!(st.pin_date.as_deref(), Some("2026-10-02"));
+ assert_eq!(st.licence_spdx.as_deref(), Some("BSD-2-Clause"));
+ assert_eq!(st.licence_class.as_deref(), Some("adapt-with-attribution"));
+ // A verified pack must not trip the incomplete-coverage warning.
+ assert!(incomplete_coverage(&st).is_none());
+ // Atomic write leaves no tmp file.
+ assert!(!root.path().join("state/.lz4.json.tmp").exists());
+ }
+
+ #[test]
+ fn a_hub_pack_is_never_refused_for_age() {
+ // The staleness-rule change: a 400-day-old hub pack still answers
+ // (freshness is the catalogue's job), while a locally indexed corpus of
+ // the same age is refused.
+ let root = tempfile::tempdir().unwrap();
+ let mut st = aged(root.path(), "lz4", 400);
+ assert!(
+ check_fresh(&st, false, "`--stale-ok`").is_err(),
+ "a local index this old is refused"
+ );
+ st.source = Some(SOURCE_HUBPACK.to_string());
+ assert_eq!(
+ check_fresh(&st, false, "`--stale-ok`").unwrap(),
+ Some(400),
+ "a hub pack reports its age but is never refused"
+ );
+ }
}
diff --git a/engine/crates/xerj-hub/Cargo.toml b/engine/crates/xerj-hub/Cargo.toml
index bd2e4fd00..955a0c4bb 100644
--- a/engine/crates/xerj-hub/Cargo.toml
+++ b/engine/crates/xerj-hub/Cargo.toml
@@ -22,3 +22,13 @@ tar = "0.4"
[dev-dependencies]
tempfile.workspace = true
+# The pack roundtrip test boots a real in-process node (ephemeral TCP port) so
+# the builder/pull snapshot+restore HTTP calls run end to end.
+xerj-api = { path = "../xerj-api" }
+xerj-engine = { path = "../xerj-engine" }
+xerj-common = { path = "../xerj-common" }
+xerj-autoindex = { path = "../xerj-autoindex" }
+tokio = { workspace = true }
+axum.workspace = true
+sha2 = "0.10"
+serde_json = { workspace = true }
diff --git a/engine/crates/xerj-hub/src/cli.rs b/engine/crates/xerj-hub/src/cli.rs
new file mode 100644
index 000000000..8d6d2a910
--- /dev/null
+++ b/engine/crates/xerj-hub/src/cli.rs
@@ -0,0 +1,879 @@
+//! Corpus Hub v2 — the `xerj hub …` subcommands and the `--def` code path
+//! (plan §2 builder + client, §3 `def`).
+//!
+//! Three entry points, all returning a process exit code:
+//!
+//! - [`run_hub_cli`] dispatches `xerj hub build-pack` (CI builds a signed,
+//! pre-indexed pack) and `xerj hub pull` (a client downloads, verifies and
+//! restores one). Future hub subcommands (status, sync, …) are plan §5/§8.
+//! - [`run_code`] is the `xerj code` front door: `--def <SYMBOL>` answers from
+//! the corpus's `-defs` index via [`crate::def::lookup`] and the shared
+//! renderer; everything else delegates unchanged to the existing
+//! `xerj_autoindex::xc::run_code_cli`.
+//!
+//! The crate graph forbids `run_code_query` (in `xerj-common`) from calling
+//! `def::lookup` (here, above `xerj-autoindex`), so the plan's "`run_code_query`
+//! calls `lookup`" is realised one layer up, in `run_code`, which sees both the
+//! code CLI and `def::lookup` without a dependency cycle. The user-facing
+//! contract is identical: `xerj code <slug> --def <SYMBOL>` prints a def answer
+//! through the §1 renderer.
+
+use std::fs;
+use std::path::{Path, PathBuf};
+use std::time::Duration;
+
+use anyhow::{anyhow, bail, Context, Result};
+use serde_json::{json, Value};
+
+use xerj_common::hub::{
+ render, Answer, LicenceClass, PackIndex, PackManifest, PackSource, DEFAULT_HUB_URL,
+ HUB_PUBKEY_HEX, PACK_FORMAT_VERSION,
+};
+use xerj_common::xccode::manifest::read_hub_manifest;
+use xerj_common::xccode::state;
+use xerj_common::xccode::XcHttp;
+
+use crate::catalogue::{build_catalogue, load_catalogue, CorpusBuildInput};
+use crate::node::{resolve_url, HubNode};
+use crate::pack;
+
+const HUB_USAGE: &str = "usage: xerj hub <command>
+
+ build-pack <slug> --registry <dir> --out <dir> --url <node> --sign-key <seed-file>
+ Build a signed, pre-indexed pack from a registry manifest (CI).
+ pull <slug> [--quiet] [--url <node>]
+ Download, verify and restore a pack, then `xerj code <slug>` works.
+
+Packs are pulled on demand and never cloned or indexed on the user's machine
+(docs/CORPUS_HUB_V2_IMPLEMENTATION.md).";
+
+/// `xerj hub <command> …`.
+pub fn run_hub_cli(args: &[String]) -> i32 {
+ let Some(sub) = args.first() else {
+ eprintln!("{HUB_USAGE}");
+ return 2;
+ };
+ let rest = &args[1..];
+ match sub.as_str() {
+ "build-pack" => run_build_pack(rest),
+ "pull" => run_pull(rest),
+ "-h" | "--help" | "help" => {
+ println!("{HUB_USAGE}");
+ 0
+ }
+ other => {
+ eprintln!("xerj hub: unknown command '{other}'\n\n{HUB_USAGE}");
+ 2
+ }
+ }
+}
+
+// ── xerj hub build-pack ──────────────────────────────────────────────────────
+
+fn run_build_pack(args: &[String]) -> i32 {
+ let mut slug: Option<String> = None;
+ let mut registry: Option<String> = None;
+ let mut out: Option<String> = None;
+ let mut url: Option<String> = None;
+ let mut sign_key: Option<String> = None;
+ let mut i = 0;
+ while i < args.len() {
+ macro_rules! val {
+ ($n:expr) => {
+ match args.get(i + 1) {
+ Some(v) => {
+ i += 1;
+ v.clone()
+ }
+ None => {
+ eprintln!("xerj hub build-pack: {} needs a value\n\n{HUB_USAGE}", $n);
+ return 2;
+ }
+ }
+ };
+ }
+ match args[i].as_str() {
+ "-h" | "--help" => {
+ println!("{HUB_USAGE}");
+ return 0;
+ }
+ "--registry" => registry = Some(val!("--registry")),
+ "--out" => out = Some(val!("--out")),
+ "--url" => url = Some(val!("--url")),
+ "--sign-key" => sign_key = Some(val!("--sign-key")),
+ a if a.starts_with('-') => {
+ eprintln!("xerj hub build-pack: unknown flag '{a}'\n\n{HUB_USAGE}");
+ return 2;
+ }
+ a => {
+ if slug.is_none() {
+ slug = Some(a.to_string());
+ } else {
+ eprintln!("xerj hub build-pack: one <slug>, not two\n\n{HUB_USAGE}");
+ return 2;
+ }
+ }
+ }
+ i += 1;
+ }
+ let (Some(slug), Some(registry), Some(out), Some(sign_key)) = (slug, registry, out, sign_key)
+ else {
+ eprintln!(
+ "xerj hub build-pack: <slug>, --registry, --out and --sign-key are required\n\n{HUB_USAGE}"
+ );
+ return 2;
+ };
+ let url = resolve_url(url.as_deref());
+ match build_pack(&slug, &registry, &out, &url, &sign_key) {
+ Ok(summary) => {
+ println!("{summary}");
+ 0
+ }
+ Err(e) => {
+ eprintln!("xerj hub build-pack: {e:#}");
+ 1
+ }
+ }
+}
+
+/// Build the pack and return the one-line summary `pack <slug> <pin8> <bytes>
+/// <indices> <defs>` (plan §2 step 6).
+fn build_pack(
+ slug: &str,
+ registry: &str,
+ out: &str,
+ url: &str,
+ sign_key_file: &str,
+) -> Result<String> {
+ let seed = fs::read_to_string(sign_key_file)
+ .with_context(|| format!("read sign key {sign_key_file}"))?
+ .trim()
+ .to_string();
+ let manifest_path = Path::new(registry).join(format!("{slug}.json"));
+ if !manifest_path.is_file() {
+ bail!("no registry manifest at {}", manifest_path.display());
+ }
+
+ // 1. Licence, pin and sources — from the EXISTING parsers (no second parser
+ // for the registry manifest, plan §11): `read_hub_manifest` for the
+ // per-repo sources, and the catalogue builder for the restrictive-first
+ // licence class + pin date it already computes.
+ let meta = resolve_pack_metadata(&manifest_path, &seed)
+ .with_context(|| format!("read licence/pin from {}", manifest_path.display()))?;
+ let pin8 = pin8_of(&meta.pin_sha)?;
+
+ // 2. Clone + index into the builder node (the SAME lifecycle the CLI runs).
+ let rc = xerj_autoindex::xc::run_corpus_cli(&[
+ "add".into(),
+ slug.into(),
+ "--from".into(),
+ manifest_path.to_string_lossy().into_owned(),
+ ]);
+ if rc != 0 {
+ bail!("`corpus add` failed (exit {rc})");
+ }
+ let rc = xerj_autoindex::xc::run_corpus_cli(&[
+ "index".into(),
+ slug.into(),
+ "--url".into(),
+ url.into(),
+ ]);
+ if rc != 0 {
+ bail!("`corpus index` failed (exit {rc})");
+ }
+
+ let root = xerj_autoindex::xc::code_root();
+ let st = state::load_state(&root, slug).map_err(|e| anyhow!("{e}"))?;
+ let index_prefix = state::query_prefix(&st);
+
+ // 3. Defs + file inventory from the cloned tree (plan §3 extraction).
+ let corpus_root = root.join("corpora").join(slug);
+ let licence_map = xerj_common::xccode::manifest::licence_map(&root, slug);
+ let overall_licence = meta.licence_spdx.clone();
+ let licence_of = move |rel: &str| {
+ // The file's repo is its top-level directory under the corpus root.
+ rel.split('/')
+ .next()
+ .and_then(|top| licence_map.get(top))
+ .cloned()
+ .filter(|s| !s.is_empty())
+ .unwrap_or_else(|| overall_licence.clone())
+ };
+ let (defs, files) = pack::build_defs_and_files(&corpus_root, &licence_of)
+ .with_context(|| format!("extract defs from {}", corpus_root.display()))?;
+
+ // 4. Build + index the `-defs` index (plan §3 mapping) on the builder node.
+ let node = HubNode::connect_with_key(url, None)?;
+ node.wait_until_reachable(Duration::from_secs(30))
+ .context("builder node not reachable")?;
+ let defs_index = format!("{index_prefix}-defs");
+ create_defs_index(&node, &defs_index)?;
+ index_defs(&node, &defs_index, &defs)?;
+ node.request_ok("POST", &format!("/{defs_index}/_refresh"), None)
+ .ok();
+
+ // 5. Snapshot `<index_prefix>-*` (docs + defs) into <out>/<slug>/snapshot.
+ fs::create_dir_all(out).with_context(|| format!("create {out}"))?;
+ let out_canon = fs::canonicalize(out).with_context(|| format!("canonicalize {out}"))?;
+ let snapshot_location = out_canon.join(slug).join("snapshot");
+ let snapshot_name = format!("{slug}-{pin8}");
+ register_repo(&node, "hub-build", &snapshot_location)?;
+ node.request_ok(
+ "PUT",
+ &format!("/_snapshot/hub-build/{snapshot_name}?wait_for_completion=true"),
+ Some(&json!({ "indices": format!("{index_prefix}-*") })),
+ )
+ .context("create snapshot")?;
+
+ // 6. Assemble pack.json, write + sign the archive.
+ let indices = pack_indices(&node, &index_prefix)?;
+ let manifest = PackManifest {
+ format_version: PACK_FORMAT_VERSION,
+ slug: slug.to_string(),
+ pin_sha: meta.pin_sha.clone(),
+ pin_date: meta.pin_date.clone(),
+ built_at: now_rfc3339(),
+ builder_version: format!("xerj {}", env!("CARGO_PKG_VERSION")),
+ index_prefix: index_prefix.clone(),
+ indices,
+ snapshot_name: snapshot_name.clone(),
+ licence_spdx: meta.licence_spdx.clone(),
+ licence_class: meta.licence_class,
+ sources: meta.sources.clone(),
+ defs_count: defs.len() as u64,
+ files_count: files.len() as u64,
+ };
+ let n_indices = manifest.indices.len();
+ let out_archive = out_canon.join(format!("{slug}-{pin8}.hubpack.tar.zst"));
+ let (_sha, bytes) = pack::write_pack(
+ &out_archive,
+ &manifest,
+ &defs,
+ &files,
+ &snapshot_location,
+ &seed,
+ )
+ .context("write pack archive")?;
+
+ Ok(format!(
+ "pack {slug} {pin8} {bytes} {n_indices} {}",
+ defs.len()
+ ))
+}
+
+/// Pack licence/pin/sources, resolved from the registry manifest via existing
+/// parsers only.
+struct PackMetadata {
+ pin_sha: String,
+ pin_date: String,
+ licence_spdx: String,
+ licence_class: LicenceClass,
+ sources: Vec<PackSource>,
+}
+
+/// Read the pack's licence class + pin date through the catalogue builder (it
+/// already applies the restrictive-first rule over the manifest's review
+/// blocks) and the per-repo sources through `read_hub_manifest` — both existing
+/// parsers, so the registry manifest is never parsed by a second reader
+/// (plan §11). `seed` is only used because `build_catalogue` signs its output;
+/// the signature is discarded.
+fn resolve_pack_metadata(manifest_path: &Path, seed: &str) -> Result<PackMetadata> {
+ let input = CorpusBuildInput {
+ manifest_path: manifest_path.to_path_buf(),
+ domain: String::new(),
+ refresh_cadence_days: 0,
+ pack_bytes: 0,
+ pack_url: String::new(),
+ pack_sha256: String::new(),
+ sig_url: String::new(),
+ quality_grade: None,
+ terms: Vec::new(),
+ pin_sha: String::new(),
+ ask_for: String::new(),
+ };
+ let (cat, _sig) = build_catalogue(&[input], "", seed)?;
+ let entry = cat
+ .corpora
+ .first()
+ .ok_or_else(|| anyhow!("catalogue builder produced no entry"))?;
+
+ let hub = read_hub_manifest(manifest_path).map_err(|e| anyhow!("{e}"))?;
+ let sources = hub
+ .rows
+ .iter()
+ .map(|r| PackSource {
+ repo: r.repo.clone(),
+ url: r.url.clone(),
+ sha: r.sha.clone(),
+ licence: r.declared_licence.clone(),
+ })
+ .collect();
+
+ Ok(PackMetadata {
+ pin_sha: entry.pin_sha.clone(),
+ pin_date: entry.pin_date.clone(),
+ licence_spdx: entry.licence_spdx.clone(),
+ licence_class: entry.licence_class,
+ sources,
+ })
+}
+
+/// `PUT /<index>` with the plan's §3 defs mapping.
+fn create_defs_index(node: &HubNode, index: &str) -> Result<()> {
+ let body = 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" }
+ }}
+ });
+ node.request_ok("PUT", &format!("/{index}"), Some(&body))
+ .with_context(|| format!("create defs index {index}"))?;
+ Ok(())
+}
+
+/// Bulk-index every def document (`symbol_text` mirrors `symbol`, analysed).
+fn index_defs(node: &HubNode, index: &str, defs: &[xerj_common::hub::DefRecord]) -> Result<()> {
+ if defs.is_empty() {
+ return Ok(());
+ }
+ let mut ndjson = String::with_capacity(defs.len() * 160);
+ for d in defs {
+ ndjson.push_str("{\"index\":{}}\n");
+ let doc = json!({
+ "symbol": d.symbol,
+ "symbol_text": d.symbol,
+ "kind": d.kind,
+ "lang": d.lang,
+ "file": d.file,
+ "line": d.line,
+ "text": d.text,
+ "value": d.value,
+ });
+ ndjson.push_str(&doc.to_string());
+ ndjson.push('\n');
+ }
+ let resp = node.bulk_ndjson(&format!("/{index}/_bulk"), ndjson)?;
+ if resp.get("errors").and_then(Value::as_bool) == Some(true) {
+ bail!("defs bulk index reported errors: {resp}");
+ }
+ Ok(())
+}
+
+/// `PUT /_snapshot/<repo>` with the fs location.
+fn register_repo(node: &HubNode, repo: &str, location: &Path) -> Result<()> {
+ let body = json!({
+ "type": "fs",
+ "settings": { "location": location.to_string_lossy() }
+ });
+ node.request_ok("PUT", &format!("/_snapshot/{repo}"), Some(&body))
+ .with_context(|| format!("register snapshot repo {repo}"))?;
+ Ok(())
+}
+
+/// The `-*` indices as `PackIndex` rows (name/docs/bytes), from `_cat/indices`.
+fn pack_indices(node: &HubNode, prefix: &str) -> Result<Vec<PackIndex>> {
+ let path = format!("/_cat/indices/{prefix}-*?format=json&h=index,docs.count,store.size.bytes");
+ let v = node
+ .request_ok("GET", &path, None)
+ .with_context(|| format!("list indices {prefix}-*"))?;
+ let mut out = Vec::new();
+ for row in v.as_array().cloned().unwrap_or_default() {
+ let name = row
+ .get("index")
+ .and_then(Value::as_str)
+ .unwrap_or("")
+ .to_string();
+ if name.is_empty() {
+ continue;
+ }
+ out.push(PackIndex {
+ name,
+ docs: num_field(&row, "docs.count"),
+ bytes: num_field(&row, "store.size.bytes"),
+ });
+ }
+ out.sort_by(|a, b| a.name.cmp(&b.name));
+ Ok(out)
+}
+
+/// Read a `_cat` numeric column that may arrive as a number or a string.
+fn num_field(row: &Value, key: &str) -> u64 {
+ match row.get(key) {
+ Some(Value::Number(n)) => n.as_u64().unwrap_or(0),
+ Some(Value::String(s)) => s.parse().unwrap_or(0),
+ _ => 0,
+ }
+}
+
+// ── xerj hub pull ────────────────────────────────────────────────────────────
+
+fn run_pull(args: &[String]) -> i32 {
+ let mut slug: Option<String> = None;
+ let mut url: Option<String> = None;
+ let mut quiet = false;
+ let mut i = 0;
+ while i < args.len() {
+ match args[i].as_str() {
+ "-h" | "--help" => {
+ println!("{HUB_USAGE}");
+ return 0;
+ }
+ "--quiet" => quiet = true,
+ "--url" => match args.get(i + 1) {
+ Some(v) => {
+ url = Some(v.clone());
+ i += 1;
+ }
+ None => {
+ eprintln!("xerj hub pull: --url needs a value\n\n{HUB_USAGE}");
+ return 2;
+ }
+ },
+ a if a.starts_with('-') => {
+ eprintln!("xerj hub pull: unknown flag '{a}'\n\n{HUB_USAGE}");
+ return 2;
+ }
+ a => {
+ if slug.is_none() {
+ slug = Some(a.to_string());
+ } else {
+ eprintln!("xerj hub pull: one <slug>, not two\n\n{HUB_USAGE}");
+ return 2;
+ }
+ }
+ }
+ i += 1;
+ }
+ let Some(slug) = slug else {
+ eprintln!("xerj hub pull: <slug> is required\n\n{HUB_USAGE}");
+ return 2;
+ };
+ let url = resolve_url(url.as_deref());
+ match pull(&slug, &url, quiet) {
+ Ok(Pulled::Already) => {
+ if !quiet {
+ println!("{slug}: already present");
+ }
+ 0
+ }
+ Ok(Pulled::Done(line)) => {
+ if !quiet {
+ println!("{line}");
+ }
+ 0
+ }
+ Err(PullError { code, message }) => {
+ eprintln!("xerj hub pull: {message}");
+ code
+ }
+ }
+}
+
+enum Pulled {
+ Already,
+ Done(String),
+}
+
+/// A pull failure carrying the plan's exit code (2 unknown slug, 3 verify fail).
+struct PullError {
+ code: i32,
+ message: String,
+}
+impl PullError {
+ fn new(code: i32, message: impl Into<String>) -> Self {
+ PullError {
+ code,
+ message: message.into(),
+ }
+ }
+}
+
+fn pull(slug: &str, url: &str, _quiet: bool) -> Result<Pulled, PullError> {
+ let hub_home = hub_home();
+ let hub_url = std::env::var("XERJ_HUB_URL")
+ .ok()
+ .filter(|u| !u.is_empty())
+ .unwrap_or_else(|| DEFAULT_HUB_URL.to_string());
+
+ // 1. Catalogue → the entry for this slug. Unknown slug is exit 2.
+ let cat = load_catalogue(&hub_url, &hub_home, false)
+ .map_err(|e| PullError::new(2, format!("cannot load catalogue: {e:#}")))?;
+ let entry = cat.corpora.iter().find(|c| c.slug == slug).ok_or_else(|| {
+ PullError::new(
+ 2,
+ format!(
+ "unknown corpus '{slug}' (catalogue generated {}); `xerj hub status` lists what is \
+ available",
+ cat.generated_at
+ ),
+ )
+ })?;
+ let pin8 = pin8_of(&entry.pin_sha)
+ .map_err(|e| PullError::new(2, format!("catalogue entry for '{slug}': {e:#}")))?;
+
+ // 2. Already present? Same pin in the local ledger AND its indices live on
+ // this node → nothing to do (plan §2 step 4 "skip restore and say so").
+ let root = xerj_autoindex::xc::code_root();
+ let node = HubNode::connect_with_key(url, None)
+ .map_err(|e| PullError::new(2, format!("connect {url}: {e:#}")))?;
+ if let Ok(st) = state::load_state(&root, slug) {
+ if st.pin_sha.as_deref() == Some(entry.pin_sha.as_str()) {
+ let prefix = state::query_prefix(&st);
+ if node
+ .cat_indices_json(&format!("{prefix}*"))
+ .map(|v| !v.is_empty())
+ .unwrap_or(false)
+ {
+ return Ok(Pulled::Already);
+ }
+ }
+ }
+
+ // 3. Download pack + sig into a temp dir. NOTHING is extracted yet.
+ let pack_dir = hub_home.join("packs").join(slug);
+ let tmp = pack_dir.join(format!("{pin8}.tmp"));
+ let extract = pack_dir.join(pin8.clone());
+ // A stale temp from a crashed pull must not poison this one.
+ let _ = fs::remove_dir_all(&tmp);
+ fs::create_dir_all(&tmp)
+ .map_err(|e| PullError::new(3, format!("create {}: {e}", tmp.display())))?;
+ let archive = tmp.join(format!("{slug}-{pin8}.hubpack.tar.zst"));
+ let sig = tmp.join(format!("{slug}-{pin8}.hubpack.tar.zst.sig"));
+ let dl = (|| -> Result<u64> {
+ let n = fetch_to(&entry.pack_url, &archive)
+ .with_context(|| format!("download pack {}", entry.pack_url))?;
+ fetch_to(&entry.sig_url, &sig)
+ .with_context(|| format!("download sig {}", entry.sig_url))?;
+ Ok(n)
+ })();
+ let bytes = match dl {
+ Ok(n) => n,
+ Err(e) => {
+ let _ = fs::remove_dir_all(&tmp);
+ return Err(PullError::new(3, format!("{e:#}")));
+ }
+ };
+
+ // 4. Verify sha256 THEN signature THEN format_version, extracting nothing
+ // until all pass (plan §11). Any failure: delete the temp, exit 3.
+ let pubkey = hub_pubkey().map_err(|e| PullError::new(3, format!("{e:#}")))?;
+ let manifest =
+ match pack::read_and_verify_pack(&archive, &sig, &entry.pack_sha256, &pubkey, &extract) {
+ Ok(m) => m,
+ Err(e) => {
+ let _ = fs::remove_dir_all(&tmp);
+ // On failure read_and_verify_pack never populates `extract`; make
+ // sure a half-written dir from an interrupted prior run is gone too.
+ let _ = fs::remove_dir_all(&extract);
+ return Err(PullError::new(
+ 3,
+ format!("pack verification failed: {e:#}"),
+ ));
+ }
+ };
+ let _ = fs::remove_dir_all(&tmp);
+
+ // 5. Register + restore the snapshot (unless the same prefix is already
+ // restored on this node).
+ let prefix = manifest.index_prefix.clone();
+ let already_live = node
+ .cat_indices_json(&format!("{prefix}*"))
+ .map(|v| !v.is_empty())
+ .unwrap_or(false);
+ if !already_live {
+ let location = extract.join("snapshot");
+ register_repo(&node, &format!("hub-{slug}"), &location)
+ .map_err(|e| PullError::new(3, format!("register restore repo: {e:#}")))?;
+ node.request_ok(
+ "POST",
+ &format!(
+ "/_snapshot/hub-{slug}/{}/_restore?wait_for_completion=true",
+ manifest.snapshot_name
+ ),
+ Some(&json!({ "indices": format!("{prefix}-*") })),
+ )
+ .map_err(|e| PullError::new(3, format!("restore snapshot: {e:#}")))?;
+ }
+
+ // 6. Write the ledger with source: hubpack — `xerj code <slug>` now works.
+ state::write_hubpack_state(
+ &root,
+ slug,
+ url,
+ &manifest.index_prefix,
+ &manifest.pin_sha,
+ &manifest.pin_date,
+ &manifest.licence_spdx,
+ licence_class_str(manifest.licence_class),
+ )
+ .map_err(|e| PullError::new(3, format!("write state: {e}")))?;
+
+ let n_indices = manifest.indices.len();
+ Ok(Pulled::Done(format!(
+ "pulled {slug} {pin8} {bytes} → {n_indices} indices, {} definitions",
+ manifest.defs_count
+ )))
+}
+
+/// Download `url` to `dest`. Supports `file://` (the tests' local packs) and
+/// `http(s)://`. Returns the number of bytes written.
+fn fetch_to(url: &str, dest: &Path) -> Result<u64> {
+ if let Some(path) = url.strip_prefix("file://") {
+ let n = fs::copy(path, dest).with_context(|| format!("copy {path}"))?;
+ return Ok(n);
+ }
+ let resp = reqwest::blocking::get(url).with_context(|| format!("GET {url}"))?;
+ let status = resp.status();
+ if !status.is_success() {
+ bail!("GET {url} -> HTTP {status}");
+ }
+ let bytes = resp.bytes().with_context(|| format!("read body {url}"))?;
+ fs::write(dest, &bytes).with_context(|| format!("write {}", dest.display()))?;
+ Ok(bytes.len() as u64)
+}
+
+// ── xerj code (with --def) ───────────────────────────────────────────────────
+
+/// `xerj code …`: `--def <SYMBOL>` answers from the `-defs` index; everything
+/// else is the existing retrieval path, delegated unchanged.
+pub fn run_code(args: &[String]) -> i32 {
+ if !args.iter().any(|a| a == "--def") {
+ return xerj_autoindex::xc::run_code_cli(args);
+ }
+ run_code_def(args)
+}
+
+fn run_code_def(args: &[String]) -> i32 {
+ let mut slug: Option<String> = None;
+ let mut symbol: Option<String> = None;
+ let mut k: usize = crate::def::DEFAULT_K;
+ let mut url: Option<String> = None;
+ let mut api_key: Option<String> = None;
+ let mut as_json = false;
+ let mut i = 0;
+ let bad = |m: String| -> i32 {
+ eprintln!("xerj code: {m}");
+ 2
+ };
+ while i < args.len() {
+ macro_rules! val {
+ ($n:expr) => {
+ match args.get(i + 1) {
+ Some(v) => {
+ i += 1;
+ v.clone()
+ }
+ None => return bad(format!("{} needs a value", $n)),
+ }
+ };
+ }
+ match args[i].as_str() {
+ "--def" => symbol = Some(val!("--def")),
+ "-k" => {
+ let v = val!("-k");
+ match v.parse::<usize>() {
+ Ok(n) if (1..=50).contains(&n) => k = n,
+ _ => return bad(format!("-k must be 1..=50, got '{v}'")),
+ }
+ }
+ "--url" => url = Some(val!("--url")),
+ "--api-key" => api_key = Some(val!("--api-key")),
+ "--json" => as_json = true,
+ "-h" | "--help" => {
+ println!("usage: xerj code <corpus> --def <SYMBOL> [-k N] [--json] [--url URL]");
+ return 0;
+ }
+ a if a.starts_with('-') => return bad(format!("unknown flag '{a}' in --def mode")),
+ a => {
+ if slug.is_none() {
+ slug = Some(a.to_string());
+ } else {
+ return bad(format!("unexpected argument '{a}'"));
+ }
+ }
+ }
+ i += 1;
+ }
+ let (Some(slug), Some(symbol)) = (slug, symbol) else {
+ return bad("both <corpus> and --def <SYMBOL> are required".into());
+ };
+
+ let url = resolve_url(url.as_deref());
+ let node = match HubNode::connect_with_key(&url, api_key) {
+ Ok(n) => n,
+ Err(e) => return bad(format!("cannot reach {url}: {e:#}")),
+ };
+ let root = xerj_autoindex::xc::code_root();
+
+ // Mirror the retrieval path's refusals so a def miss is distinguishable
+ // from "not indexed" (exit 2) and "not loaded on this node" (exit 3).
+ let st = match state::load_state(&root, &slug) {
+ Ok(st) => st,
+ Err(msg) => {
+ eprintln!("{msg}");
+ return 2;
+ }
+ };
+ if let Err(refusal) = state::check_fresh(&st, false, "`--stale-ok`") {
+ eprintln!("{refusal}");
+ return 2;
+ }
+ let prefix = state::query_prefix(&st);
+ if let Ok(live) = node.cat_indices_json(&format!("{prefix}*")) {
+ if live.is_empty() {
+ eprintln!("{}", state::not_loaded_message(&st, &prefix, &url));
+ return 3;
+ }
+ }
+
+ let answer = crate::def::lookup(&node, &slug, &symbol, k);
+ emit_answer(&answer, as_json);
+ if answer.hits.is_empty() {
+ 1
+ } else {
+ 0
+ }
+}
+
+/// Print an [`Answer`]: warnings to stderr, the §1 rendering to stdout, and the
+/// JSON form to stdout when `--json`.
+fn emit_answer(answer: &Answer, as_json: bool) {
+ for w in &answer.warnings {
+ eprintln!("{w}");
+ }
+ if as_json {
+ match serde_json::to_string(answer) {
+ Ok(s) => println!("{s}"),
+ Err(e) => eprintln!("xerj code: cannot serialize answer: {e}"),
+ }
+ } else {
+ println!("{}", render(answer));
+ }
+}
+
+// ── small shared helpers ─────────────────────────────────────────────────────
+
+/// `~/.xerj/hub`, overridable by `XERJ_HUB_HOME` (tests). Never `/tmp`: the
+/// pack cache and catalogue must survive a reboot (same rule as `code_root`).
+fn hub_home() -> PathBuf {
+ if let Ok(h) = std::env::var("XERJ_HUB_HOME") {
+ if !h.is_empty() {
+ return PathBuf::from(h);
+ }
+ }
+ let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
+ Path::new(&home).join(".xerj").join("hub")
+}
+
+/// The hub's ed25519 public key: `XERJ_HUB_PUBKEY` (tests) else the compiled-in
+/// [`HUB_PUBKEY_HEX`]. An empty key is a hard error — an unverifiable pack is
+/// never extracted.
+fn hub_pubkey() -> Result<String> {
+ if let Ok(k) = std::env::var("XERJ_HUB_PUBKEY") {
+ if !k.is_empty() {
+ return Ok(k);
+ }
+ }
+ if !HUB_PUBKEY_HEX.is_empty() {
+ return Ok(HUB_PUBKEY_HEX.to_string());
+ }
+ bail!(
+ "no hub public key configured (HUB_PUBKEY_HEX is empty and XERJ_HUB_PUBKEY is unset); \
+ cannot verify a pack signature"
+ )
+}
+
+/// First 8 hex chars of a 40-hex commit — the `pin8` in pack names.
+fn pin8_of(pin_sha: &str) -> Result<String> {
+ let s = pin_sha.trim();
+ if s.len() < 8 || !s.chars().all(|c| c.is_ascii_hexdigit()) {
+ bail!("pin sha '{s}' is not a hex commit of at least 8 chars");
+ }
+ Ok(s[..8].to_ascii_lowercase())
+}
+
+/// The kebab-case string for a licence class — the state ledger's spelling.
+fn licence_class_str(c: LicenceClass) -> &'static str {
+ match c {
+ LicenceClass::AdaptWithAttribution => "adapt-with-attribution",
+ LicenceClass::ApproachOnly => "approach-only",
+ LicenceClass::Excluded => "excluded",
+ }
+}
+
+fn now_rfc3339() -> String {
+ chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn pin8_takes_eight_lowercase_hex() {
+ assert_eq!(
+ pin8_of("0774D05537f9762f838f7ab541b7765f1a729cb5").unwrap(),
+ "0774d055"
+ );
+ assert!(pin8_of("short").is_err());
+ assert!(pin8_of("nothexxx").is_err());
+ }
+
+ #[test]
+ fn licence_class_strings_round_trip_through_the_state_spelling() {
+ for (c, s) in [
+ (LicenceClass::AdaptWithAttribution, "adapt-with-attribution"),
+ (LicenceClass::ApproachOnly, "approach-only"),
+ (LicenceClass::Excluded, "excluded"),
+ ] {
+ assert_eq!(licence_class_str(c), s);
+ }
+ }
+
+ #[test]
+ fn run_code_without_def_does_not_enter_the_def_path() {
+ // No node is contacted and no panic: a bare `code` with a bad flag
+ // routes to the existing CLI, which returns its own usage exit code.
+ let rc = run_code(&["--definitely-not-a-flag".into()]);
+ assert_eq!(rc, 2, "delegates to run_code_cli, which rejects the flag");
+ }
+
+ #[test]
+ fn hub_usage_names_both_subcommands() {
+ assert!(HUB_USAGE.contains("build-pack"));
+ assert!(HUB_USAGE.contains("pull"));
+ assert_eq!(run_hub_cli(&["help".into()]), 0);
+ assert_eq!(run_hub_cli(&["bogus".into()]), 2);
+ }
+
+ #[test]
+ fn fetch_to_copies_a_file_url() {
+ let tmp = tempfile::tempdir().unwrap();
+ let src = tmp.path().join("src.bin");
+ fs::write(&src, b"hub pack bytes").unwrap();
+ let dst = tmp.path().join("dst.bin");
+ let url = format!("file://{}", src.display());
+ let n = fetch_to(&url, &dst).unwrap();
+ assert_eq!(n, 14);
+ assert_eq!(fs::read(&dst).unwrap(), b"hub pack bytes");
+ }
+
+ #[test]
+ fn hub_pubkey_prefers_env_and_errors_when_empty() {
+ // Serialise env mutation with other env-touching tests in this crate is
+ // unnecessary here: XERJ_HUB_PUBKEY is unique to this path.
+ std::env::set_var("XERJ_HUB_PUBKEY", "abcd");
+ assert_eq!(hub_pubkey().unwrap(), "abcd");
+ std::env::remove_var("XERJ_HUB_PUBKEY");
+ // HUB_PUBKEY_HEX is empty in this build, so no key is an error.
+ if HUB_PUBKEY_HEX.is_empty() {
+ assert!(hub_pubkey().is_err());
+ }
+ }
+}
diff --git a/engine/crates/xerj-hub/src/def.rs b/engine/crates/xerj-hub/src/def.rs
new file mode 100644
index 000000000..245f9bd5c
--- /dev/null
+++ b/engine/crates/xerj-hub/src/def.rs
@@ -0,0 +1,456 @@
+//! Corpus Hub v2 — `def` mode: one exact definition lookup (plan §3).
+//!
+//! `def` answers "what is X" from a corpus's `-defs` index: a term query on the
+//! `symbol` keyword (exact), with a `match` on the analysed `symbol_text` as a
+//! fallback for a near miss. Hits are exact-first, then by file path. Zero hits
+//! is a normal, empty [`Answer`] — a miss is an answer, not an error.
+//!
+//! [`lookup`] is the one function the CLI (`xerj code <slug> --def`), the MCP
+//! `xerj_hub_def` tool (plan §7) and the hosted `/_hub/v1/def` route (plan §6)
+//! all call, so every surface returns the same [`Answer`]. It reads the local
+//! state ledger for the corpus's pinned revision and licence (written by
+//! `xerj hub pull`, see `state::write_hubpack_state`) and queries the node for
+//! the hits; the query half ([`query_defs`]) is pure over [`XcHttp`] and unit
+//! tested with a fake node.
+
+use chrono::NaiveDate;
+use serde_json::{json, Value};
+use xerj_common::hub::{Answer, AnswerMode, AnsweredFrom, Hit, LicenceClass};
+use xerj_common::xccode::{state, XcHttp};
+
+/// `def`'s default result count (plan §3: "k default 5").
+pub const DEFAULT_K: usize = 5;
+/// Never return more than this, however large a `k` a caller passes.
+const MAX_K: usize = 50;
+
+/// Corpus facts the [`Answer`] carries, resolved from the local state ledger.
+struct DefMeta {
+ corpus: String,
+ index_prefix: String,
+ pin_sha: String,
+ pin_date: String,
+ age_days: u32,
+ licence_spdx: String,
+ licence_class: LicenceClass,
+ answered_from: AnsweredFrom,
+ /// A note to attach to the answer (e.g. the corpus is not indexed here).
+ warning: Option<String>,
+}
+
+impl DefMeta {
+ /// Resolve the corpus's pin, licence and the exact index prefix from
+ /// `{root}/state/{slug}.json`. A hub pack carries pin + licence directly; a
+ /// corpus that is not indexed here degrades to the `xc-<slug>` namespace
+ /// with a warning (the CLI refuses that case earlier with an exit code; the
+ /// hosted and MCP surfaces get an honest empty answer instead of a panic).
+ fn resolve(root: &std::path::Path, slug: &str) -> DefMeta {
+ match state::load_state(root, slug) {
+ Ok(st) => {
+ let licence_class = parse_licence_class(st.licence_class.as_deref());
+ let pin_date = st.pin_date.clone().unwrap_or_default();
+ let age_days = age_days_from(&pin_date, st.indexed_at.as_deref());
+ DefMeta {
+ corpus: st.name(slug),
+ index_prefix: state::query_prefix(&st),
+ pin_sha: st.pin_sha.clone().unwrap_or_default(),
+ pin_date,
+ age_days,
+ licence_spdx: st.licence_spdx.clone().unwrap_or_default(),
+ licence_class,
+ answered_from: if st.is_hubpack() {
+ AnsweredFrom::LocalPack
+ } else {
+ AnsweredFrom::LocalIndex
+ },
+ warning: None,
+ }
+ }
+ Err(_) => DefMeta {
+ corpus: slug.to_string(),
+ index_prefix: format!("xc-{slug}"),
+ pin_sha: String::new(),
+ pin_date: String::new(),
+ age_days: 0,
+ licence_spdx: String::new(),
+ licence_class: LicenceClass::AdaptWithAttribution,
+ answered_from: AnsweredFrom::LocalPack,
+ warning: Some(format!(
+ "corpus '{slug}' is not pulled; run `xerj hub pull {slug}`"
+ )),
+ },
+ }
+ }
+}
+
+/// Look up `symbol` in `slug`'s defs index and build the [`Answer`].
+///
+/// `k` is the max hits (0 means [`DEFAULT_K`]); it is clamped to [`MAX_K`].
+/// Reads the local state ledger for the corpus's pin and licence, then queries
+/// `<index_prefix>-defs`. A transport error becomes a warning on an otherwise
+/// empty answer (the CLI reports transport failures as an exit code before it
+/// gets here).
+pub fn lookup(http: &impl XcHttp, slug: &str, symbol: &str, k: usize) -> Answer {
+ let root = xerj_autoindex::xc::code_root();
+ lookup_in(http, &root, slug, symbol, k)
+}
+
+/// [`lookup`] with the state root injected — the seam the tests use so they do
+/// not depend on `$HOME`/`$XERJ_CODE_HOME`.
+pub fn lookup_in(
+ http: &impl XcHttp,
+ root: &std::path::Path,
+ slug: &str,
+ symbol: &str,
+ k: usize,
+) -> Answer {
+ let k = if k == 0 { DEFAULT_K } else { k.min(MAX_K) };
+ let meta = DefMeta::resolve(root, slug);
+ let defs_index = format!("{}-defs", meta.index_prefix);
+
+ let mut warnings = Vec::new();
+ if let Some(w) = &meta.warning {
+ warnings.push(w.clone());
+ }
+ let hits = match query_defs(http, &defs_index, symbol, k) {
+ Ok(hits) => hits,
+ Err(e) if e.contains("__404__") => {
+ // No defs index for this corpus — treated as "no definition here".
+ Vec::new()
+ }
+ Err(e) => {
+ warnings.push(format!("defs query failed: {e}"));
+ Vec::new()
+ }
+ };
+
+ build_answer(&meta, hits, warnings)
+}
+
+/// Build the [`Answer`] from resolved corpus facts and the retrieved hits. An
+/// approach-only corpus tags every hit with the read-don't-copy licence
+/// warning (plan §5), so the licence travels with the text wherever the answer
+/// is rendered.
+fn build_answer(meta: &DefMeta, mut hits: Vec<Hit>, warnings: Vec<String>) -> Answer {
+ if meta.licence_class == LicenceClass::ApproachOnly {
+ let note = format!(
+ "approach-only licence ({}): read, do not copy",
+ if meta.licence_spdx.is_empty() {
+ "unknown"
+ } else {
+ &meta.licence_spdx
+ }
+ );
+ for hit in &mut hits {
+ if hit.licence_warning.is_none() {
+ hit.licence_warning = Some(note.clone());
+ }
+ }
+ }
+ Answer {
+ corpus: meta.corpus.clone(),
+ pin_sha: meta.pin_sha.clone(),
+ pin_date: meta.pin_date.clone(),
+ age_days: meta.age_days,
+ licence_spdx: meta.licence_spdx.clone(),
+ licence_class: meta.licence_class,
+ answered_from: meta.answered_from,
+ mode: AnswerMode::Def,
+ hits,
+ truncated: false,
+ warnings,
+ }
+}
+
+/// The pure query half: a term query on `symbol` with a `match` on
+/// `symbol_text` as a fallback, against `defs_index`, returning up to `k` hits
+/// sorted exact-first then by file path. `Err` carries the transport/HTTP
+/// reason (incl. the `__404__` sentinel for a missing index).
+pub fn query_defs(
+ http: &impl XcHttp,
+ defs_index: &str,
+ symbol: &str,
+ k: usize,
+) -> Result<Vec<Hit>, String> {
+ // Fetch a window wider than `k` so the exact-first re-sort has the exact
+ // hit to promote even when fuzzy `symbol_text` matches are plentiful, then
+ // truncate to `k`.
+ let window = k.saturating_mul(4).clamp(10, MAX_K);
+ let body = json!({
+ "size": window,
+ "query": {
+ "bool": {
+ "should": [
+ { "term": { "symbol": symbol } },
+ { "match": { "symbol_text": symbol } }
+ ],
+ "minimum_should_match": 1
+ }
+ }
+ });
+
+ let resp = http.search(defs_index, &body)?;
+ let rows = resp
+ .pointer("/hits/hits")
+ .and_then(Value::as_array)
+ .cloned()
+ .unwrap_or_default();
+
+ // Parse each row, remembering whether its `symbol` is an EXACT match so the
+ // re-sort can put exact definitions first.
+ let mut parsed: Vec<(bool, String, u32, Hit)> = Vec::with_capacity(rows.len());
+ for row in &rows {
+ let src = match row.get("_source") {
+ Some(s) => s,
+ None => continue,
+ };
+ let sym = src.get("symbol").and_then(Value::as_str).unwrap_or("");
+ let file = src
+ .get("file")
+ .and_then(Value::as_str)
+ .unwrap_or("")
+ .to_string();
+ let line = src.get("line").and_then(Value::as_u64).unwrap_or(0) as u32;
+ let hit = Hit {
+ file: file.clone(),
+ line,
+ kind: src
+ .get("kind")
+ .and_then(Value::as_str)
+ .unwrap_or("")
+ .to_string(),
+ text: src
+ .get("text")
+ .and_then(Value::as_str)
+ .unwrap_or("")
+ .to_string(),
+ value: src.get("value").and_then(Value::as_str).map(str::to_string),
+ score: row.get("_score").and_then(Value::as_f64).unwrap_or(0.0) as f32,
+ licence_warning: None,
+ };
+ parsed.push((sym == symbol, file, line, hit));
+ }
+
+ // Exact matches first, then by file path, then by line — a total,
+ // deterministic order independent of the server's score.
+ parsed.sort_by(|a, b| {
+ b.0.cmp(&a.0) // exact (true) before fuzzy (false)
+ .then_with(|| a.1.cmp(&b.1)) // file path ascending
+ .then_with(|| a.2.cmp(&b.2)) // line ascending
+ });
+ parsed.truncate(k);
+ Ok(parsed.into_iter().map(|(_, _, _, h)| h).collect())
+}
+
+/// Map a kebab-case licence-class string to the enum, defaulting to the most
+/// permissive (`adapt-with-attribution`) when absent or unrecognised — the
+/// answer still carries the SPDX, and an unknown class never upgrades to a
+/// stricter one by surprise.
+fn parse_licence_class(s: Option<&str>) -> LicenceClass {
+ match s {
+ Some("approach-only") => LicenceClass::ApproachOnly,
+ Some("excluded") => LicenceClass::Excluded,
+ _ => LicenceClass::AdaptWithAttribution,
+ }
+}
+
+/// Days between the pin date (`YYYY-MM-DD`) and today, else between
+/// `indexed_at` and now, else 0. Never negative.
+fn age_days_from(pin_date: &str, indexed_at: Option<&str>) -> u32 {
+ if let Ok(d) = NaiveDate::parse_from_str(pin_date, "%Y-%m-%d") {
+ let today = chrono::Utc::now().date_naive();
+ return (today - d).num_days().max(0) as u32;
+ }
+ if let Some(stamp) = indexed_at {
+ if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(stamp, "%Y-%m-%dT%H:%M:%SZ") {
+ let age = chrono::Utc::now()
+ .naive_utc()
+ .signed_duration_since(dt)
+ .num_days();
+ return age.max(0) as u32;
+ }
+ }
+ 0
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::cell::RefCell;
+
+ /// A fake [`XcHttp`] that returns a canned search response and records the
+ /// query body it was handed, so a test can assert the def query shape.
+ struct FakeNode {
+ response: Value,
+ last_body: RefCell<Option<Value>>,
+ }
+ impl FakeNode {
+ fn new(response: Value) -> Self {
+ FakeNode {
+ response,
+ last_body: RefCell::new(None),
+ }
+ }
+ }
+ impl XcHttp for FakeNode {
+ fn get_mapping(&self, _: &str) -> Result<Value, String> {
+ Ok(json!({}))
+ }
+ fn cat_indices_json(&self, _: &str) -> Result<Vec<String>, String> {
+ Ok(vec![])
+ }
+ fn search(&self, _index: &str, body: &Value) -> Result<Value, String> {
+ *self.last_body.borrow_mut() = Some(body.clone());
+ Ok(self.response.clone())
+ }
+ }
+
+ fn hit_row(symbol: &str, file: &str, line: u32, value: Option<&str>, score: f64) -> Value {
+ json!({
+ "_score": score,
+ "_source": {
+ "symbol": symbol,
+ "symbol_text": symbol,
+ "kind": "define",
+ "lang": "c",
+ "file": file,
+ "line": line,
+ "text": format!("#define {symbol} {}", value.unwrap_or("")),
+ "value": value,
+ }
+ })
+ }
+
+ #[test]
+ fn query_builds_a_term_plus_match_should() {
+ let node = FakeNode::new(json!({"hits": {"hits": []}}));
+ let _ = query_defs(&node, "xc-x-b1-defs", "FOO", 5).unwrap();
+ let body = node.last_body.borrow().clone().unwrap();
+ let should = body
+ .pointer("/query/bool/should")
+ .unwrap()
+ .as_array()
+ .unwrap();
+ assert_eq!(should.len(), 2);
+ assert_eq!(should[0].pointer("/term/symbol").unwrap(), &json!("FOO"));
+ assert_eq!(
+ should[1].pointer("/match/symbol_text").unwrap(),
+ &json!("FOO")
+ );
+ assert_eq!(
+ body.pointer("/query/bool/minimum_should_match").unwrap(),
+ &json!(1)
+ );
+ }
+
+ #[test]
+ fn exact_symbol_sorts_before_fuzzy_then_by_file() {
+ // A fuzzy match scores HIGHER than the exact one; exact must still win,
+ // and ties break on file path.
+ let resp = json!({"hits": {"hits": [
+ hit_row("MINI_LIMIT_MAX", "z.c", 9, Some("1"), 99.0), // fuzzy, high score
+ hit_row("MINI_LIMIT", "b.c", 7, Some("128"), 2.0), // exact
+ hit_row("MINI_LIMIT", "a.c", 3, Some("64"), 1.0), // exact, earlier file
+ ]}});
+ let node = FakeNode::new(resp);
+ let hits = query_defs(&node, "xc-mini-c-b1-defs", "MINI_LIMIT", 5).unwrap();
+ assert_eq!(hits.len(), 3);
+ // exact first, by file path
+ assert_eq!((hits[0].file.as_str(), hits[0].line), ("a.c", 3));
+ assert_eq!(hits[0].value.as_deref(), Some("64"));
+ assert_eq!((hits[1].file.as_str(), hits[1].line), ("b.c", 7));
+ assert_eq!(hits[1].value.as_deref(), Some("128"));
+ // fuzzy last
+ assert_eq!(hits[2].file.as_str(), "z.c");
+ }
+
+ #[test]
+ fn k_truncates_after_the_exact_first_sort() {
+ let resp = json!({"hits": {"hits": [
+ hit_row("A", "a.c", 1, None, 1.0),
+ hit_row("A", "b.c", 2, None, 1.0),
+ hit_row("A", "c.c", 3, None, 1.0),
+ ]}});
+ let node = FakeNode::new(resp);
+ let hits = query_defs(&node, "idx", "A", 2).unwrap();
+ assert_eq!(hits.len(), 2);
+ assert_eq!(hits[0].file, "a.c");
+ assert_eq!(hits[1].file, "b.c");
+ }
+
+ #[test]
+ fn missing_index_404_is_a_normal_empty_answer() {
+ struct NotFound;
+ impl XcHttp for NotFound {
+ fn get_mapping(&self, _: &str) -> Result<Value, String> {
+ Ok(json!({}))
+ }
+ fn cat_indices_json(&self, _: &str) -> Result<Vec<String>, String> {
+ Ok(vec![])
+ }
+ fn search(&self, _: &str, _: &Value) -> Result<Value, String> {
+ Err("__404__".to_string())
+ }
+ }
+ let root = tempfile::tempdir().unwrap();
+ // write a hubpack state so meta resolves
+ state::write_hubpack_state(
+ root.path(),
+ "lz4",
+ "http://x",
+ "xc-lz4-b1",
+ "abc",
+ "2026-10-02",
+ "BSD-2-Clause",
+ "adapt-with-attribution",
+ )
+ .unwrap();
+ let ans = lookup_in(&NotFound, root.path(), "lz4", "NOPE", 5);
+ assert!(ans.hits.is_empty());
+ assert_eq!(ans.mode, AnswerMode::Def);
+ assert_eq!(ans.corpus, "lz4");
+ assert_eq!(ans.answered_from, AnsweredFrom::LocalPack);
+ // The shipped renderer prints the corpus + pin on the empty answer.
+ let text = xerj_common::hub::render(&ans);
+ assert!(text.contains("no match in lz4"), "{text}");
+ }
+
+ #[test]
+ fn approach_only_corpus_tags_each_hit_and_answer_carries_pin() {
+ let root = tempfile::tempdir().unwrap();
+ state::write_hubpack_state(
+ root.path(),
+ "sonic",
+ "http://x",
+ "xc-sonic-b1",
+ "deadbeef",
+ "2026-10-01",
+ "GPL-3.0-only",
+ "approach-only",
+ )
+ .unwrap();
+ let node = FakeNode::new(json!({"hits": {"hits": [
+ hit_row("SEARCH_LIMIT", "store.c", 5, Some("1000"), 3.0),
+ ]}}));
+ let ans = lookup_in(&node, root.path(), "sonic", "SEARCH_LIMIT", 5);
+ assert_eq!(ans.hits.len(), 1);
+ assert_eq!(ans.licence_class, LicenceClass::ApproachOnly);
+ assert_eq!(ans.pin_sha, "deadbeef");
+ assert_eq!(ans.pin_date, "2026-10-01");
+ assert_eq!(
+ ans.hits[0].licence_warning.as_deref(),
+ Some("approach-only licence (GPL-3.0-only): read, do not copy")
+ );
+ }
+
+ #[test]
+ fn not_pulled_corpus_warns_but_does_not_panic() {
+ let node = FakeNode::new(json!({"hits": {"hits": []}}));
+ let root = tempfile::tempdir().unwrap();
+ let ans = lookup_in(&node, root.path(), "ghost", "X", 5);
+ assert!(ans.hits.is_empty());
+ assert!(ans
+ .warnings
+ .iter()
+ .any(|w| w.contains("not pulled") && w.contains("xerj hub pull ghost")));
+ }
+}
diff --git a/engine/crates/xerj-hub/src/lib.rs b/engine/crates/xerj-hub/src/lib.rs
index 9a1a05261..e46f16250 100644
--- a/engine/crates/xerj-hub/src/lib.rs
+++ b/engine/crates/xerj-hub/src/lib.rs
@@ -14,6 +14,8 @@
//! router + ask (Step 5). Alongside them this file re-exports the shared types.
pub mod catalogue;
+pub mod cli;
+pub mod def;
pub mod lockfile;
pub mod node;
pub mod pack;
diff --git a/engine/crates/xerj-hub/src/node.rs b/engine/crates/xerj-hub/src/node.rs
index 7d45ee1c7..4a01d6d09 100644
--- a/engine/crates/xerj-hub/src/node.rs
+++ b/engine/crates/xerj-hub/src/node.rs
@@ -1,3 +1,248 @@
-//! Corpus Hub v2 — the node module. Filled by the implementing agent per
-//! docs/CORPUS_HUB_V2_IMPLEMENTATION.md. This stub reserves the module so the
-//! crate wires up before the behaviour lands.
+//! Corpus Hub v2 — node resolution and a blocking HTTP client to a xerj node
+//! (plan §2 "Node for the client", §4 node resolution).
+//!
+//! `build-pack`, `pull` and `def` all talk to a running node: the builder
+//! snapshots into one, `pull` restores into one, and `def` queries one. This
+//! module resolves WHICH node ([`resolve_url`], the same `--url` / `XERJ_URL` /
+//! `localhost:9200` order `xc.rs` uses) and gives a small blocking client
+//! ([`HubNode`]) over it.
+//!
+//! The AUTOMATIC node spawn (start a node when none answers) is plan §5 and is
+//! NOT done here — this module only resolves an explicit or defaulted URL and
+//! connects to it. [`HubNode`] implements [`XcHttp`] so `def::lookup` runs over
+//! it unchanged, and it adds the extra verbs (`PUT`/`POST` with an arbitrary
+//! path, a readiness poll) the builder and the pull path need.
+
+use std::time::{Duration, Instant};
+
+use anyhow::{anyhow, bail, Context, Result};
+use serde_json::Value;
+use xerj_common::localauth::{discover_local_admin_key, url_is_loopback};
+use xerj_common::xccode::XcHttp;
+
+/// `--url` flag > `XERJ_URL` > `http://localhost:9200`, exactly as `xc.rs`
+/// resolves it for the reference-coding read commands (a hub `pull`/`def`
+/// honours `XERJ_URL` the same way `corpus index` does).
+pub fn resolve_url(explicit: Option<&str>) -> String {
+ explicit
+ .map(str::to_string)
+ .or_else(|| std::env::var("XERJ_URL").ok().filter(|u| !u.is_empty()))
+ .unwrap_or_else(|| "http://localhost:9200".to_string())
+}
+
+/// A blocking HTTP client to one xerj node. Holds the resolved base URL and the
+/// `Authorization: ApiKey …` value (if any), reusing one `reqwest` client.
+pub struct HubNode {
+ base: String,
+ auth: Option<String>,
+ client: reqwest::blocking::Client,
+}
+
+impl HubNode {
+ /// Connect to `url`, resolving the API key the way `xc.rs` does:
+ /// `XERJ_API_KEY` wins; otherwise, for a loopback URL, fall back to the
+ /// node's on-disk admin key (announced, loopback-only). An `--insecure`
+ /// node needs no key and none is sent.
+ pub fn connect(url: &str) -> Result<Self> {
+ Self::connect_with_key(url, None)
+ }
+
+ /// Connect with an explicit API key (overrides discovery). `api_key: None`
+ /// uses the same `XERJ_API_KEY` / loopback-admin-key fallback as
+ /// [`HubNode::connect`].
+ pub fn connect_with_key(url: &str, api_key: Option<String>) -> Result<Self> {
+ let base = url.trim_end_matches('/').to_string();
+ let key = match api_key {
+ Some(k) => Some(k),
+ None => match std::env::var("XERJ_API_KEY").ok().filter(|k| !k.is_empty()) {
+ Some(k) => Some(k),
+ None if url_is_loopback(&base) => discover_local_admin_key().map(|(k, path)| {
+ eprintln!(
+ "xerj hub: no --api-key/XERJ_API_KEY given; using the admin key at {}",
+ path.display()
+ );
+ k
+ }),
+ None => None,
+ },
+ };
+ let client = reqwest::blocking::Client::builder()
+ .timeout(Duration::from_secs(300))
+ .build()
+ .context("build HTTP client")?;
+ Ok(HubNode {
+ base,
+ auth: key.map(|k| format!("ApiKey {k}")),
+ client,
+ })
+ }
+
+ /// The resolved base URL (no trailing slash) — for diagnostics and the
+ /// state ledger's `url` field.
+ pub fn url(&self) -> &str {
+ &self.base
+ }
+
+ /// One request returning `(status, parsed-body)`. A non-JSON body comes
+ /// back as `Value::String`. Transport failure (not an HTTP status) is an
+ /// `Err`; the caller classifies HTTP statuses itself.
+ fn send(&self, method: &str, path: &str, body: Option<&Value>) -> Result<(u16, Value), String> {
+ let url = format!("{}{}", self.base, path);
+ let m = reqwest::Method::from_bytes(method.as_bytes())
+ .map_err(|_| format!("not an HTTP method: {method}"))?;
+ let mut req = self.client.request(m, &url);
+ if let Some(h) = &self.auth {
+ req = req.header("Authorization", h);
+ }
+ if let Some(b) = body {
+ req = req.json(b);
+ }
+ let resp = req
+ .send()
+ .map_err(|e| format!("no response from {url}: {e}"))?;
+ let status = resp.status().as_u16();
+ let text = resp.text().map_err(|e| format!("read {url}: {e}"))?;
+ let v: Value = serde_json::from_str(&text).unwrap_or(Value::String(text));
+ Ok((status, v))
+ }
+
+ /// A request that must return 2xx, else an `anyhow` error carrying the
+ /// status and body. Used by the builder/pull control-plane calls (create
+ /// index, bulk, snapshot, restore).
+ pub fn request_ok(&self, method: &str, path: &str, body: Option<&Value>) -> Result<Value> {
+ let (status, v) = self
+ .send(method, path, body)
+ .map_err(|e| anyhow!("{method} {path}: {e}"))?;
+ if (200..300).contains(&status) {
+ Ok(v)
+ } else {
+ bail!("{method} {path} -> HTTP {status}: {v}")
+ }
+ }
+
+ /// `POST` a raw NDJSON `_bulk` body (content-type `application/x-ndjson`)
+ /// and require 2xx. The builder uses this to index the defs documents;
+ /// `request_ok`'s `.json()` cannot send the newline-delimited bulk format.
+ pub fn bulk_ndjson(&self, path: &str, ndjson: String) -> Result<Value> {
+ let url = format!("{}{}", self.base, path);
+ let mut req = self
+ .client
+ .post(&url)
+ .header("Content-Type", "application/x-ndjson")
+ .body(ndjson);
+ if let Some(h) = &self.auth {
+ req = req.header("Authorization", h);
+ }
+ let resp = req.send().with_context(|| format!("bulk {url}"))?;
+ let status = resp.status().as_u16();
+ let text = resp.text().unwrap_or_default();
+ let v: Value = serde_json::from_str(&text).unwrap_or(Value::String(text));
+ if (200..300).contains(&status) {
+ Ok(v)
+ } else {
+ bail!("bulk {path} -> HTTP {status}: {v}")
+ }
+ }
+
+ /// Poll `GET /_cluster/health` until the node answers (any HTTP status that
+ /// is not a transport error means it is up), up to `timeout`. Returns the
+ /// last health body. The automatic node spawn (plan §5) will reuse this to
+ /// wait for a node it started; here it lets `pull`/`build-pack` fail fast
+ /// with a clear message when the node is not reachable.
+ pub fn wait_until_reachable(&self, timeout: Duration) -> Result<Value> {
+ let deadline = Instant::now() + timeout;
+ loop {
+ let last_err = match self.send("GET", "/_cluster/health", None) {
+ Ok((status, v)) if (200..500).contains(&status) => return Ok(v),
+ Ok((status, v)) => format!("HTTP {status}: {v}"),
+ Err(e) => e,
+ };
+ if Instant::now() >= deadline {
+ bail!("node at {} not reachable: {last_err}", self.base);
+ }
+ std::thread::sleep(Duration::from_millis(200));
+ }
+ }
+}
+
+impl XcHttp for HubNode {
+ fn get_mapping(&self, path: &str) -> Result<Value, String> {
+ match self.send("GET", path, None) {
+ Ok((status, v)) if (200..300).contains(&status) => Ok(v),
+ Ok((404, _)) => Err("__404__".to_string()),
+ Ok((status, v)) => Err(format!("HTTP {status}: {v}")),
+ Err(e) => Err(e),
+ }
+ }
+ fn cat_indices_json(&self, pattern: &str) -> Result<Vec<String>, String> {
+ let path = format!("/_cat/indices/{pattern}?format=json&h=index");
+ match self.send("GET", &path, None) {
+ // A wildcard matching no index is "none", not an error.
+ Ok((404, _)) => Ok(Vec::new()),
+ Ok((status, v)) if (200..300).contains(&status) => v
+ .as_array()
+ .map(|rows| {
+ rows.iter()
+ .filter_map(|r| r.get("index").and_then(Value::as_str))
+ .map(str::to_string)
+ .collect()
+ })
+ .ok_or_else(|| "non-array _cat reply".to_string()),
+ Ok((status, v)) => Err(format!("HTTP {status}: {v}")),
+ Err(e) => Err(e),
+ }
+ }
+ fn search(&self, index: &str, body: &Value) -> Result<Value, String> {
+ match self.send("POST", &format!("/{index}/_search"), Some(body)) {
+ Ok((status, v)) if (200..300).contains(&status) => Ok(v),
+ Ok((404, _)) => Err("__404__".to_string()),
+ Ok((status, v)) => Err(format!("HTTP {status}: {v}")),
+ Err(e) => Err(e),
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ // `resolve_url` mutates process env, which is global; serialise the env
+ // cases so they do not race other tests in the crate.
+ use std::sync::Mutex;
+ static ENV_LOCK: Mutex<()> = Mutex::new(());
+
+ #[test]
+ fn url_resolution_prefers_flag_then_env_then_default() {
+ let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
+ // Flag wins over everything.
+ std::env::set_var("XERJ_URL", "http://env:1");
+ assert_eq!(resolve_url(Some("http://flag:1")), "http://flag:1");
+ // Env is used when no flag.
+ assert_eq!(resolve_url(None), "http://env:1");
+ // Default when neither.
+ std::env::remove_var("XERJ_URL");
+ assert_eq!(resolve_url(None), "http://localhost:9200");
+ // An empty XERJ_URL is ignored (falls through to the default).
+ std::env::set_var("XERJ_URL", "");
+ assert_eq!(resolve_url(None), "http://localhost:9200");
+ std::env::remove_var("XERJ_URL");
+ }
+
+ #[test]
+ fn connect_trims_trailing_slash_and_sets_no_auth_without_a_key() {
+ let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
+ std::env::remove_var("XERJ_API_KEY");
+ // A non-loopback URL never reaches for a local admin key, so no auth
+ // header is set when none was given.
+ let n = HubNode::connect("http://example.invalid:9200/").unwrap();
+ assert_eq!(n.url(), "http://example.invalid:9200");
+ assert!(n.auth.is_none());
+ }
+
+ #[test]
+ fn explicit_key_becomes_an_apikey_header() {
+ let n = HubNode::connect_with_key("http://example.invalid:9200", Some("sekret".into()))
+ .unwrap();
+ assert_eq!(n.auth.as_deref(), Some("ApiKey sekret"));
+ }
+}
diff --git a/engine/crates/xerj-hub/src/pack.rs b/engine/crates/xerj-hub/src/pack.rs
index e4ecdbb05..f08516d04 100644
--- a/engine/crates/xerj-hub/src/pack.rs
+++ b/engine/crates/xerj-hub/src/pack.rs
@@ -32,6 +32,7 @@ use std::path::{Component, Path, PathBuf};
use anyhow::{bail, Context, Result};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
+use xerj_autoindex::extract::code::{definitions, is_code_ext};
use xerj_autoindex::harvest::sign::{sign_bytes, verify_bytes};
use xerj_common::hub::{DefRecord, PackManifest, PACK_FORMAT_VERSION};
@@ -374,6 +375,170 @@ fn extract_into(members: &BTreeMap<String, Vec<u8>>, dest: &Path) -> Result<()>
Ok(())
}
+// ── builder: defs + file inventory from a cloned corpus tree (plan §2/§3) ────
+
+/// Largest file read for AST extraction — past a couple MB a "file" is a
+/// generated bundle, not human code (mirrors the ingest extractor's `CODE_CAP`).
+const DEFS_READ_CAP: u64 = 2 << 20;
+
+/// Walk a cloned corpus tree and return (a) every definition
+/// ([`xerj_autoindex::extract::code::definitions`]) as [`DefRecord`]s, sorted by
+/// `(file, line)`, and (b) a file inventory as [`PackFileEntry`]s, sorted by
+/// path — the `defs.jsonl` and `files.jsonl` members of the pack (plan §2).
+///
+/// `corpus_root` is `<code_root>/corpora/<slug>`; paths are recorded relative to
+/// it with forward slashes (so they read the same on every OS and line up with
+/// the docs index's `ax_path`). `licence_of(rel)` supplies the per-file licence
+/// (the licence of the repo sub-tree the file sits in). `.git` and the corpus's
+/// own `corpus.json` are skipped. This is NODE-FREE: it only reads files.
+pub fn build_defs_and_files(
+ corpus_root: &Path,
+ licence_of: &dyn Fn(&str) -> String,
+) -> Result<(Vec<DefRecord>, Vec<PackFileEntry>)> {
+ let mut defs: Vec<DefRecord> = Vec::new();
+ let mut files: Vec<PackFileEntry> = Vec::new();
+ let mut found: Vec<(String, PathBuf)> = Vec::new();
+ walk_corpus(corpus_root, corpus_root, &mut found)?;
+
+ for (rel, abs) in &found {
+ // The corpus's own metadata file is not a source file.
+ if rel == "corpus.json" {
+ continue;
+ }
+ let bytes = fs::metadata(abs).map(|m| m.len()).unwrap_or(0);
+ let ext = ext_of(rel);
+ let licence = licence_of(rel);
+
+ let lang = if is_code_ext(&ext) && bytes <= DEFS_READ_CAP {
+ // Read once; the decoded text is used for both language resolution
+ // (the `.m` objc/matlab probe needs content) and extraction.
+ let raw = fs::read(abs).unwrap_or_default();
+ let text = String::from_utf8_lossy(&raw);
+ if let Some(lang) = lang_for_ext(&ext, &text) {
+ defs.extend(definitions(rel, lang, &text));
+ Some(lang)
+ } else {
+ None
+ }
+ } else {
+ None
+ };
+
+ files.push(PackFileEntry {
+ path: rel.clone(),
+ lang: lang.unwrap_or("").to_string(),
+ bytes,
+ licence,
+ });
+ }
+
+ defs.sort_by(|a, b| a.file.cmp(&b.file).then(a.line.cmp(&b.line)));
+ files.sort_by(|a, b| a.path.cmp(&b.path));
+ Ok((defs, files))
+}
+
+/// Recursively collect regular files as `(relative-forward-slash path, abs)`,
+/// skipping `.git`. Mirrors the snapshot walker but keyed on a corpus root.
+fn walk_corpus(base: &Path, dir: &Path, out: &mut Vec<(String, PathBuf)>) -> Result<()> {
+ for entry in fs::read_dir(dir).with_context(|| format!("read dir {}", dir.display()))? {
+ let entry = entry?;
+ let path = entry.path();
+ let ft = entry.file_type()?;
+ if ft.is_dir() {
+ if entry.file_name() == ".git" {
+ continue;
+ }
+ walk_corpus(base, &path, out)?;
+ } else if ft.is_file() {
+ if let Ok(rel) = path.strip_prefix(base) {
+ if let Ok(s) = rel_to_forward_slash(rel) {
+ out.push((s, path));
+ }
+ }
+ }
+ }
+ Ok(())
+}
+
+/// Lower-case extension of a `/`-joined relative path (empty when none).
+fn ext_of(rel: &str) -> String {
+ rel.rsplit('/')
+ .next()
+ .and_then(|name| name.rsplit_once('.').map(|(_, e)| e))
+ .unwrap_or("")
+ .to_ascii_lowercase()
+}
+
+/// Map a lower-case extension to the registry language name
+/// `extract/code.rs`'s `definitions` expects. Kept in lock-step with that
+/// registry (there is no public enumerator to borrow it from); the
+/// `lang_table_matches_is_code_ext` test fails if the two drift on any
+/// extension this table knows. The `.m`/`.mm` collision is resolved the way the
+/// extractor does — Objective-C markers win, MATLAB is the fallback for `.m`.
+fn lang_for_ext(ext: &str, text: &str) -> Option<&'static str> {
+ let name = match ext {
+ "py" | "pyi" => "python",
+ "js" | "jsx" | "mjs" | "cjs" => "javascript",
+ "ts" | "mts" | "cts" => "typescript",
+ "tsx" => "tsx",
+ "rs" => "rust",
+ "go" => "go",
+ "java" => "java",
+ "c" | "h" => "c",
+ "cpp" | "cc" | "cxx" | "hpp" | "hh" | "hxx" => "cpp",
+ "rb" => "ruby",
+ "php" => "php",
+ "cs" => "csharp",
+ "sh" | "bash" => "bash",
+ "kt" | "kts" => "kotlin",
+ "swift" => "swift",
+ "scala" | "sc" => "scala",
+ "dart" => "dart",
+ "lua" => "lua",
+ "pl" | "pm" => "perl",
+ "r" => "r",
+ "jl" => "julia",
+ "hs" => "haskell",
+ "ex" | "exs" => "elixir",
+ "erl" | "hrl" => "erlang",
+ "ml" => "ocaml",
+ "mli" => "ocaml_interface",
+ "zig" => "zig",
+ "mm" => "objc",
+ "m" => {
+ if looks_like_objc(text) {
+ "objc"
+ } else {
+ "matlab"
+ }
+ }
+ "groovy" | "gradle" => "groovy",
+ "ps1" | "psm1" | "psd1" => "powershell",
+ "fs" | "fsx" => "fsharp",
+ "nix" => "nix",
+ "f90" | "f95" | "f03" => "fortran",
+ "sol" => "solidity",
+ "clj" | "cljs" | "cljc" => "clojure",
+ "scm" | "ss" | "sld" | "sps" => "scheme",
+ _ => return None,
+ };
+ Some(name)
+}
+
+/// `.m` disambiguator — Objective-C near-universally carries one of these
+/// markers; a `.m` with none is MATLAB (the extractor's `looks_like_objc`).
+fn looks_like_objc(text: &str) -> bool {
+ [
+ "#import",
+ "@interface",
+ "@implementation",
+ "@protocol",
+ "@end",
+ ]
+ .iter()
+ .any(|m| text.contains(m))
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -678,4 +843,94 @@ mod tests {
"SHA256SUMS must not list itself"
);
}
+
+ #[test]
+ fn build_defs_and_files_extracts_c_defines_and_inventories_files() {
+ let tmp = tempfile::tempdir().unwrap();
+ let root = tmp.path().join("corpora").join("mini-c");
+ fs::create_dir_all(root.join("lz4")).unwrap();
+ fs::write(
+ root.join("lz4/limits.h"),
+ "#define MINI_LIMIT 128\nint helper(int x);\n",
+ )
+ .unwrap();
+ fs::write(root.join("LICENSE"), "MIT License\n").unwrap();
+ // corpus.json is metadata, never a source file.
+ fs::write(root.join("corpus.json"), "{}").unwrap();
+ // .git content is skipped.
+ fs::create_dir_all(root.join(".git")).unwrap();
+ fs::write(root.join(".git/HEAD"), "ref: refs/heads/main\n").unwrap();
+
+ let licence_of = |_rel: &str| "MIT".to_string();
+ let (defs, files) = build_defs_and_files(&root, &licence_of).unwrap();
+
+ // The #define carries its value; the prototype has none.
+ let limit = defs
+ .iter()
+ .find(|d| d.symbol == "MINI_LIMIT")
+ .expect("MINI_LIMIT extracted");
+ assert_eq!(limit.value.as_deref(), Some("128"));
+ assert_eq!(limit.file, "lz4/limits.h");
+ assert_eq!(limit.lang, "c");
+ assert_eq!(limit.line, 1);
+
+ // Inventory: the .h and the LICENSE, never corpus.json or .git/*.
+ let paths: Vec<&str> = files.iter().map(|f| f.path.as_str()).collect();
+ assert_eq!(paths, vec!["LICENSE", "lz4/limits.h"]);
+ assert!(!paths
+ .iter()
+ .any(|p| p.contains(".git") || *p == "corpus.json"));
+ let h = files.iter().find(|f| f.path == "lz4/limits.h").unwrap();
+ assert_eq!(h.lang, "c");
+ assert_eq!(h.licence, "MIT");
+ // A non-code file is inventoried with an empty lang.
+ assert_eq!(files.iter().find(|f| f.path == "LICENSE").unwrap().lang, "");
+ }
+
+ #[test]
+ fn defs_are_sorted_by_file_then_line() {
+ let tmp = tempfile::tempdir().unwrap();
+ let root = tmp.path().join("c");
+ fs::create_dir_all(&root).unwrap();
+ fs::write(root.join("b.c"), "#define B1 1\n#define B2 2\n").unwrap();
+ fs::write(root.join("a.c"), "#define A1 9\n").unwrap();
+ let (defs, _) = build_defs_and_files(&root, &|_| "MIT".into()).unwrap();
+ let order: Vec<(&str, u32)> = defs.iter().map(|d| (d.file.as_str(), d.line)).collect();
+ assert_eq!(order, vec![("a.c", 1), ("b.c", 1), ("b.c", 2)]);
+ }
+
+ /// The hub's extension→language table must agree with the extractor's own
+ /// `is_code_ext` for every extension it claims — the guard against the two
+ /// drifting apart (there is no public registry enumerator to share).
+ #[test]
+ fn lang_table_matches_is_code_ext() {
+ let claimed = [
+ "py", "pyi", "js", "jsx", "mjs", "cjs", "ts", "mts", "cts", "tsx", "rs", "go", "java",
+ "c", "h", "cpp", "cc", "cxx", "hpp", "hh", "hxx", "rb", "php", "cs", "sh", "bash",
+ "kt", "kts", "swift", "scala", "sc", "dart", "lua", "pl", "pm", "r", "jl", "hs", "ex",
+ "exs", "erl", "hrl", "ml", "mli", "zig", "m", "mm", "groovy", "gradle", "ps1", "psm1",
+ "psd1", "fs", "fsx", "nix", "f90", "f95", "f03", "sol", "clj", "cljs", "cljc", "scm",
+ "ss", "sld", "sps",
+ ];
+ for ext in claimed {
+ assert!(
+ is_code_ext(ext),
+ "{ext} is in the hub lang table but the extractor no longer treats it as code"
+ );
+ assert!(
+ lang_for_ext(ext, "").is_some(),
+ "{ext} resolves to no language"
+ );
+ }
+ // A non-code extension resolves to no language.
+ assert!(lang_for_ext("md", "").is_none());
+ assert!(lang_for_ext("", "").is_none());
+ }
+
+ #[test]
+ fn dot_m_probes_objc_vs_matlab() {
+ assert_eq!(lang_for_ext("m", "@interface Foo\n@end\n"), Some("objc"));
+ assert_eq!(lang_for_ext("m", "function y = f(x)\n"), Some("matlab"));
+ assert_eq!(lang_for_ext("mm", ""), Some("objc"));
+ }
}
diff --git a/engine/crates/xerj-hub/tests/fixtures/mini-c/LICENSE b/engine/crates/xerj-hub/tests/fixtures/mini-c/LICENSE
new file mode 100644
index 000000000..0c5203ca4
--- /dev/null
+++ b/engine/crates/xerj-hub/tests/fixtures/mini-c/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 mini-c authors
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/engine/crates/xerj-hub/tests/fixtures/mini-c/buffer.c b/engine/crates/xerj-hub/tests/fixtures/mini-c/buffer.c
new file mode 100644
index 000000000..0a835a470
--- /dev/null
+++ b/engine/crates/xerj-hub/tests/fixtures/mini-c/buffer.c
@@ -0,0 +1,22 @@
+#include "limits.h"
+#include <string.h>
+
+#define MINI_BUFFER_CAP 256
+
+static char mini_buffer[MINI_BUFFER_CAP];
+
+/* Copy at most MINI_BUFFER_CAP-1 bytes, always NUL-terminating. */
+int mini_buffer_set(const char *src)
+{
+ size_t n = strlen(src);
+ if (n >= MINI_BUFFER_CAP)
+ n = MINI_BUFFER_CAP - 1;
+ memcpy(mini_buffer, src, n);
+ mini_buffer[n] = '\0';
+ return (int)n;
+}
+
+const char *mini_buffer_get(void)
+{
+ return mini_buffer;
+}
diff --git a/engine/crates/xerj-hub/tests/fixtures/mini-c/clamp.c b/engine/crates/xerj-hub/tests/fixtures/mini-c/clamp.c
new file mode 100644
index 000000000..011d7dc49
--- /dev/null
+++ b/engine/crates/xerj-hub/tests/fixtures/mini-c/clamp.c
@@ -0,0 +1,16 @@
+#include "limits.h"
+
+/* Clamp a value into [lo, hi]. */
+int mini_clamp(int value, int lo, int hi)
+{
+ if (value < lo)
+ return lo;
+ if (value > hi)
+ return hi;
+ return value;
+}
+
+int mini_within_limit(int value)
+{
+ return mini_clamp(value, 0, MINI_LIMIT);
+}
diff --git a/engine/crates/xerj-hub/tests/fixtures/mini-c/hash.c b/engine/crates/xerj-hub/tests/fixtures/mini-c/hash.c
new file mode 100644
index 000000000..69f9e2290
--- /dev/null
+++ b/engine/crates/xerj-hub/tests/fixtures/mini-c/hash.c
@@ -0,0 +1,13 @@
+#include "limits.h"
+
+#define MINI_HASH_SEED 5381
+
+/* A tiny djb2 hash, bounded to MINI_LIMIT buckets. */
+unsigned long mini_hash(const char *s)
+{
+ unsigned long h = MINI_HASH_SEED;
+ int c;
+ while ((c = *s++))
+ h = ((h << 5) + h) + (unsigned long)c;
+ return h % MINI_LIMIT;
+}
diff --git a/engine/crates/xerj-hub/tests/fixtures/mini-c/limits.h b/engine/crates/xerj-hub/tests/fixtures/mini-c/limits.h
new file mode 100644
index 000000000..f0d0fa650
--- /dev/null
+++ b/engine/crates/xerj-hub/tests/fixtures/mini-c/limits.h
@@ -0,0 +1,13 @@
+#ifndef MINI_LIMITS_H
+#define MINI_LIMITS_H
+
+/* The one definition the def-mode test looks up. */
+#define MINI_LIMIT 128
+
+#define MINI_VERSION_MAJOR 1
+#define MINI_VERSION_MINOR 4
+#define MINI_NAME "mini-c"
+
+int mini_clamp(int value, int lo, int hi);
+
+#endif /* MINI_LIMITS_H */
diff --git a/engine/crates/xerj-hub/tests/fixtures/mini-c/parse.c b/engine/crates/xerj-hub/tests/fixtures/mini-c/parse.c
new file mode 100644
index 000000000..6b0ccdcd4
--- /dev/null
+++ b/engine/crates/xerj-hub/tests/fixtures/mini-c/parse.c
@@ -0,0 +1,17 @@
+#include "limits.h"
+#include <ctype.h>
+
+#define MINI_RADIX 10
+
+/* Parse a non-negative decimal integer, capped at MINI_LIMIT. */
+int mini_parse_uint(const char *s)
+{
+ int acc = 0;
+ while (*s && isdigit((unsigned char)*s)) {
+ acc = acc * MINI_RADIX + (*s - '0');
+ if (acc > MINI_LIMIT)
+ return MINI_LIMIT;
+ s++;
+ }
+ return acc;
+}
diff --git a/engine/crates/xerj-hub/tests/pack_roundtrip.rs b/engine/crates/xerj-hub/tests/pack_roundtrip.rs
new file mode 100644
index 000000000..cc917701e
--- /dev/null
+++ b/engine/crates/xerj-hub/tests/pack_roundtrip.rs
@@ -0,0 +1,487 @@
+//! Corpus Hub v2 — the pack build → pull → `def` roundtrip (plan §2/§3 "Tests").
+//!
+//! This boots REAL nodes in-process (an ephemeral TCP port each, the way
+//! `xerj-api`'s endpoint tests build a router) so the snapshot/restore HTTP
+//! calls run end to end:
+//!
+//! - build a mini-c pack on node A (create a `-defs` index, bulk the defs,
+//! snapshot it, [`pack::write_pack`] + a test keypair);
+//! - pull it into node B's empty data dir through the real `xerj hub pull` CLI,
+//! verifying sha256 THEN signature before extracting;
+//! - assert `def::lookup` answers `MINI_LIMIT = 128` and the state ledger says
+//! `source: hubpack`;
+//! - a flipped archive byte makes `pull` exit 3 and extract nothing;
+//! - a second pull of the same pin says "already present";
+//! - a `format_version: 2` pack is refused (exit 3).
+//!
+//! The archive-level guarantees (verify-before-extract, SHA256SUMS coverage,
+//! format-version refusal) are also covered by `pack.rs`'s unit tests; this file
+//! adds the parts that need a live node: restore and the `def` query over it.
+//!
+//! One `#[tokio::test]` holds the whole flow because it mutates process-global
+//! env (`XERJ_CODE_HOME`, `XERJ_HUB_HOME`, `XERJ_HUB_PUBKEY`) between scenarios.
+
+use std::path::{Path, PathBuf};
+use std::time::Duration;
+
+use serde_json::json;
+use sha2::{Digest, Sha256};
+
+use xerj_autoindex::harvest::sign::generate_keypair;
+use xerj_hub::node::HubNode;
+use xerj_hub::pack::{self, PackFileEntry};
+use xerj_hub::{
+ Catalogue, CatalogueEntry, DefRecord, LicenceClass, PackIndex, PackManifest, PackSource,
+ Sketch, CATALOGUE_FORMAT_VERSION, PACK_FORMAT_VERSION,
+};
+
+const PIN_SHA: &str = "0774d05537f9762f838f7ab541b7765f1a729cb5";
+const PIN8: &str = "0774d055";
+const PIN_DATE: &str = "2026-10-02";
+const PREFIX: &str = "xc-mini-c-b1";
+
+/// Boot an es-compat node on an ephemeral port with `data_dir` and the given
+/// snapshot-repo allowlist, and wait until it answers.
+async fn spawn_node(data_dir: &Path, allowlist: Vec<String>) -> String {
+ std::fs::create_dir_all(data_dir).unwrap();
+ let mut config = xerj_common::config::Config::default();
+ config.server.data_dir = data_dir.to_string_lossy().into_owned();
+ config.storage.wal_sync = xerj_common::config::WalSync::Async;
+ config.limits.snapshot_repo_allowlist = allowlist;
+ let metrics = xerj_common::metrics::Metrics::new().unwrap();
+ let engine = xerj_engine::Engine::new(config.clone()).unwrap();
+ let state = xerj_api::state::AppState::new(config, engine, metrics);
+ let app = xerj_api::router::build_es_compat_router(state);
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let port = listener.local_addr().unwrap().port();
+ tokio::spawn(async move {
+ let _ = axum::serve(listener, app.into_make_service()).await;
+ });
+ let url = format!("http://127.0.0.1:{port}");
+ let probe = url.clone();
+ tokio::task::spawn_blocking(move || {
+ HubNode::connect(&probe)
+ .unwrap()
+ .wait_until_reachable(Duration::from_secs(30))
+ .unwrap();
+ })
+ .await
+ .unwrap();
+ url
+}
+
+/// The defs the test indexes and packs. `MINI_LIMIT` is the §3 lookup target.
+fn sample_defs() -> Vec<DefRecord> {
+ vec![
+ DefRecord {
+ symbol: "MINI_LIMIT".into(),
+ kind: "define".into(),
+ lang: "c".into(),
+ file: "limits.h".into(),
+ line: 5,
+ text: "#define MINI_LIMIT 128".into(),
+ value: Some("128".into()),
+ },
+ DefRecord {
+ symbol: "MINI_HASH_SEED".into(),
+ kind: "define".into(),
+ lang: "c".into(),
+ file: "hash.c".into(),
+ line: 3,
+ text: "#define MINI_HASH_SEED 5381".into(),
+ value: Some("5381".into()),
+ },
+ DefRecord {
+ symbol: "mini_clamp".into(),
+ kind: "function".into(),
+ lang: "c".into(),
+ file: "clamp.c".into(),
+ line: 4,
+ text: "int mini_clamp(int value, int lo, int hi)".into(),
+ value: None,
+ },
+ ]
+}
+
+fn sha256_hex(path: &Path) -> String {
+ let bytes = std::fs::read(path).unwrap();
+ Sha256::digest(&bytes)
+ .iter()
+ .map(|b| format!("{b:02x}"))
+ .collect()
+}
+
+/// A `PackManifest` for the mini-c pack at a given `format_version`.
+fn manifest(format_version: u32) -> PackManifest {
+ PackManifest {
+ format_version,
+ slug: "mini-c".into(),
+ pin_sha: PIN_SHA.into(),
+ pin_date: PIN_DATE.into(),
+ built_at: "2026-10-14T00:00:00Z".into(),
+ builder_version: "xerj test".into(),
+ index_prefix: PREFIX.into(),
+ indices: vec![
+ PackIndex {
+ name: format!("{PREFIX}-defs"),
+ docs: 3,
+ bytes: 0,
+ },
+ PackIndex {
+ name: format!("{PREFIX}-docs"),
+ docs: 1,
+ bytes: 0,
+ },
+ ],
+ snapshot_name: format!("mini-c-{PIN8}"),
+ licence_spdx: "MIT".into(),
+ licence_class: LicenceClass::AdaptWithAttribution,
+ sources: vec![PackSource {
+ repo: "mini-c".into(),
+ url: "file:///fixtures/mini-c".into(),
+ sha: PIN_SHA.into(),
+ licence: "MIT".into(),
+ }],
+ defs_count: 3,
+ files_count: 2,
+ }
+}
+
+/// Create the docs + defs indices on `url`, bulk the defs, and snapshot
+/// `<prefix>-*` into `location`. Leaves the snapshot files on disk for packing.
+fn seed_and_snapshot(url: &str, location: &Path) {
+ let node = HubNode::connect(url).unwrap();
+ // A docs index so the snapshot carries more than one index (realistic).
+ node.request_ok(
+ "PUT",
+ &format!("/{PREFIX}-docs"),
+ Some(&json!({"mappings":{"properties":{"body":{"type":"text"}}}})),
+ )
+ .unwrap();
+ node.bulk_ndjson(
+ &format!("/{PREFIX}-docs/_bulk"),
+ "{\"index\":{}}\n{\"body\":\"mini c reference\"}\n".to_string(),
+ )
+ .unwrap();
+
+ // The defs index with the §3 mapping.
+ node.request_ok(
+ "PUT",
+ &format!("/{PREFIX}-defs"),
+ Some(&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"}
+ }}})),
+ )
+ .unwrap();
+ let mut ndjson = String::new();
+ for d in sample_defs() {
+ ndjson.push_str("{\"index\":{}}\n");
+ ndjson.push_str(
+ &json!({
+ "symbol": d.symbol, "symbol_text": d.symbol, "kind": d.kind,
+ "lang": d.lang, "file": d.file, "line": d.line, "text": d.text, "value": d.value,
+ })
+ .to_string(),
+ );
+ ndjson.push('\n');
+ }
+ node.bulk_ndjson(&format!("/{PREFIX}-defs/_bulk"), ndjson)
+ .unwrap();
+ node.request_ok("POST", &format!("/{PREFIX}-defs/_refresh"), None)
+ .ok();
+
+ node.request_ok(
+ "PUT",
+ "/_snapshot/hub-build",
+ Some(&json!({"type":"fs","settings":{"location": location.to_string_lossy()}})),
+ )
+ .unwrap();
+ node.request_ok(
+ "PUT",
+ &format!("/_snapshot/hub-build/mini-c-{PIN8}?wait_for_completion=true"),
+ Some(&json!({"indices": format!("{PREFIX}-*")})),
+ )
+ .unwrap();
+}
+
+/// Write a catalogue with one mini-c entry pointing at a `file://` pack.
+fn write_catalogue(hub_home: &Path, archive: &Path, pack_sha256: &str) {
+ let sig = {
+ let mut s = archive.as_os_str().to_os_string();
+ s.push(".sig");
+ PathBuf::from(s)
+ };
+ let entry = CatalogueEntry {
+ slug: "mini-c".into(),
+ domain: "DEV".into(),
+ topics: vec!["c".into()],
+ ask_for: "a tiny C fixture corpus".into(),
+ pin_sha: PIN_SHA.into(),
+ pin_date: PIN_DATE.into(),
+ refresh_cadence_days: 7,
+ licence_spdx: "MIT".into(),
+ licence_class: LicenceClass::AdaptWithAttribution,
+ pack_bytes: std::fs::metadata(archive).map(|m| m.len()).unwrap_or(0),
+ pack_url: format!("file://{}", archive.display()),
+ pack_sha256: pack_sha256.to_string(),
+ sig_url: format!("file://{}", sig.display()),
+ dependency_names: vec![],
+ quality_grade: None,
+ term_sketch: Sketch {
+ m_bits: 64,
+ k_hashes: 7,
+ bits_base64: "AAAAAAAAAAA=".into(),
+ },
+ };
+ let cat = Catalogue {
+ format_version: CATALOGUE_FORMAT_VERSION,
+ generated_at: "2026-10-14T00:00:00Z".into(),
+ corpora: vec![entry],
+ };
+ std::fs::create_dir_all(hub_home).unwrap();
+ std::fs::write(
+ hub_home.join("catalogue.json"),
+ serde_json::to_vec(&cat).unwrap(),
+ )
+ .unwrap();
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn pack_build_pull_def_roundtrip() {
+ // One canonical work root so every snapshot location is inside the nodes'
+ // allowlist (the engine refuses a repo location outside data_dir or the
+ // allowlist — plan §2; we configure the root, never weaken the check).
+ let work_tmp = tempfile::tempdir().unwrap();
+ let work = std::fs::canonicalize(work_tmp.path()).unwrap();
+ let out = work.join("out");
+ std::fs::create_dir_all(&out).unwrap();
+ let allowlist = vec![work.to_string_lossy().into_owned()];
+
+ let (seed, public) = generate_keypair().unwrap();
+
+ // ── Build the pack on node A ──────────────────────────────────────────
+ let url_a = spawn_node(&work.join("data-a"), allowlist.clone()).await;
+ let location = out.join("mini-c").join("snapshot");
+ {
+ let url_a = url_a.clone();
+ let location = location.clone();
+ tokio::task::spawn_blocking(move || seed_and_snapshot(&url_a, &location))
+ .await
+ .unwrap();
+ }
+
+ // write_pack from the on-disk snapshot + the matching defs/files.
+ let defs = sample_defs();
+ let files = vec![
+ PackFileEntry {
+ path: "LICENSE".into(),
+ lang: "".into(),
+ bytes: 1069,
+ licence: "MIT".into(),
+ },
+ PackFileEntry {
+ path: "limits.h".into(),
+ lang: "c".into(),
+ bytes: 300,
+ licence: "MIT".into(),
+ },
+ ];
+ let archive = out.join(format!("mini-c-{PIN8}.hubpack.tar.zst"));
+ {
+ let (m, d, f, loc, seed) = (
+ manifest(PACK_FORMAT_VERSION),
+ defs.clone(),
+ files.clone(),
+ location.clone(),
+ seed.clone(),
+ );
+ let archive = archive.clone();
+ tokio::task::spawn_blocking(move || {
+ pack::write_pack(&archive, &m, &d, &f, &loc, &seed).unwrap();
+ })
+ .await
+ .unwrap();
+ }
+ assert!(archive.exists(), "archive written");
+ let good_sha = sha256_hex(&archive);
+
+ // ── Scenario 1: a flipped byte is refused (exit 3), nothing extracted ──
+ {
+ let code_home = work.join("code-flip");
+ let hub_home = work.join("hub-flip");
+ let flipped = out.join("flipped.hubpack.tar.zst");
+ std::fs::copy(&archive, &flipped).unwrap();
+ // keep the sibling .sig next to the flipped copy
+ std::fs::copy(
+ archive.with_file_name(format!("mini-c-{PIN8}.hubpack.tar.zst.sig")),
+ flipped.with_file_name("flipped.hubpack.tar.zst.sig"),
+ )
+ .unwrap();
+ let mut bytes = std::fs::read(&flipped).unwrap();
+ let mid = bytes.len() / 2;
+ bytes[mid] ^= 0xff;
+ std::fs::write(&flipped, &bytes).unwrap();
+ // catalogue records the ORIGINAL sha, so the flip is caught.
+ write_catalogue(&hub_home, &flipped, &good_sha);
+
+ let url_a2 = url_a.clone();
+ let (ch, hh, pk) = (code_home.clone(), hub_home.clone(), public.clone());
+ let rc = tokio::task::spawn_blocking(move || {
+ std::env::set_var("XERJ_CODE_HOME", &ch);
+ std::env::set_var("XERJ_HUB_HOME", &hh);
+ std::env::set_var("XERJ_HUB_PUBKEY", &pk);
+ xerj_hub::cli::run_hub_cli(&[
+ "pull".into(),
+ "mini-c".into(),
+ "--url".into(),
+ url_a2,
+ "--quiet".into(),
+ ])
+ })
+ .await
+ .unwrap();
+ assert_eq!(rc, 3, "a flipped archive fails verification with exit 3");
+ let extract = hub_home.join("packs").join("mini-c").join(PIN8);
+ assert!(
+ !extract.exists(),
+ "nothing is extracted when verification fails"
+ );
+ }
+
+ // ── Scenario 2: a format_version: 2 pack is refused (exit 3) ───────────
+ {
+ let code_home = work.join("code-v2");
+ let hub_home = work.join("hub-v2");
+ let v2 = out.join("v2.hubpack.tar.zst");
+ {
+ let (m, d, f, loc, seed) = (
+ manifest(2),
+ defs.clone(),
+ files.clone(),
+ location.clone(),
+ seed.clone(),
+ );
+ let v2 = v2.clone();
+ tokio::task::spawn_blocking(move || {
+ pack::write_pack(&v2, &m, &d, &f, &loc, &seed).unwrap();
+ })
+ .await
+ .unwrap();
+ }
+ let v2_sha = sha256_hex(&v2);
+ write_catalogue(&hub_home, &v2, &v2_sha);
+
+ let url_a2 = url_a.clone();
+ let (ch, hh, pk) = (code_home.clone(), hub_home.clone(), public.clone());
+ let rc = tokio::task::spawn_blocking(move || {
+ std::env::set_var("XERJ_CODE_HOME", &ch);
+ std::env::set_var("XERJ_HUB_HOME", &hh);
+ std::env::set_var("XERJ_HUB_PUBKEY", &pk);
+ xerj_hub::cli::run_hub_cli(&[
+ "pull".into(),
+ "mini-c".into(),
+ "--url".into(),
+ url_a2,
+ "--quiet".into(),
+ ])
+ })
+ .await
+ .unwrap();
+ assert_eq!(rc, 3, "a future pack format_version is refused");
+ }
+
+ // ── Scenario 3: a valid pull into node B, then def, then already-present ─
+ let url_b = spawn_node(&work.join("data-b"), allowlist.clone()).await;
+ let code_home = work.join("code-pull");
+ let hub_home = work.join("hub-pull");
+ write_catalogue(&hub_home, &archive, &good_sha);
+
+ // First pull — downloads, verifies, restores, writes the ledger.
+ let rc = {
+ let (url_b, ch, hh, pk) = (
+ url_b.clone(),
+ code_home.clone(),
+ hub_home.clone(),
+ public.clone(),
+ );
+ tokio::task::spawn_blocking(move || {
+ std::env::set_var("XERJ_CODE_HOME", &ch);
+ std::env::set_var("XERJ_HUB_HOME", &hh);
+ std::env::set_var("XERJ_HUB_PUBKEY", &pk);
+ xerj_hub::cli::run_hub_cli(&[
+ "pull".into(),
+ "mini-c".into(),
+ "--url".into(),
+ url_b,
+ "--quiet".into(),
+ ])
+ })
+ .await
+ .unwrap()
+ };
+ assert_eq!(rc, 0, "a valid pack pulls cleanly");
+
+ // The ledger records source: hubpack.
+ let state_json: serde_json::Value = serde_json::from_slice(
+ &std::fs::read(code_home.join("state").join("mini-c.json")).unwrap(),
+ )
+ .unwrap();
+ assert_eq!(state_json["source"], json!("hubpack"));
+ assert_eq!(state_json["index_prefix"], json!(PREFIX));
+ assert_eq!(state_json["pin_sha"], json!(PIN_SHA));
+
+ // def answers MINI_LIMIT = 128 from the restored defs index.
+ let answer = {
+ let (url_b, ch) = (url_b.clone(), code_home.clone());
+ tokio::task::spawn_blocking(move || {
+ std::env::set_var("XERJ_CODE_HOME", &ch);
+ let node = HubNode::connect(&url_b).unwrap();
+ xerj_hub::def::lookup(&node, "mini-c", "MINI_LIMIT", 5)
+ })
+ .await
+ .unwrap()
+ };
+ assert_eq!(answer.corpus, "mini-c");
+ assert_eq!(answer.pin_date, PIN_DATE);
+ assert_eq!(answer.hits.len(), 1, "one exact MINI_LIMIT hit: {answer:?}");
+ assert_eq!(answer.hits[0].value.as_deref(), Some("128"));
+ assert_eq!(answer.hits[0].file, "limits.h");
+ assert_eq!(answer.hits[0].line, 5);
+
+ // Second pull of the same pin → already present, restores nothing.
+ let rc2 = {
+ let (url_b, ch, hh, pk) = (
+ url_b.clone(),
+ code_home.clone(),
+ hub_home.clone(),
+ public.clone(),
+ );
+ tokio::task::spawn_blocking(move || {
+ std::env::set_var("XERJ_CODE_HOME", &ch);
+ std::env::set_var("XERJ_HUB_HOME", &hh);
+ std::env::set_var("XERJ_HUB_PUBKEY", &pk);
+ xerj_hub::cli::run_hub_cli(&[
+ "pull".into(),
+ "mini-c".into(),
+ "--url".into(),
+ url_b,
+ "--quiet".into(),
+ ])
+ })
+ .await
+ .unwrap()
+ };
+ assert_eq!(rc2, 0, "a second pull of the same pin is a no-op success");
+
+ // Clean up the env so it does not leak to other tests in the binary.
+ std::env::remove_var("XERJ_CODE_HOME");
+ std::env::remove_var("XERJ_HUB_HOME");
+ std::env::remove_var("XERJ_HUB_PUBKEY");
+}
diff --git a/engine/crates/xerj-server/Cargo.toml b/engine/crates/xerj-server/Cargo.toml
index 13b64ae2e..a11e0edde 100644
--- a/engine/crates/xerj-server/Cargo.toml
+++ b/engine/crates/xerj-server/Cargo.toml
@@ -24,6 +24,8 @@ xerj-compress = { path = "../xerj-compress" }
xerj-cluster = { path = "../xerj-cluster" }
xerj-console-api = { path = "../xerj-console-api" }
xerj-autoindex = { path = "../xerj-autoindex" }
+# Corpus Hub v2 client: `xerj hub …` and the `--def` code path.
+xerj-hub = { path = "../xerj-hub" }
# `xerj mcp` — the MCP stdio server, in the one binary users install. Pulls in
# only reqwest + serde_json, both already in this tree.
xerj-mcp = { path = "../xerj-mcp" }
diff --git a/engine/crates/xerj-server/src/main.rs b/engine/crates/xerj-server/src/main.rs
index bb4c24ba4..4b297ef89 100644
--- a/engine/crates/xerj-server/src/main.rs
+++ b/engine/crates/xerj-server/src/main.rs
@@ -2293,9 +2293,11 @@ async fn async_main() -> Result<()> {
if matches!(argv1.as_deref(), Some("code")) {
// Reference-coding retrieval (issue #977, previously xc.py): blocking
// ES-compat client + local state ledger, synchronous — off the
- // runtime like `def`.
+ // 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 code = tokio::task::spawn_blocking(move || xerj_autoindex::xc::run_code_cli(&args))
+ let code = tokio::task::spawn_blocking(move || xerj_hub::cli::run_code(&args))
.await
.unwrap_or(1);
std::process::exit(code);
@@ -2310,6 +2312,16 @@ async fn async_main() -> Result<()> {
.unwrap_or(1);
std::process::exit(code);
}
+ if matches!(argv1.as_deref(), Some("hub")) {
+ // 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 code = tokio::task::spawn_blocking(move || xerj_hub::cli::run_hub_cli(&args))
+ .await
+ .unwrap_or(1);
+ std::process::exit(code);
+ }
// Start profiling before config loading, TLS, engine replay, and router
// construction so delay=0 is a genuine initialization profile.