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(autoindex,xerj-common): corpus add --from <pack> — harvested pack consumption (M3)

xerj-org44d6b870ff17
diff --git a/engine/crates/xerj-autoindex/src/harvest/pack.rs b/engine/crates/xerj-autoindex/src/harvest/pack.rs
index 357614967..bcb9fdd5b 100644
--- a/engine/crates/xerj-autoindex/src/harvest/pack.rs
+++ b/engine/crates/xerj-autoindex/src/harvest/pack.rs
@@ -13,6 +13,12 @@
//!
//! `manifest.json` and `SHA256SUMS` necessarily vary (timestamp,
//! generation) — determinism is claimed for the RECORDS, never the wrapper.
+//!
+//! Reading a pack back ([`read_manifest`]) is the consumption half of
+//! `xerj corpus add --from <pack>`: checksum-verify EVERYTHING the manifest
+//! and SHA256SUMS claim, refusing loudly on any mismatch, because a pack is
+//! an artifact that traveled — disk, download, or release attachment —
+//! before it got here.
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
@@ -208,6 +214,230 @@ fn hex(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{b:02x}")).collect()
}
+// ── reading a pack back (consumption) ───────────────────────────────────────
+
+/// One source row of a read pack — the pseudo-repo `corpus add` writes for
+/// it (repo=slug, licence, url, watermark-as-sha).
+#[derive(Debug, Clone)]
+pub struct PackSource {
+ pub slug: String,
+ pub licence: String,
+ pub url: Option<String>,
+ pub watermark: Option<String>,
+}
+
+/// One records file of a read pack, already checksum-verified.
+#[derive(Debug, Clone)]
+pub struct PackFile {
+ pub name: String,
+ pub records: usize,
+}
+
+/// A VERIFIED pack: everything the manifest and SHA256SUMS claim was checked
+/// against the bytes on disk before this was returned.
+#[derive(Debug)]
+pub struct PackMeta {
+ pub name: String,
+ pub description: String,
+ pub generation: u64,
+ pub records: usize,
+ pub sources: Vec<PackSource>,
+ /// Records files in name order — the deterministic read order.
+ pub files: Vec<PackFile>,
+}
+
+/// Read and VERIFY a pack directory. Strict where [`emit`] was careful: an
+/// unknown `format_version` is refused (a reader that silently indexed a
+/// future format would mis-map fields), every SHA256SUMS line is re-hashed,
+/// and every records file's sha256 and line count must match the manifest.
+/// A pack that fails here is corrupt or tampered with, and the error says
+/// which file and why.
+pub fn read_manifest(pack_dir: &Path) -> Result<PackMeta> {
+ let at = |what: &str| format!("{}: {what}", pack_dir.display());
+
+ let v: Value = serde_json::from_str(
+ &std::fs::read_to_string(pack_dir.join("manifest.json"))
+ .with_context(|| at("cannot read manifest.json"))?,
+ )
+ .with_context(|| at("manifest.json is not valid JSON"))?;
+
+ let version = v.get("format_version").and_then(Value::as_u64).unwrap_or(0);
+ if version != 1 {
+ bail!(at(&format!(
+ "pack format version {version} is not supported by this build (supported: 1)"
+ )));
+ }
+ let kind = v.get("kind").and_then(Value::as_str).unwrap_or("");
+ if kind != "harvested" {
+ bail!(at(&format!(
+ "not a harvested pack (kind='{kind}') — this reader consumes packs from `xerj \
+ corpus build`"
+ )));
+ }
+ let name = v.get("pack").and_then(Value::as_str).unwrap_or("");
+ if name.is_empty() {
+ bail!(at("manifest has no 'pack' name"));
+ }
+
+ // files: name → {sha256, records}. A file name is about to become a path
+ // under pack_dir — plain file names only, same charset thinking as the
+ // zip-entry gate in source.rs.
+ let mut files: Vec<PackFile> = Vec::new();
+ let mut declared: BTreeMap<String, String> = BTreeMap::new();
+ for (fname, meta) in v
+ .get("files")
+ .and_then(Value::as_object)
+ .ok_or_else(|| anyhow::anyhow!(at("manifest has no 'files' map")))?
+ {
+ if !plain_file_name(fname) {
+ bail!(at(&format!(
+ "manifest names file '{fname}', which is not a plain file name"
+ )));
+ }
+ let sha = meta
+ .get("sha256")
+ .and_then(Value::as_str)
+ .filter(|s| s.len() == 64 && s.chars().all(|c| c.is_ascii_hexdigit()))
+ .ok_or_else(|| anyhow::anyhow!(at(&format!("file '{fname}' has no valid sha256"))))?;
+ let records =
+ meta.get("records").and_then(Value::as_u64).ok_or_else(|| {
+ anyhow::anyhow!(at(&format!("file '{fname}' has no record count")))
+ })? as usize;
+ declared.insert(fname.clone(), sha.to_string());
+ files.push(PackFile {
+ name: fname.clone(),
+ records,
+ });
+ }
+ files.sort_by(|a, b| a.name.cmp(&b.name));
+
+ // SHA256SUMS is the outer truth: re-hash EVERYTHING it names.
+ let sums_raw = std::fs::read_to_string(pack_dir.join("SHA256SUMS"))
+ .with_context(|| at("cannot read SHA256SUMS"))?;
+ let mut sums: BTreeMap<String, String> = BTreeMap::new();
+ for line in sums_raw.lines() {
+ let line = line.trim_end_matches('\r');
+ if line.is_empty() {
+ continue;
+ }
+ let Some((sha, fname)) = line.split_once(" ") else {
+ bail!(at(&format!(
+ "SHA256SUMS line is not '<sha> <file>': '{line}'"
+ )));
+ };
+ if !plain_file_name(fname) {
+ bail!(at(&format!(
+ "SHA256SUMS names '{fname}', which is not a plain file name"
+ )));
+ }
+ sums.insert(fname.to_string(), sha.to_string());
+ }
+ for required in ["manifest.json", "recipe.toml"] {
+ if !sums.contains_key(required) {
+ bail!(at(&format!("SHA256SUMS does not cover {required}")));
+ }
+ }
+ for (fname, sha) in &declared {
+ if !sums.contains_key(fname) {
+ bail!(at(&format!("SHA256SUMS does not cover {fname}")));
+ }
+ if &sums[fname] != sha {
+ bail!(at(&format!(
+ "{fname}: manifest sha256 and SHA256SUMS disagree — the pack is inconsistent"
+ )));
+ }
+ }
+ for (fname, sha) in &sums {
+ let bytes = std::fs::read(pack_dir.join(fname))
+ .with_context(|| at(&format!("SHA256SUMS names {fname}, which is missing")))?;
+ let got = hex(&Sha256::digest(&bytes));
+ if &got != sha {
+ bail!(at(&format!(
+ "{fname}: checksum mismatch (want {sha}, got {got}) — corrupt or tampered"
+ )));
+ }
+ }
+
+ // line counts: the manifest's per-file record counts must be the truth
+ for f in &files {
+ let n = std::fs::read_to_string(pack_dir.join(&f.name))
+ .with_context(|| at(&format!("cannot read {}", f.name)))?
+ .lines()
+ .filter(|l| !l.trim().is_empty())
+ .count();
+ if n != f.records {
+ bail!(at(&format!(
+ "{}: manifest says {} records, file holds {n}",
+ f.name, f.records
+ )));
+ }
+ }
+
+ let sources = v
+ .get("sources")
+ .and_then(Value::as_array)
+ .ok_or_else(|| anyhow::anyhow!(at("manifest has no 'sources' array")))?
+ .iter()
+ .map(|s| PackSource {
+ slug: s
+ .get("slug")
+ .and_then(Value::as_str)
+ .unwrap_or("")
+ .to_string(),
+ licence: s
+ .get("licence")
+ .and_then(Value::as_str)
+ .unwrap_or("")
+ .to_string(),
+ url: s
+ .get("url")
+ .and_then(Value::as_str)
+ .filter(|u| !u.is_empty())
+ .map(str::to_string),
+ watermark: s
+ .get("watermark")
+ .and_then(Value::as_str)
+ .filter(|w| !w.is_empty())
+ .map(str::to_string),
+ })
+ .collect::<Vec<PackSource>>();
+ if sources.is_empty() {
+ bail!(at("manifest declares no sources"));
+ }
+ if sources.iter().any(|s| s.slug.is_empty()) {
+ bail!(at("a manifest source has no slug"));
+ }
+
+ Ok(PackMeta {
+ name: name.to_string(),
+ description: v
+ .get("description")
+ .and_then(Value::as_str)
+ .unwrap_or("")
+ .to_string(),
+ generation: v.get("generation").and_then(Value::as_u64).unwrap_or(0),
+ records: v
+ .get("counts")
+ .and_then(|c| c.get("records"))
+ .and_then(Value::as_u64)
+ .unwrap_or(0) as usize,
+ sources,
+ files,
+ })
+}
+
+/// A name that may be joined onto a pack dir without escaping it: no path
+/// separators, no `..`, no drive letters, not hidden, not empty.
+fn plain_file_name(name: &str) -> bool {
+ !name.is_empty()
+ && !name.starts_with('.')
+ && !name.contains('/')
+ && !name.contains('\\')
+ && !name.contains(':')
+ && name != "."
+ && name != ".."
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -323,6 +553,169 @@ mod tests {
}
}
+ fn src_stat(slug: &str) -> SourceStat {
+ SourceStat {
+ slug: slug.to_string(),
+ kind: "dir".to_string(),
+ path: Some("data".to_string()),
+ url: None,
+ licence: "CC0-1.0".to_string(),
+ watermark: None,
+ unchanged: false,
+ records: 1,
+ new: 1,
+ skipped: 0,
+ pruned: 0,
+ }
+ }
+
+ fn stats_with_source() -> RunStats {
+ RunStats {
+ envelopes: 3,
+ per_source: vec![src_stat("a")],
+ }
+ }
+
+ #[test]
+ fn read_manifest_round_trips_a_verified_pack() {
+ let tmp = tempfile::tempdir().unwrap();
+ let records = vec![rec("a", &[]), rec("b", &[]), rec("c", &[])];
+ let r = emit(
+ tmp.path(),
+ &recipe("t", 2),
+ "# r\n",
+ records,
+ &stats_with_source(),
+ )
+ .unwrap();
+ let meta = read_manifest(&r.dir).unwrap();
+ assert_eq!(meta.name, "t");
+ assert_eq!(meta.generation, 1);
+ assert_eq!(meta.records, 3);
+ let total: usize = meta.files.iter().map(|f| f.records).sum();
+ assert_eq!(total, 3);
+ assert_eq!(meta.sources.len(), 1);
+ assert_eq!(meta.sources[0].slug, "a");
+ assert_eq!(meta.sources[0].licence, "CC0-1.0");
+ }
+
+ #[test]
+ fn read_manifest_names_the_tampered_file() {
+ let tmp = tempfile::tempdir().unwrap();
+ let r = emit(
+ tmp.path(),
+ &recipe("t", 1),
+ "# r\n",
+ vec![rec("a", &[])],
+ &stats_with_source(),
+ )
+ .unwrap();
+ let fname = meta_file_name(&r.dir);
+ let path = r.dir.join(&fname);
+ let mut bytes = std::fs::read(&path).unwrap();
+ bytes.push(b' ');
+ std::fs::write(&path, bytes).unwrap();
+ let err = read_manifest(&r.dir).unwrap_err().to_string();
+ assert!(err.contains("checksum mismatch"), "{err}");
+ assert!(err.contains(&fname), "{err}");
+ }
+
+ #[test]
+ fn read_manifest_refuses_an_unknown_format_version() {
+ let tmp = tempfile::tempdir().unwrap();
+ let r = emit(
+ tmp.path(),
+ &recipe("t", 1),
+ "# r\n",
+ vec![rec("a", &[])],
+ &stats_with_source(),
+ )
+ .unwrap();
+ // checked BEFORE any checksum: a future format must be refused on the
+ // version alone, not on a hash of a file we cannot interpret
+ let m: Value =
+ serde_json::from_str(&std::fs::read_to_string(r.dir.join("manifest.json")).unwrap())
+ .unwrap();
+ let mut m = m;
+ m["format_version"] = json!(2);
+ std::fs::write(
+ r.dir.join("manifest.json"),
+ serde_json::to_vec_pretty(&m).unwrap(),
+ )
+ .unwrap();
+ let err = read_manifest(&r.dir).unwrap_err().to_string();
+ assert!(err.contains("format version 2 is not supported"), "{err}");
+ }
+
+ #[test]
+ fn read_manifest_refuses_a_truncated_sums() {
+ let tmp = tempfile::tempdir().unwrap();
+ let r = emit(
+ tmp.path(),
+ &recipe("t", 1),
+ "# r\n",
+ vec![rec("a", &[])],
+ &stats_with_source(),
+ )
+ .unwrap();
+ let kept: String = std::fs::read_to_string(r.dir.join("SHA256SUMS"))
+ .unwrap()
+ .lines()
+ .filter(|l| !l.ends_with("manifest.json"))
+ .map(|l| format!("{l}\n"))
+ .collect();
+ std::fs::write(r.dir.join("SHA256SUMS"), kept).unwrap();
+ let err = read_manifest(&r.dir).unwrap_err().to_string();
+ assert!(err.contains("does not cover manifest.json"), "{err}");
+ }
+
+ #[test]
+ fn read_manifest_refuses_manifest_and_sums_disagreement() {
+ // A manifest whose files[] sha disagrees with SHA256SUMS: caught
+ // before any bytes are re-hashed, because the pack is internally
+ // inconsistent whichever of the two is the tampered one. (The case
+ // sums + manifest agree but the FILE differs is the tamper test
+ // above; the case everything-agree-but-lying is what signatures —
+ // a later milestone — exist for.)
+ let tmp = tempfile::tempdir().unwrap();
+ let r = emit(
+ tmp.path(),
+ &recipe("t", 1),
+ "# r\n",
+ vec![rec("a", &[])],
+ &stats_with_source(),
+ )
+ .unwrap();
+ let fname = meta_file_name(&r.dir);
+ let mut m: Value =
+ serde_json::from_str(&std::fs::read_to_string(r.dir.join("manifest.json")).unwrap())
+ .unwrap();
+ m["files"][&fname]["sha256"] = json!("0".repeat(64));
+ std::fs::write(
+ r.dir.join("manifest.json"),
+ serde_json::to_vec_pretty(&m).unwrap(),
+ )
+ .unwrap();
+ let err = read_manifest(&r.dir).unwrap_err().to_string();
+ assert!(err.contains("disagree"), "{err}");
+ assert!(err.contains(&fname), "{err}");
+ }
+
+ /// The first records file the manifest names (shards are hash-assigned,
+ /// so read the name instead of guessing it).
+ fn meta_file_name(pack_dir: &Path) -> String {
+ let m: Value =
+ serde_json::from_str(&std::fs::read_to_string(pack_dir.join("manifest.json")).unwrap())
+ .unwrap();
+ m["files"]
+ .as_object()
+ .unwrap()
+ .keys()
+ .next()
+ .unwrap()
+ .clone()
+ }
+
#[test]
fn duplicate_ids_are_refused() {
let tmp = tempfile::tempdir().unwrap();
diff --git a/engine/crates/xerj-autoindex/src/xc.rs b/engine/crates/xerj-autoindex/src/xc.rs
index b1ebe6697..19015dfbe 100644
--- a/engine/crates/xerj-autoindex/src/xc.rs
+++ b/engine/crates/xerj-autoindex/src/xc.rs
@@ -224,15 +224,17 @@ pub fn run_code_cli(args: &[String]) -> i32 {
// ── xerj corpus add ─────────────────────────────────────────────────────────
const CORPUS_USAGE: &str =
- "usage: xerj corpus add <name> <git-url>... | --from <manifest.json> [--as <name>]
+ "usage: xerj corpus add <name> <git-url>... | --from <manifest.json|pack-dir|pack.zip> [--as <name>]
xerj corpus build <name> [--recipe <path>] [--fresh]
xerj corpus index <name> [--fresh] [--url URL]
xerj corpus list [--url URL]
clone the repos, detect licences, write corpora/<name>/corpus.json;
---from takes the corpus name from the manifest's 'corpus' field unless
-<name> or --as overrides it; build harvests recipe sources into a
-deterministic pack under builds/<name>/ (see tools/xerj-code/);
+--from takes the corpus name from the manifest's 'corpus' field (or the
+pack's 'pack' field) unless <name> or --as overrides it; a harvested pack
+also checksum-verifies and materializes records per source; build
+harvests recipe sources into a deterministic pack under builds/<name>/
+(see tools/xerj-code/);
index builds/verifies/switches the corpus (exit 3 skips junk — normal);
list shows what is loaded on this node.";
@@ -384,6 +386,38 @@ fn run_corpus_add(args: &[String]) -> i32 {
);
return 2;
}
+ // A `--from` that names a harvested pack (a pack dir, the pack's own
+ // manifest.json, or a pack.zip) routes to the pack path BEFORE the
+ // hub-manifest arm reads it: the two are different documents (`repos[]`
+ // vs `files`+`kind`), and mis-reading one as the other produces noise,
+ // not a useful error.
+ if let Some(path) = &from {
+ match resolve_pack_source(path) {
+ Ok(FromPack::NotAPack) => {}
+ Ok(FromPack::Dir(dir)) => return run_corpus_add_pack(&dir, explicit_name),
+ Ok(FromPack::Zip(zip)) => {
+ // transient staging, never build state — it dies with this
+ // call, after the records have been copied out
+ let tmp = match tempfile::tempdir() {
+ Ok(t) => t,
+ Err(e) => {
+ eprintln!("xerj corpus add: cannot stage {zip}: {e}");
+ return 2;
+ }
+ };
+ let dest = tmp.path().join("pack");
+ if let Err(e) = crate::harvest::source::extract_zip(Path::new(&zip), &dest) {
+ eprintln!("xerj corpus add: cannot extract {zip}: {e:#}");
+ return 2;
+ }
+ return run_corpus_add_pack(&dest, explicit_name);
+ }
+ Err(e) => {
+ eprintln!("xerj corpus add: {e}");
+ return 2;
+ }
+ }
+ }
// The manifest is read BEFORE the name is finalised: with `--from` and
// no explicit <name>/--as, the manifest's own 'corpus' field supplies
// it. Everything downstream (dest, carry, entries) needs the resolved
@@ -439,6 +473,21 @@ fn run_corpus_add(args: &[String]) -> i32 {
let root = code_root();
let dest = root.join("corpora").join(&name);
+ // A corpus name is EITHER a cloned-repo corpus or a harvested one.
+ // Cloning repos into a harvested corpus's dir would corrupt both views:
+ // the manifest's pseudo-repos would sit beside real clones, and
+ // `xerj code`'s per-hit licence lookups would key on whichever won.
+ if let Ok(prev) = manifest::read_corpus_manifest(&dest.join("corpus.json")) {
+ if prev.kind.as_deref() == Some("harvested") {
+ eprintln!(
+ "xerj corpus add: corpus '{name}' is a harvested corpus — rebuild it from its pack:"
+ );
+ eprintln!(
+ "xerj corpus add: xerj corpus add {name} --from <pack-dir|pack.zip|manifest.json>"
+ );
+ return 2;
+ }
+ }
if let Err(e) = std::fs::create_dir_all(&dest) {
eprintln!("xerj corpus add: cannot create {}: {e}", dest.display());
return 2;
@@ -561,6 +610,248 @@ fn run_corpus_add(args: &[String]) -> i32 {
0
}
+// ── xerj corpus add --from <pack> ───────────────────────────────────────────
+
+/// What `--from` named, as decided by [`resolve_pack_source`].
+#[derive(Debug)]
+enum FromPack {
+ /// Not a pack — the hub-manifest arm handles it.
+ NotAPack,
+ /// A directory holding a harvested `manifest.json`.
+ Dir(PathBuf),
+ /// A zip file to stage and treat as `Dir` after extraction.
+ Zip(String),
+}
+
+/// Decide whether a `--from` argument names a harvested pack. A directory
+/// with a `manifest.json` whose `kind` is `harvested`, a `.json` file of the
+/// same shape (the pack's own manifest, one level inside the pack), or a
+/// `.zip` — anything else is `NotAPack`. `Err` is reserved for paths that
+/// LOOK like a pack but cannot be inspected: a broken zip or an unreadable
+/// manifest must be reported, never silently fallen through to the hub arm
+/// (which would emit a confusing `repos[]` error for the same file).
+fn resolve_pack_source(path: &str) -> Result<FromPack, String> {
+ let p = Path::new(path);
+ let is_harvested = |m: &Path| -> Result<bool, String> {
+ let v: Value = std::fs::read_to_string(m)
+ .map_err(|e| format!("cannot read {}: {e}", m.display()))
+ .and_then(|raw| {
+ serde_json::from_str(&raw)
+ .map_err(|e| format!("{} is not valid JSON: {e}", m.display()))
+ })?;
+ Ok(v.get("kind").and_then(Value::as_str) == Some("harvested"))
+ };
+ if p.is_dir() {
+ let m = p.join("manifest.json");
+ if !m.is_file() {
+ return Err(format!(
+ "{} is a directory with no manifest.json — name the pack directory, its \
+ manifest, or its zip",
+ p.display()
+ ));
+ }
+ return if is_harvested(&m)? {
+ Ok(FromPack::Dir(p.to_path_buf()))
+ } else {
+ Err(format!(
+ "{} holds a manifest.json that is not a harvested pack",
+ p.display()
+ ))
+ };
+ }
+ let lower = path.to_lowercase();
+ if lower.ends_with(".zip") {
+ return Ok(FromPack::Zip(path.to_string()));
+ }
+ if p.is_file() {
+ if let Ok(true) = is_harvested(p) {
+ let dir = p.parent().unwrap_or(Path::new(".")).to_path_buf();
+ return Ok(FromPack::Dir(dir));
+ }
+ }
+ Ok(FromPack::NotAPack)
+}
+
+/// `corpus add --from <pack>`: checksum-verify the pack, then materialize it
+/// as a corpus — one directory per source slug holding that source's
+/// records, plus an extended corpus.json whose pseudo-repos are the pack's
+/// sources. The per-slug layout is load-bearing, not cosmetic: `xerj code`
+/// derives a hit's licence from the FIRST path segment of its locator
+/// ([`xccode::passage::locator_repo`]), so `rustsec/records.jsonl` keys the
+/// same way a cloned `rustsec/` repo always did and the per-hit licence
+/// warnings work unchanged.
+fn run_corpus_add_pack(pack_dir: &Path, explicit_name: Option<String>) -> i32 {
+ let meta = match crate::harvest::pack::read_manifest(pack_dir) {
+ Ok(m) => m,
+ Err(e) => {
+ eprintln!("xerj corpus add: {e:#}");
+ return 2;
+ }
+ };
+ let name = match resolve_corpus_name(explicit_name, &meta.name, &pack_dir.display().to_string())
+ {
+ Ok(n) => n,
+ Err(e) => {
+ eprintln!("xerj corpus add: {e}");
+ return 2;
+ }
+ };
+ if let Err(e) = xccode::pathgate::valid_corpus_name(&name) {
+ eprintln!("xerj corpus add: {e}");
+ return 2;
+ }
+ let root = code_root();
+ let dest = root.join("corpora").join(&name);
+ // Same one-kind-per-name rule the git arm enforces, from the other side.
+ if let Ok(prev) = manifest::read_corpus_manifest(&dest.join("corpus.json")) {
+ if prev.kind.as_deref() != Some("harvested") {
+ eprintln!(
+ "xerj corpus add: corpus '{name}' already exists as a cloned-repo corpus at {}",
+ dest.display()
+ );
+ eprintln!("xerj corpus add: pick another name (--as <name>) or remove it first");
+ return 2;
+ }
+ }
+ println!(
+ "materializing corpus '{name}' from pack generation {}",
+ meta.generation
+ );
+ if let Err(e) = add_pack_materialize(&dest, pack_dir, &meta) {
+ eprintln!("xerj corpus add: {e:#}");
+ return 1;
+ }
+ let mut total = 0usize;
+ for s in &meta.sources {
+ let count = std::fs::read_to_string(dest.join(&s.slug).join("records.jsonl"))
+ .map(|t| t.lines().filter(|l| !l.trim().is_empty()).count())
+ .unwrap_or(0);
+ total += count;
+ println!(" [pack] {}: {} record(s) ({})", s.slug, count, s.licence);
+ if let Some(w) = xccode::licence::clone_warning_line(&s.licence) {
+ eprintln!("{w}");
+ }
+ }
+ println!(
+ "corpus '{name}': {} records from {} source(s) at {}",
+ total,
+ meta.sources.len(),
+ dest.display()
+ );
+ println!(
+ "share it: {} (rebuild with xerj corpus add {name} --from <that pack>)",
+ pack_dir.display()
+ );
+ println!("next: xerj corpus index {name}");
+ 0
+}
+
+/// Copy the pack's records into `corpora/<name>/<slug>/records.jsonl`
+/// (verbatim lines — the pack line IS canonical JSON), reconcile away slug
+/// dirs a previous add owned that this pack no longer has, and write the
+/// extended corpus.json. Records are routed by their `source` field (the
+/// merge winner), which the pack's uniform-key invariant guarantees on
+/// every record.
+fn add_pack_materialize(
+ dest: &Path,
+ pack_dir: &Path,
+ meta: &crate::harvest::pack::PackMeta,
+) -> anyhow::Result<()> {
+ use std::collections::HashSet;
+ use std::io::{BufRead, BufReader, Write};
+
+ let slugs: HashSet<&str> = meta.sources.iter().map(|s| s.slug.as_str()).collect();
+
+ // reconcile FIRST: every dir the previous harvested manifest owned is
+ // regenerated from this pack — drop them all, not just the renamed ones,
+ // or a re-add APPENDS to the old records.jsonl and duplicates every line
+ if let Ok(prev) = manifest::read_corpus_manifest(&dest.join("corpus.json")) {
+ for r in &prev.repos {
+ let _ = std::fs::remove_dir_all(dest.join(&r.repo));
+ }
+ }
+ std::fs::create_dir_all(dest).with_context(|| format!("cannot create {}", dest.display()))?;
+
+ // per-slug buffer: shard files interleave ids (bucket = hash(id) %
+ // shards), so the corpus's records.jsonl is re-sorted by id at write
+ // time — a refresh then diffs clean against the pack's own ordering
+ let mut by_slug: std::collections::HashMap<String, Vec<(String, String)>> =
+ std::collections::HashMap::new();
+ for f in &meta.files {
+ let rdr = BufReader::new(
+ std::fs::File::open(pack_dir.join(&f.name))
+ .with_context(|| format!("cannot read {}", f.name))?,
+ );
+ for line in rdr.lines() {
+ let line = line.with_context(|| format!("read {}", f.name))?;
+ if line.trim().is_empty() {
+ continue;
+ }
+ let v: Value = serde_json::from_str(&line)
+ .with_context(|| format!("{}: a record line is not valid JSON", f.name))?;
+ let slug = v.get("source").and_then(Value::as_str).unwrap_or("");
+ if !slugs.contains(slug) {
+ let fname = &f.name;
+ anyhow::bail!(
+ "{fname}: a record names source '{slug}' which the pack does not declare"
+ );
+ }
+ let id = v
+ .get("id")
+ .and_then(Value::as_str)
+ .unwrap_or("")
+ .to_string();
+ by_slug
+ .entry(slug.to_string())
+ .or_default()
+ .push((id, line));
+ }
+ }
+ if by_slug.is_empty() {
+ anyhow::bail!("pack holds no records — nothing to materialize");
+ }
+
+ let mut counts: std::collections::HashMap<String, u64> = std::collections::HashMap::new();
+ for (slug, mut records) in by_slug {
+ records.sort_by(|a, b| a.0.cmp(&b.0));
+ let dir = dest.join(&slug);
+ std::fs::create_dir_all(&dir)
+ .with_context(|| format!("cannot create {}", dir.display()))?;
+ let path = dir.join("records.jsonl");
+ let mut w = std::fs::File::create(&path)
+ .with_context(|| format!("cannot write {}", path.display()))?;
+ for (_, line) in &records {
+ // verbatim: the pack line IS canonical JSON
+ w.write_all(line.as_bytes())?;
+ w.write_all(b"\n")?;
+ }
+ counts.insert(slug, records.len() as u64);
+ }
+
+ let mut entries = Vec::new();
+ for s in &meta.sources {
+ let path = dest.join(&s.slug).join("records.jsonl");
+ let bytes = std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0);
+ entries.push(manifest::ManifestRepo {
+ repo: s.slug.clone(),
+ url: s.url.clone().unwrap_or_default(),
+ licence: s.licence.clone(),
+ sha: s.watermark.clone().unwrap_or_default(),
+ files: Some(*counts.get(&s.slug).unwrap_or(&0)),
+ bytes: Some(bytes),
+ review: None,
+ });
+ }
+ manifest::write_corpus_manifest_kind(
+ &dest.join("corpus.json"),
+ &meta.name,
+ Some("harvested"),
+ &chrono_now_stamp(),
+ &entries,
+ );
+ Ok(())
+}
+
fn record(
entries: &mut Vec<manifest::ManifestRepo>,
repo_name: &str,
@@ -1819,4 +2110,269 @@ mod tests {
assert!(node.live("xc-kv-000"));
assert!(node.ops.borrow().iter().all(|o| !o.starts_with("delete:")));
}
+
+ // ── corpus add --from <pack> (harvested consumption) ────────────────────
+
+ /// Holds XERJ_CODE_HOME at `home` for the guard's lifetime — both the
+ /// build and the add paths resolve their root through `code_root()` at
+ /// CALL time, so a test that builds a pack and then adds it needs the
+ /// env held across both, not scoped per call. Under ENV_LOCK for the
+ /// same reason the env tests above are (do NOT re-enter: the lock is not
+ /// reentrant, so nothing inside may take it again).
+ struct CodeHomeGuard(std::sync::MutexGuard<'static, ()>);
+ impl Drop for CodeHomeGuard {
+ fn drop(&mut self) {
+ std::env::remove_var("XERJ_CODE_HOME");
+ }
+ }
+ fn code_home(home: &Path) -> CodeHomeGuard {
+ let g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
+ std::env::set_var("XERJ_CODE_HOME", home);
+ CodeHomeGuard(g)
+ }
+
+ /// A small two-source pack under `home`: source `a` owns X1 (merged with
+ /// b's alias-linked record) and X3; source `b` wins nothing.
+ fn build_demo_pack(home: &Path) -> PathBuf {
+ let root = home.join("recipes");
+ std::fs::create_dir_all(root.join("data/a")).unwrap();
+ std::fs::create_dir_all(root.join("data/b")).unwrap();
+ std::fs::write(
+ root.join("demo.toml"),
+ r#"
+[recipe]
+format = 1
+name = "demo"
+
+[[sources]]
+slug = "a"
+kind = "dir"
+path = "data/a"
+format = "flat"
+licence = "CC0-1.0"
+
+[[sources]]
+slug = "b"
+kind = "dir"
+path = "data/b"
+format = "flat"
+licence = "CC-BY-4.0"
+
+[identity]
+edges = [{ field = "id" }, { field = "aliases", each = true }]
+canonical_source_order = ["a", "b"]
+
+[merge]
+precedence = ["a", "b"]
+"#,
+ )
+ .unwrap();
+ std::fs::write(
+ root.join("data/a/one.json"),
+ r#"{"id":"X1","aliases":["C1"],"title":"one"}"#,
+ )
+ .unwrap();
+ std::fs::write(
+ root.join("data/a/three.json"),
+ r#"{"id":"X3","title":"three"}"#,
+ )
+ .unwrap();
+ std::fs::write(
+ root.join("data/b/two.json"),
+ r#"{"id":"X2","aliases":["C1"],"title":"two"}"#,
+ )
+ .unwrap();
+ let rc = crate::harvest::run_build(&["demo".to_string()]);
+ assert_eq!(rc, 0, "pack build must succeed");
+ home.join("builds/demo/pack/demo")
+ }
+
+ fn records_lines(path: &Path) -> Vec<Value> {
+ std::fs::read_to_string(path)
+ .unwrap_or_default()
+ .lines()
+ .filter(|l| !l.trim().is_empty())
+ .map(|l| serde_json::from_str(l).unwrap())
+ .collect()
+ }
+
+ #[test]
+ fn resolve_pack_source_sniffs_the_pack_spellings() {
+ let tmp = tempfile::tempdir().unwrap();
+ let _h = code_home(tmp.path());
+ let pack = build_demo_pack(tmp.path());
+ assert!(matches!(
+ resolve_pack_source(&pack.display().to_string()).unwrap(),
+ FromPack::Dir(_)
+ ));
+ // the pack's own manifest names the pack (its parent dir)
+ assert!(matches!(
+ resolve_pack_source(&pack.join("manifest.json").display().to_string()).unwrap(),
+ FromPack::Dir(_)
+ ));
+ // a hub manifest is not a pack — the hub arm reads it
+ let hub = tmp.path().join("hub.json");
+ std::fs::write(&hub, r#"{"corpus":"x","repos":[]}"#).unwrap();
+ assert!(matches!(
+ resolve_pack_source(&hub.display().to_string()).unwrap(),
+ FromPack::NotAPack
+ ));
+ // a zip is staged, not inspected, here
+ let zipf = tmp.path().join("p.zip");
+ std::fs::write(&zipf, b"PK").unwrap();
+ assert!(matches!(
+ resolve_pack_source(&zipf.display().to_string()).unwrap(),
+ FromPack::Zip(_)
+ ));
+ // a directory without a manifest is an error, not a silent fallthrough
+ let empty = tmp.path().join("empty");
+ std::fs::create_dir_all(&empty).unwrap();
+ let err = resolve_pack_source(&empty.display().to_string()).unwrap_err();
+ assert!(err.contains("no manifest.json"), "{err}");
+ // and a dir whose manifest is not a harvested pack is named as such
+ let hubdir = tmp.path().join("hubdir");
+ std::fs::create_dir_all(&hubdir).unwrap();
+ std::fs::write(hubdir.join("manifest.json"), r#"{"corpus":"x"}"#).unwrap();
+ let err = resolve_pack_source(&hubdir.display().to_string()).unwrap_err();
+ assert!(err.contains("not a harvested pack"), "{err}");
+ }
+
+ #[test]
+ fn corpus_add_from_pack_materializes_re_adds_and_refuses_mixing() {
+ let home = tempfile::tempdir().unwrap();
+ let _h = code_home(home.path());
+ let pack = build_demo_pack(home.path());
+ let corpus = home.path().join("corpora/demo");
+
+ let add = || run_corpus_add(&["--from".to_string(), pack.display().to_string()]);
+ let rc = add();
+ assert_eq!(rc, 0);
+
+ // records are partitioned by WINNING source: a holds X1 (merged with
+ // b's alias) and X3; b won nothing so it has no directory at all
+ let a = records_lines(&corpus.join("a/records.jsonl"));
+ assert_eq!(a.len(), 2);
+ assert_eq!(a[0]["id"], json!("X1"));
+ assert_eq!(a[0]["sources"], json!(["a", "b"]), "alias merge survived");
+ assert_eq!(a[1]["id"], json!("X3"));
+ assert!(!corpus.join("b").exists(), "no b-won records, no b dir");
+
+ // the manifest: kind + pseudo-repos with the pack's source licences
+ let m = manifest::read_corpus_manifest(&corpus.join("corpus.json")).unwrap();
+ assert_eq!(m.kind.as_deref(), Some("harvested"));
+ assert_eq!(m.repos.len(), 2);
+ assert_eq!(m.repos[0].repo, "a");
+ assert_eq!(m.repos[0].licence, "CC0-1.0");
+ assert_eq!(m.repos[0].files, Some(2));
+ assert_eq!(m.repos[1].repo, "b");
+ assert_eq!(m.repos[1].files, Some(0));
+
+ // THE integration pin: xerj code's per-hit licence lookups key on the
+ // first locator segment, which is the slug dir — licence_map must see
+ // exactly what a cloned repo would have given it
+ let lic = manifest::licence_map(home.path(), "demo");
+ assert_eq!(lic.get("a").map(String::as_str), Some("CC0-1.0"));
+ assert_eq!(lic.get("b").map(String::as_str), Some("CC-BY-4.0"));
+
+ // re-add: refresh, never duplicate — same pack, same line counts
+ assert_eq!(add(), 0);
+ assert_eq!(records_lines(&corpus.join("a/records.jsonl")).len(), 2);
+
+ // a git-shaped corpus already owns the name → refused, nothing cloned
+ std::fs::write(
+ corpus.join("corpus.json"),
+ r#"{"corpus":"demo","repos":[]}"#,
+ )
+ .unwrap();
+ assert_eq!(add(), 2);
+ }
+
+ #[test]
+ fn git_arm_refuses_to_clone_onto_a_harvested_name() {
+ let home = tempfile::tempdir().unwrap();
+ let corpus = home.path().join("corpora/occupied");
+ std::fs::create_dir_all(&corpus).unwrap();
+ // harvested-kind marker: the git arm must refuse BEFORE cloning
+ manifest::write_corpus_manifest_kind(
+ &corpus.join("corpus.json"),
+ "occupied",
+ Some("harvested"),
+ "t",
+ &[manifest::ManifestRepo {
+ repo: "a".into(),
+ url: "u".into(),
+ licence: "CC0-1.0".into(),
+ sha: String::new(),
+ files: None,
+ bytes: None,
+ review: None,
+ }],
+ );
+ let _h = code_home(home.path());
+ let rc = run_corpus_add(&[
+ "occupied".to_string(),
+ "https://github.com/xerj-org/xerj".to_string(),
+ ]);
+ assert_eq!(rc, 2);
+ assert!(!corpus.join("xerj").exists(), "no clone happened");
+ }
+
+ #[test]
+ fn a_pack_zip_stages_and_materializes() {
+ let home = tempfile::tempdir().unwrap();
+ let _h = code_home(home.path());
+ let pack = build_demo_pack(home.path());
+
+ // zip the pack dir the way a release artifact would
+ let zip_path = home.path().join("demo-pack.zip");
+ {
+ use std::io::Write;
+ let f = std::fs::File::create(&zip_path).unwrap();
+ let mut z = zip::ZipWriter::new(f);
+ let opts: zip::write::SimpleFileOptions = zip::write::SimpleFileOptions::default();
+ fn add(
+ z: &mut zip::ZipWriter<std::fs::File>,
+ base: &Path,
+ rel: &Path,
+ opts: zip::write::SimpleFileOptions,
+ ) {
+ if rel.is_dir() {
+ if let Ok(entries) = std::fs::read_dir(rel) {
+ for e in entries.flatten() {
+ add(z, base, &e.path(), opts);
+ }
+ }
+ return;
+ }
+ let name = rel
+ .strip_prefix(base)
+ .unwrap()
+ .to_string_lossy()
+ .replace('\\', "/");
+ z.start_file(name, opts).unwrap();
+ z.write_all(&std::fs::read(rel).unwrap()).unwrap();
+ }
+ add(&mut z, &pack, &pack, opts);
+ z.finish().unwrap();
+ }
+
+ let corpus = home.path().join("corpora/demo");
+ let rc = run_corpus_add(&["--from".to_string(), zip_path.display().to_string()]);
+ assert_eq!(rc, 0);
+ assert_eq!(records_lines(&corpus.join("a/records.jsonl")).len(), 2);
+ assert_eq!(
+ manifest::read_corpus_manifest(&corpus.join("corpus.json"))
+ .unwrap()
+ .kind
+ .as_deref(),
+ Some("harvested")
+ );
+
+ // and a non-pack zip fails loudly instead of materializing noise
+ let junk = home.path().join("junk.zip");
+ std::fs::write(&junk, b"definitely not a zip").unwrap();
+ let rc = run_corpus_add(&["--from".to_string(), junk.display().to_string()]);
+ assert_eq!(rc, 2);
+ assert!(!home.path().join("corpora/junk").exists());
+ }
}
diff --git a/engine/crates/xerj-common/src/xccode/manifest.rs b/engine/crates/xerj-common/src/xccode/manifest.rs
index f91e3b715..620f7f757 100644
--- a/engine/crates/xerj-common/src/xccode/manifest.rs
+++ b/engine/crates/xerj-common/src/xccode/manifest.rs
@@ -40,6 +40,11 @@ pub struct ManifestRepo {
pub struct CorpusManifest {
#[serde(default)]
pub corpus: String,
+ /// `"harvested"` for corpora materialized from a pack (`corpus add --from
+ /// <pack>`); absent for cloned-repo corpora. Readers must treat absent as
+ /// the repo shape — every historical manifest has no `kind`.
+ #[serde(default)]
+ pub kind: Option<String>,
#[serde(default)]
pub cloned_at: Option<String>,
#[serde(default)]
@@ -103,8 +108,27 @@ fn entry_json(repo: &ManifestRepo) -> String {
/// Atomic (tmp + rename): a half-written manifest describes a checkout that
/// does not exist, and `xerj corpus list` reads these.
pub fn write_corpus_manifest(path: &Path, corpus: &str, cloned_at: &str, repos: &[ManifestRepo]) {
+ write_corpus_manifest_kind(path, corpus, None, cloned_at, repos)
+}
+
+/// [`write_corpus_manifest`] with an optional `kind`. `None` emits byte-for-byte
+/// what the pinned format has always been — a git corpus's manifest must not
+/// churn because a second kind of corpus now exists. `Some("harvested")`
+/// inserts `"kind":"harvested"` directly after `"corpus"`; only packs' corpora
+/// carry it, and `add` refuses to mix the two kinds under one name.
+pub fn write_corpus_manifest_kind(
+ path: &Path,
+ corpus: &str,
+ kind: Option<&str>,
+ cloned_at: &str,
+ repos: &[ManifestRepo],
+) {
+ let kind_json = match kind {
+ Some(k) => format!(",\"kind\":{}", Value::String(k.to_string())),
+ None => String::new(),
+ };
let mut body = format!(
- "{{\"corpus\":{},\"cloned_at\":{},\"repos\":[\n",
+ "{{\"corpus\":{}{kind_json},\"cloned_at\":{},\"repos\":[\n",
Value::String(corpus.to_string()),
Value::String(cloned_at.to_string())
);
@@ -229,6 +253,39 @@ mod tests {
assert_eq!(back.corpus, "kv");
}
+ #[test]
+ fn harvested_kind_emits_after_corpus_and_reads_back() {
+ let dir = tmp();
+ let path = dir.join("corpus.json");
+ let repos = vec![ManifestRepo {
+ repo: "rustsec".into(),
+ url: String::new(),
+ licence: "CC0-1.0".into(),
+ sha: String::new(),
+ files: Some(2),
+ bytes: Some(512),
+ review: None,
+ }];
+ write_corpus_manifest_kind(&path, "rust-vulns", Some("harvested"), "t", &repos);
+ let text = std::fs::read_to_string(&path).unwrap();
+ assert!(
+ text.starts_with("{\"corpus\":\"rust-vulns\",\"kind\":\"harvested\",\"cloned_at\":"),
+ "{text}"
+ );
+ let back = read_corpus_manifest(&path).unwrap();
+ assert_eq!(back.kind.as_deref(), Some("harvested"));
+ assert_eq!(back.repos[0].repo, "rustsec");
+
+ // and the pinned git shape is UNCHANGED by the extension
+ write_corpus_manifest(&path, "kv", "t", &repos);
+ let text = std::fs::read_to_string(&path).unwrap();
+ assert!(
+ text.starts_with("{\"corpus\":\"kv\",\"cloned_at\":"),
+ "{text}"
+ );
+ assert!(read_corpus_manifest(&path).unwrap().kind.is_none());
+ }
+
#[test]
fn licence_map_comes_from_the_record_not_the_prose() {
let dir = tmp();