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.

Preserve ambiguous clone state and stage new corpus checkouts

xerj-org3ca7e392bc84
diff --cc CHANGELOG.md
index cca1ef8bf,86c46a9ac..618ebf467
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -7,86 -7,17 +7,90 @@@ and this project adheres to [Semantic V
## [Unreleased]
+### Added
+
+- Corpus Hub manifest `paths` entries may name regular files as well as
+ directories (#2486). A file selection checks out that file without its
+ siblings; symlinks and submodules are refused.
+
+- MCP `xerj_status` reports node reachability, cluster health and visible
+ indices before a search. It distinguishes a missing autoindex catalog from
+ other indexed data and preserves failed or malformed probes as errors
+ rather than reporting a successful empty node (#2515).
+
+- Empty autoindex maps now explain that managed corpus slugs and autoindex
+ dataset/index names belong to separate discovery surfaces. CLI diagnostics,
+ MCP empty responses and the `xerj_map` description point to corpus discovery
+ without claiming a corpus exists. Missing catalogs remain errors; auth
+ refusals and successful dataset maps retain their behavior (#2412).
+
+- Public Agent Skills Discovery v0.2.0 index and a documentation-routing skill
+ at `/.well-known/agent-skills/`. The index is generated from the published
+ skill's metadata and exact-byte SHA-256, with a CI drift check.
+
### Fixed
-- Re-running `xerj corpus add` after a clone was stopped partway (an agent's
- tool timeout) now finishes that clone instead of recording it as
- `[skip] already cloned` with no files and `sha: unknown` (#2453). A clone
- stopped before its first checkout is cloned again (`[reclone]`); one
- stopped while writing files is restored in place (`[repair]`), offline
- unless it is pinned. A leftover `.git/index.lock` (a hard kill leaves
- one), or a checkout git cannot read, fails the run with what to do and
- keeps the checkout. A second `corpus add` on the same corpus is refused
- while one runs.
++- Corpus cloning validates existing checkouts and serializes writers (#2453).
++ New checkouts are staged before publication. Ambiguous existing directories
++ are preserved for recovery rather than deleted or reset automatically.
++
+- MCP `xerj_search` advertises plain text in `query` and structured clauses
+ in `query_dsl`. Legacy object-valued `query` and omitted-query browsing
+ remain supported; conflicting fields fail before HTTP requests (#2549).
+- Search payloads and batch retrieval default to 8,000 UAX #29 words when
+ `max_tokens` is absent or null (#2491). This is not a byte or model-token
+ cap. Explicit larger budgets remain available; errors and mandatory
+ search staleness hints stay outside the payload budget.
+- GitHub field-report submission uses the supported explicit-repository
+ `gh repo fork --clone=false` invocation and adds the fork remote itself
+ (#2596). The rollback test now verifies that the report was committed
+ before a failed push, rather than passing after an earlier fork failure.
+- Local admin-key discovery reports the source of the selected key and warns
+ when its directory is outside the working tree (#2578). Packaged installs
+ have their own provenance, and MCP guidance names `XERJ_AUTH`. Discovery
+ priority and explicit credential overrides are unchanged.
+
+- SQL source extraction no longer slices statement heads inside a UTF-8
+ character, so unrecognized CJK statement/comment heads do not panic (#2547).
+- Short Markdown files with YAML frontmatter retain their prose body even
+ when bullets or `Key: value` lines also parse as YAML (#2447). Existing
+ frontmatter-title behavior and structured CSV/JSON body detection remain.
+- Empty files keep separate inventory identities instead of being reported
+ as content duplicates of unrelated paths (#2449). Non-empty byte-identical
+ files still deduplicate.
+- A search with both `query` and a top-level `knn` returns `size` hits, not
+ `k` (#2561). The page was widened to `k`, so `size: 5, k: 20` returned
+ 20 hits. `k` still sets how many nearest neighbours join the candidate
+ set, and `from`/`size` page through the union, as in Elasticsearch.
+- Index deletion no longer waits for unrelated index statistics while
+ resolving its selectors. Index listings and health checks also release
+ their index-map locks before awaiting statistics, so a stalled schema
+ update does not hold those locks against DELETE (part of #2405; extracted
+ from #2489). Merge/flush cancellation and the process memory cap remain
+ separate follow-ups.
+- `xerj autoindex` compresses per-file phase-B stages with zstd level 1 and
+ uses temporary files cleaned up by the operating system when the client
+ exits (#2493, part of #2427). It finishes buffered compression before
+ deleting previous records, so a stage finalization error preserves the old
+ records and an ordinary resume can complete the replacement. Compression
+ savings depend on the data; this does not impose a disk or server-memory cap.
+- `autoindex` bulk back-pressure patience is now measured since the last
+ progress, not since the first round. A window the server drains a few
+ records at a time (per-item 429 `resource_exhausted` on an embedding
+ deadline or admission refusal) used to abort with `bulk backend failed`
+ once the rounds together passed the 600 s `THROTTLE_PATIENCE`, even though
+ every round settled records. Each round that settles at least one item now
+ restarts the patience clock and the backoff; rounds that settle nothing
+ still count, so a server that answers 429 forever fails at the same limits
+ as before.
+- `xerj autoindex` titles a prose file that opens with YAML frontmatter from
+ its `title:` key, or from the first line after the closing `---` when there
+ is none (#2556). Every such file (Jekyll, Hugo, Obsidian) used to be titled
+ `---`, its opening fence. A leading `---` block that is not parseable
+ frontmatter (unclosed, not a YAML mapping, over 64 KiB) takes the first line
+ that is not a bare `---`; the body, the frontmatter text in it and
+ `start_line` are unchanged. An unchanged file is not re-extracted, so re-index
+ with `xerj autoindex --fresh` to retitle documents already in an index.
## [1.0.0-rc.100] - 2026-10-26
diff --cc engine/crates/xerj-autoindex/src/xc.rs
index 8371472b6,bac88def8..fc1c248fe
--- a/engine/crates/xerj-autoindex/src/xc.rs
+++ b/engine/crates/xerj-autoindex/src/xc.rs
@@@ -494,20 -486,6 +494,13 @@@ pub(crate) fn git(dir: Option<&Path>, a
))
}
- /// Whether an existing directory can be reused as a clone of its remote.
- ///
- /// `.git` appears before the first object lands, so its presence says nothing
- /// about whether the clone finished: a killed `git clone` leaves a repository
- /// with no HEAD and no files. HEAD names a commit only once the fetch and the
- /// checkout got that far (#2453).
++/// `.git` alone does not establish a completed checkout (#2453). Check the
++/// readable commit, the Git-owned index location (also for linked worktrees),
++/// and a pending index lock before reusing an existing checkout.
+fn existing_checkout_is_complete(target: &Path) -> bool {
- if !target.join(".git").exists() {
- return false;
- }
- git(Some(target), &["rev-parse", "--verify", "--quiet", "HEAD"])
- .is_ok_and(|(rc, out)| rc == 0 && !out.is_empty())
++ target.join(".git").exists() && unfinished_clone(target).is_none()
+}
+
/// How much of git's own stdout/stderr a fetch failure keeps. A TLS
/// intercept or a rejected pin is a paragraph; the rest of the bail stays
/// one line an agent can read.
@@@ -786,6 -720,94 +779,143 @@@ fn paths_note(paths: &[String]) -> Stri
}
}
-/// What a clone killed partway left behind (#2453).
++/// Observable incomplete checkout state, never proof that files are disposable.
++#[derive(Debug)]
+ enum Unfinished {
- /// Killed in `git init` (no `.git/objects` yet) or before its first
- /// checkout (no commit at HEAD, no index): nothing usable.
+ NoCommit,
- /// HEAD names a commit but there is no index: the files were not all
- /// written.
+ Checkout,
- /// `.git/index.lock` is left, by a git that was stopped or is running.
+ Locked,
- /// git cannot read the repository; git's message.
+ Unreadable(String),
+ }
+
-/// Whether a checkout with a `.git` directory is a finished clone (`None`).
-/// A clone killed before its first checkout has no commit at HEAD and no
-/// index; one killed while writing files has a commit and no index, or
-/// `.git/index.lock` if git had no time to remove it. A checkout that has
-/// an index but whose HEAD does not resolve to a commit (a lost object, a
-/// broken ref) finished once and is not ours to replace. `--git-dir` stops
-/// git from walking up to an enclosing repository.
+ fn unfinished_clone(target: &Path) -> Option<Unfinished> {
- // `git init` stopped before it made `.git/objects`: nothing was fetched,
- // and git does not take the folder for a repository at all.
- if !target.join(".git/objects").is_dir() {
- return Some(Unfinished::NoCommit);
- }
- if target.join(".git/index.lock").exists() {
- return Some(Unfinished::Locked);
- }
- let has_index = target.join(".git/index").exists();
- let rev = |spec: &str| {
- git(
- Some(target),
- &["--git-dir=.git", "rev-parse", "--verify", "--quiet", spec],
- )
- };
+ let unreadable = |out: &str| {
+ let why = out.lines().next().unwrap_or("").trim();
+ Some(Unfinished::Unreadable(if why.is_empty() {
+ "HEAD names no readable commit".to_string()
+ } else {
+ why.chars().take(200).collect()
+ }))
+ };
- // `HEAD` alone reads the ref, not the object: exit 1 is an unborn HEAD.
++ // --git-dir prevents accidentally resolving an enclosing repository;
++ // --git-path handles linked worktrees and their separate index correctly.
++ let index = match git_stdout(
++ target,
++ &["--git-dir=.git", "rev-parse", "--git-path", "index"],
++ ) {
++ Ok((0, out, _)) if !out.is_empty() => target.join(out),
++ Ok((_, _, err)) => return unreadable(&err),
++ Err(e) => return unreadable(&e.to_string()),
++ };
++ if index.with_file_name("index.lock").exists() {
++ return Some(Unfinished::Locked);
++ }
++ let rev = |spec: &str| {
++ git_stdout(
++ target,
++ &["--git-dir=.git", "rev-parse", "--verify", "--quiet", spec],
++ )
++ };
+ match rev("HEAD") {
- Ok((0, _)) => {}
- Ok((1, _)) if !has_index => return Some(Unfinished::NoCommit),
- Ok((_, out)) => return unreadable(&out),
- Err(e) => return unreadable(&format!("{e:#}")),
++ Ok((0, _, _)) => {}
++ Ok((1, _, _)) => return Some(Unfinished::NoCommit),
++ Ok((_, _, err)) => return unreadable(&err),
++ Err(e) => return unreadable(&e.to_string()),
+ }
+ match rev("HEAD^{commit}") {
- Ok((0, _)) => {}
- Ok((_, out)) => return unreadable(&out),
- Err(e) => return unreadable(&format!("{e:#}")),
- }
- if !has_index {
- return Some(Unfinished::Checkout);
++ Ok((0, _, _)) => {}
++ Ok((_, _, err)) => return unreadable(&err),
++ Err(e) => return unreadable(&e.to_string()),
++ }
++ if !index.is_file() {
++ // A committed empty tree legitimately needs no worktree index on
++ // some Git versions. A nonempty tree without an index is ambiguous.
++ let empty_tree = matches!(
++ git_stdout(target, &["--git-dir=.git", "ls-tree", "--name-only", "HEAD"]),
++ Ok((0, out, _)) if out.is_empty()
++ );
++ if !empty_tree {
++ return Some(Unfinished::Checkout);
++ }
+ }
+ None
+ }
+
++fn unfinished_checkout_message(target: &Path, state: &Unfinished) -> String {
++ let why = match state {
++ Unfinished::NoCommit => "HEAD has no commit".to_string(),
++ Unfinished::Checkout => "the Git index is missing".to_string(),
++ Unfinished::Locked => {
++ "Git index.lock exists; a Git operation may still be running".to_string()
++ }
++ Unfinished::Unreadable(why) => format!("Git cannot read the checkout: {why}"),
++ };
++ format!(
++ "{} is not a reusable checkout ({why}); kept its files unchanged. \
++ Wait for any active Git operation to finish. If this checkout is incomplete, \
++ move the directory to an unused backup location, then rerun this corpus add command",
++ target.display()
++ )
++}
++
++/// Publish only a successfully completed new checkout. The caller holds the
++/// corpus lock; the destination is under the operator-owned corpus directory.
++/// TemporaryDir cleans this attempt's private stage on ordinary failure. A
++/// process kill may leave a hidden stage, but never an apparent final clone.
++fn stage_new_checkout(target: &Path, clone: impl FnOnce(&Path) -> Result<()>) -> Result<()> {
++ let absent = || -> Result<()> {
++ match std::fs::symlink_metadata(target) {
++ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
++ Err(e) => Err(e).with_context(|| format!("cannot inspect {}", target.display())),
++ Ok(_) => anyhow::bail!("{} already exists; kept it unchanged. Move it to an unused backup location before retrying", target.display()),
++ }
++ };
++ absent()?;
++ let parent = target
++ .parent()
++ .context("checkout has no parent directory")?;
++ std::fs::create_dir_all(parent)?;
++ let stage = tempfile::Builder::new()
++ .prefix(".xerj-clone-")
++ .tempdir_in(parent)?;
++ let checkout = stage.path().join("checkout");
++ clone(&checkout)?;
++ if !existing_checkout_is_complete(&checkout) {
++ anyhow::bail!("Git did not produce a complete checkout; final directory was not published");
++ }
++ // An external writer may have created a destination while Git ran. Do
++ // not replace it. Cooperating corpus writers are serialized by the lock.
++ absent()?;
++ std::fs::rename(&checkout, target)
++ .with_context(|| format!("cannot publish checkout at {}", target.display()))?;
++ Ok(())
++}
++
+ /// One `corpus add` per corpus at a time (#2453): a second run would
+ /// otherwise take the first one's clone in progress for an unfinished one.
+ /// Released when the returned file is dropped.
+ fn lock_corpus_add(root: &Path, name: &str) -> Result<std::fs::File> {
+ let dir = root.join("locks");
+ std::fs::create_dir_all(&dir).with_context(|| format!("cannot create {}", dir.display()))?;
+ let path = dir.join(format!("corpus-add-{name}.lock"));
+ let file = std::fs::OpenOptions::new()
+ .create(true)
+ .truncate(false)
+ .read(true)
+ .write(true)
+ .open(&path)
+ .with_context(|| format!("cannot open {}", path.display()))?;
+ match fs2::FileExt::try_lock_exclusive(&file) {
+ Ok(()) => Ok(file),
+ Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => anyhow::bail!(
+ "corpus '{name}' is being written by another `xerj corpus add` (lock: {}). \
+ Run this again when it finishes.",
+ path.display()
+ ),
+ Err(e) => Err(anyhow::Error::new(e).context(format!("cannot lock {}", path.display()))),
+ }
+ }
+
fn dir_stats(target: &Path) -> (String, u64, u64) {
let sha = git(Some(target), &["rev-parse", "HEAD"])
.ok()
@@@ -1281,6 -1310,57 +1418,23 @@@ fn run_corpus_add(args: &[String]) -> i
},
);
};
- // #2453: a clone killed partway (an agent's tool timeout) leaves a
- // `.git` behind, and trusting it records an empty or partial repo.
- // Killed before its first checkout there is nothing to keep, so it is
- // cloned again; killed while writing files, everything is on disk
- // and the files are restored in place, offline. A leftover
- // `.git/index.lock` may belong to a git that is still running, and a
- // repository git cannot read is not provably ours to replace: both
- // fail with what to do, and the checkout is kept.
- let mut restore_pin = false;
- if target.join(".git").is_dir() {
- let fail = match unfinished_clone(&target) {
- None => None,
- Some(Unfinished::NoCommit) => {
- println!(" [reclone] {repo_name}: no commit yet (clone stopped early, or the remote is empty); cloning again");
- std::fs::remove_dir_all(&target)
- .err()
- .map(|e| format!("cannot remove {}: {e}", target.display()))
- }
- Some(Unfinished::Checkout) => {
- println!(" [repair] {repo_name}: unfinished checkout (no .git/index); restoring files");
- if !sha.is_empty() {
- restore_pin = true;
- None
- } else if matches!(
- git(Some(&target), &["reset", "--hard", "--quiet", "HEAD"]),
- Ok((0, _))
- ) {
- None
- } else {
- Some(format!(
- "could not restore files; kept {}",
- target.display()
- ))
- }
- }
- Some(Unfinished::Locked) => Some(format!(
- "{} is left by a git that was stopped or is still running; \
- if no git is running, delete it and run this again",
- target.join(".git/index.lock").display()
- )),
- Some(Unfinished::Unreadable(why)) => Some(format!(
- "git cannot read {} ({why}); remove it to clone again",
- target.display()
- )),
- };
- if let Some(e) = fail {
- eprintln!(" [FAIL] {repo_name}: {e}; continuing");
++ // Existing state may contain local edits, even without HEAD or an
++ // index. Neither condition authorizes deletion or reset --hard.
++ if std::fs::symlink_metadata(&target).is_ok_and(|m| m.file_type().is_symlink()) {
++ eprintln!(" [FAIL] {repo_name}: checkout path is a symlink; kept it unchanged");
++ skipped.push(repo_name);
++ continue;
++ }
++ if target.join(".git").exists() {
++ if let Some(state) = unfinished_clone(&target) {
++ eprintln!(
++ " [FAIL] {repo_name}: {}; continuing",
++ unfinished_checkout_message(&target, &state)
++ );
+ skipped.push(repo_name);
+ continue;
+ }
+ }
if target.join(".git").exists() && !sha.is_empty() {
let at = git(Some(&target), &["rev-parse", "HEAD"])
.ok()
@@@ -1347,43 -1427,32 +1501,29 @@@
);
continue;
}
- // #2453: a killed clone leaves `.git` behind with no HEAD, so the
- // directory looked cloned forever and `corpus add` skipped it. The
- // check above says the wreck is not reusable; clear it and clone.
- if target.join(".git").exists() {
- println!(" [redo] {repo_name}: clearing an incomplete clone and re-cloning");
- if let Err(e) = std::fs::remove_dir_all(&target) {
- eprintln!(" [FAIL] {repo_name}: cannot clear the incomplete clone: {e}");
- skipped.push(repo_name);
- continue;
- }
- }
println!(" [clone] {repo_name}");
-- if sha.is_empty() {
-- if let Some(parent) = target.parent() {
-- let _ = std::fs::create_dir_all(parent);
-- }
-- // Never a shell string: the URL and target are single argv
-- // elements, so a hostile URL cannot smuggle flags.
-- let target_s = target.to_string_lossy().to_string();
-- let (rc, _) = git(None, &["clone", "--depth", "1", "--quiet", &url, &target_s])
-- .unwrap_or((-1, String::new()));
-- if rc != 0 {
-- let (rc2, _) = git(None, &["clone", "--depth", "1", &url, &target_s])
-- .unwrap_or((-1, String::new()));
-- if rc2 != 0 {
-- eprintln!(" [FAIL] {repo_name} — could not clone; continuing");
-- skipped.push(repo_name);
-- continue;
++ let cloned = stage_new_checkout(&target, |checkout| {
++ if sha.is_empty() {
++ let target_s = checkout.to_string_lossy().to_string();
++ let (rc, output) = git(None, &["clone", "--depth", "1", "--", &url, &target_s])?;
++ if rc != 0 {
++ let shown: String = output
++ .replace(&url, "[source]")
++ .chars()
++ .take(GIT_FETCH_OUTPUT_CAP)
++ .collect();
++ anyhow::bail!("git clone failed (exit {rc}): {shown}");
}
++ Ok(())
++ } else {
++ println!(" [pin] {repo_name} -> {}{note}", &sha[..12.min(sha.len())]);
++ checkout_at_sha_paths(checkout, &url, &sha, &paths)
}
-- } else {
-- println!(" [pin] {repo_name} -> {}{note}", &sha[..12.min(sha.len())]);
-- if let Err(e) = checkout_at_sha_paths(&target, &url, &sha, &paths) {
-- eprintln!(" [FAIL] {repo_name}: {e:#}; continuing");
-- skipped.push(repo_name);
-- continue;
-- }
++ });
++ if let Err(e) = cloned {
++ eprintln!(" [FAIL] {repo_name}: {e:#}; continuing");
++ skipped.push(repo_name);
++ continue;
}
carry_ignore(&target);
record(
@@@ -5515,6 -5550,334 +5662,362 @@@ precedence = ["a", "b"
sha
}
+ // ── corpus add over a clone killed partway (#2453) ─────────────────────
+
+ /// Leaves `checkout` as a `git checkout` stopped partway does: no index,
+ /// with `missing` not yet written. (SIGTERM lets git remove its
+ /// `.git/index.lock`; SIGKILL leaves it, see the refusal test.)
+ fn kill_mid_checkout(checkout: &Path, missing: &str) {
+ std::fs::remove_file(checkout.join(missing)).unwrap();
+ std::fs::remove_file(checkout.join(".git/index")).unwrap();
+ }
+
- /// `git clone` killed while fetching leaves a `.git` with no commit and
- /// no files. A re-run clones it again instead of recording an empty repo
- /// as "already cloned".
++ /// An unborn checkout is preserved, then a move-aside recovery succeeds.
+ #[test]
- fn corpus_add_reclones_a_clone_killed_before_its_first_commit() {
++ fn corpus_add_preserves_an_unborn_checkout_before_manual_recovery() {
+ let home = tempfile::tempdir().unwrap();
+ let _h = code_home(home.path());
+ let origin = home.path().join("widget");
+ init_committed_repo(&origin, &[("keep.txt", "tracked\n")]);
+ let clone = home.path().join("corpora/partial/widget");
+ std::fs::create_dir_all(&clone).unwrap();
+ let (rc, out) = git(Some(&clone), &["init", "--quiet"]).unwrap();
+ assert_eq!(rc, 0, "git init: {out}");
+
++ assert_eq!(
++ run_corpus_add(&["partial".into(), origin.display().to_string()]),
++ 1
++ );
++ let backup = preserve_incomplete_for_retry(&clone);
++ assert!(backup.join(".git/HEAD").is_file());
+ assert_eq!(
+ run_corpus_add(&["partial".into(), origin.display().to_string()]),
+ 0
+ );
+ assert_eq!(
+ std::fs::read_to_string(clone.join("keep.txt")).unwrap(),
+ "tracked\n"
+ );
+ let recorded =
+ manifest::read_corpus_manifest(&home.path().join("corpora/partial/corpus.json"))
+ .unwrap();
+ assert_eq!(recorded.repos[0].sha, head_sha(&origin));
+ assert_eq!(recorded.repos[0].files, Some(1));
+ }
+
- /// Killed inside `git init`, before `.git/objects` exists, git cannot
- /// read the folder at all; it is still a clone with nothing in it.
++ /// Missing object storage does not prove an existing directory is disposable.
+ #[test]
- fn corpus_add_reclones_a_clone_killed_during_git_init() {
++ fn corpus_add_preserves_a_checkout_without_git_objects() {
+ let home = tempfile::tempdir().unwrap();
+ let _h = code_home(home.path());
+ let origin = home.path().join("widget");
+ init_committed_repo(&origin, &[("keep.txt", "tracked\n")]);
+ let clone = home.path().join("corpora/partial/widget");
+ std::fs::create_dir_all(&clone).unwrap();
+ let (rc, out) = git(Some(&clone), &["init", "--quiet"]).unwrap();
+ assert_eq!(rc, 0, "git init: {out}");
+ std::fs::remove_dir_all(clone.join(".git/objects")).unwrap();
+ std::fs::write(clone.join(".git/config.lock"), "").unwrap();
+
++ assert_eq!(
++ run_corpus_add(&["partial".into(), origin.display().to_string()]),
++ 1
++ );
++ let backup = preserve_incomplete_for_retry(&clone);
++ assert!(backup.join(".git/HEAD").is_file());
+ assert_eq!(
+ run_corpus_add(&["partial".into(), origin.display().to_string()]),
+ 0
+ );
+ assert_eq!(
+ std::fs::read_to_string(clone.join("keep.txt")).unwrap(),
+ "tracked\n"
+ );
+ }
+
- /// Killed while checking out, the clone already holds every object, so
- /// its files are restored in place without the network: the origin is
- /// gone before the re-run. A finished clone is still left as it is.
++ /// A finished checkout is reused, but a missing index is preserved and
++ /// refused even when the remote is offline. Recovery keeps local notes.
+ #[test]
- fn corpus_add_restores_a_clone_killed_mid_checkout_offline() {
++ fn corpus_add_preserves_an_ambiguous_checkout_when_remote_is_offline() {
+ let home = tempfile::tempdir().unwrap();
+ let _h = code_home(home.path());
+ let origin = home.path().join("widget");
+ init_committed_repo(&origin, &[("a.txt", "a\n"), ("b.txt", "b\n")]);
+ let add = || run_corpus_add(&["mid".into(), origin.display().to_string()]);
+ let clone = home.path().join("corpora/mid/widget");
+ assert_eq!(add(), 0);
+
+ std::fs::write(clone.join("marker"), "kept\n").unwrap();
+ assert_eq!(add(), 0);
+ assert!(
+ clone.join("marker").exists(),
+ "a finished clone is not touched"
+ );
+
+ kill_mid_checkout(&clone, "b.txt");
+ std::fs::rename(&origin, home.path().join("gone")).unwrap();
++ assert_eq!(
++ add(),
++ 1,
++ "missing index is ambiguous even when the remote is unavailable"
++ );
++ assert!(!clone.join("b.txt").exists());
++ assert_eq!(
++ std::fs::read_to_string(clone.join("marker")).unwrap(),
++ "kept\n"
++ );
++ let backup = preserve_incomplete_for_retry(&clone);
++ std::fs::rename(home.path().join("gone"), &origin).unwrap();
+ assert_eq!(add(), 0);
+ assert_eq!(std::fs::read_to_string(clone.join("b.txt")).unwrap(), "b\n");
- assert!(clone.join("marker").exists(), "repaired, not cloned again");
++ assert!(
++ backup.join("marker").exists(),
++ "local files remain in the saved directory"
++ );
+ let recorded =
+ manifest::read_corpus_manifest(&home.path().join("corpora/mid/corpus.json")).unwrap();
- // a.txt, b.txt and the marker: every file on disk is counted.
- assert_eq!(recorded.repos[0].files, Some(3));
++ // Only the committed a.txt and b.txt are in the new checkout.
++ assert_eq!(recorded.repos[0].files, Some(2));
+ }
+
+ /// A leftover `.git/index.lock` may belong to a git that is still
- /// running, so the run fails with what to do and touches nothing. Once
- /// the lock is removed, the next run restores the files.
++ /// running, so the run fails and touches nothing. Removing a lock alone
++ /// does not authorize overwriting files when the index is still absent.
+ #[test]
+ fn corpus_add_refuses_a_checkout_left_with_index_lock() {
+ let home = tempfile::tempdir().unwrap();
+ let _h = code_home(home.path());
+ let origin = home.path().join("widget");
+ init_committed_repo(&origin, &[("a.txt", "a\n"), ("b.txt", "b\n")]);
+ let add = || run_corpus_add(&["locked".into(), origin.display().to_string()]);
+ let clone = home.path().join("corpora/locked/widget");
+ assert_eq!(add(), 0);
+
+ kill_mid_checkout(&clone, "b.txt");
+ std::fs::write(clone.join(".git/index.lock"), "").unwrap();
+ assert_eq!(add(), 1);
+ assert!(
+ clone.join(".git/index.lock").exists(),
+ "the lock is not deleted"
+ );
+ assert!(!clone.join("b.txt").exists());
+
+ std::fs::remove_file(clone.join(".git/index.lock")).unwrap();
++ assert_eq!(
++ add(),
++ 1,
++ "removing a lock does not authorize resetting local files"
++ );
++ let backup = preserve_incomplete_for_retry(&clone);
++ assert!(backup.join("a.txt").exists());
+ assert_eq!(add(), 0);
+ assert_eq!(std::fs::read_to_string(clone.join("b.txt")).unwrap(), "b\n");
+ }
+
+ /// When the files cannot be restored the run fails and the checkout,
+ /// with every object in it, is kept for the next try.
+ #[cfg(unix)]
+ #[test]
+ fn corpus_add_keeps_a_checkout_it_cannot_restore() {
- use std::os::unix::fs::PermissionsExt;
+ let home = tempfile::tempdir().unwrap();
+ let _h = code_home(home.path());
+ let origin = home.path().join("widget");
+ init_committed_repo(&origin, &[("a.txt", "a\n"), ("b.txt", "b\n")]);
+ let add = || run_corpus_add(&["stuck".into(), origin.display().to_string()]);
+ let clone = home.path().join("corpora/stuck/widget");
+ assert_eq!(add(), 0);
-
+ kill_mid_checkout(&clone, "b.txt");
- let mode = |m| std::fs::set_permissions(&clone, std::fs::Permissions::from_mode(m));
- mode(0o555).unwrap();
- // root ignores the mode; there is no failure to provoke.
- let read_only = std::fs::write(clone.join("probe"), "").is_err();
- let rc = add();
- mode(0o755).unwrap();
- if read_only {
- assert_eq!(rc, 1);
- assert!(clone.join(".git").is_dir(), "the checkout is kept");
- assert!(clone.join("a.txt").exists());
- }
++ assert_eq!(add(), 1);
++ assert!(clone.join(".git").is_dir(), "the checkout is kept");
++ assert_eq!(std::fs::read_to_string(clone.join("a.txt")).unwrap(), "a\n");
++ assert!(!clone.join("b.txt").exists());
+ }
+
- /// A pinned checkout stopped before its first checkout finished has no
- /// commit at HEAD and no index. It is now fetched and checked out again
- /// instead of recorded as it is.
++ /// A pinned checkout without HEAD is kept, not silently republished.
++ /// Moving it aside permits a fresh checkout at the declared pin.
+ #[test]
- fn corpus_add_from_reclones_a_pin_killed_mid_checkout() {
++ fn corpus_add_from_preserves_a_pin_without_head_before_recovery() {
+ let home = tempfile::tempdir().unwrap();
+ let _h = code_home(home.path());
+ let origin = home.path().join("origin");
+ init_committed_repo(
+ &origin,
+ &[("LICENSE", "bsd\n"), ("src/a.rs", "fn a() {}\n")],
+ );
+ let manifest = home.path().join("pin.json");
+ write_pin(
+ &manifest,
+ &origin.display().to_string(),
+ &head_sha(&origin),
+ None,
+ );
+ let add = || run_corpus_add(&["--from".into(), manifest.display().to_string()]);
+ let checkout = home.path().join("corpora/sparse-demo/vulndb");
+ assert_eq!(add(), 0);
+
+ kill_mid_checkout(&checkout, "src/a.rs");
+ std::fs::write(checkout.join(".git/HEAD"), "ref: refs/heads/unborn\n").unwrap();
++ assert_eq!(add(), 1);
++ assert!(checkout.join("LICENSE").is_file());
++ let backup = preserve_incomplete_for_retry(&checkout);
++ assert!(backup.join("LICENSE").is_file());
+ assert_eq!(add(), 0);
+ assert_eq!(
+ worktree_files(&checkout),
+ vec!["LICENSE".to_string(), "src/a.rs".to_string()]
+ );
+ assert!(!checkout.join(".git/index.lock").exists());
+ }
+
- /// HEAD at the pin with no index is checked out again, not reported as
- /// "already at" the sha with files missing.
++ /// HEAD at the pin does not make a missing index safe to reset.
+ #[test]
- fn corpus_add_from_restores_a_pin_left_without_an_index() {
++ fn corpus_add_from_preserves_a_pin_without_index_before_recovery() {
+ let home = tempfile::tempdir().unwrap();
+ let _h = code_home(home.path());
+ let origin = home.path().join("origin");
+ init_committed_repo(
+ &origin,
+ &[("LICENSE", "bsd\n"), ("src/a.rs", "fn a() {}\n")],
+ );
+ let manifest = home.path().join("pin.json");
+ write_pin(
+ &manifest,
+ &origin.display().to_string(),
+ &head_sha(&origin),
+ None,
+ );
+ let add = || run_corpus_add(&["--from".into(), manifest.display().to_string()]);
+ let checkout = home.path().join("corpora/sparse-demo/vulndb");
+ assert_eq!(add(), 0);
+
+ kill_mid_checkout(&checkout, "src/a.rs");
++ assert_eq!(add(), 1);
++ assert!(checkout.join("LICENSE").is_file());
++ let backup = preserve_incomplete_for_retry(&checkout);
++ assert!(backup.join("LICENSE").is_file());
+ assert_eq!(add(), 0);
+ assert_eq!(
+ worktree_files(&checkout),
+ vec!["LICENSE".to_string(), "src/a.rs".to_string()]
+ );
+ }
+
+ /// A checkout git cannot read at all (exit 128, not "no commit") is not
+ /// proof of a killed clone: the run fails and leaves it exactly as it is,
- /// instead of recording it as already cloned. Removing it, as the error
- /// says, lets the next run clone it.
++ /// instead of recording it as already cloned. Moving it aside, as the
++ /// diagnostic advises, permits a new clone while retaining local files.
+ #[test]
+ fn corpus_add_fails_on_a_checkout_git_cannot_read() {
+ let home = tempfile::tempdir().unwrap();
+ let _h = code_home(home.path());
+ let origin = home.path().join("widget");
+ init_committed_repo(&origin, &[("keep.txt", "tracked\n")]);
+ let add = || run_corpus_add(&["odd".into(), origin.display().to_string()]);
+ let clone = home.path().join("corpora/odd/widget");
+ assert_eq!(add(), 0);
+ std::fs::write(clone.join(".git/HEAD"), "garbage\n").unwrap();
+ std::fs::write(clone.join("marker"), "kept\n").unwrap();
+ assert_eq!(add(), 1);
+ assert!(
+ clone.join("marker").exists(),
+ "an unreadable checkout is not deleted"
+ );
+ assert_eq!(
+ std::fs::read_to_string(clone.join(".git/HEAD")).unwrap(),
+ "garbage\n"
+ );
+
- // The recovery the error names: remove it, and the next run clones.
- std::fs::remove_dir_all(&clone).unwrap();
++ // The recovery keeps the old directory and all local files.
++ let backup = preserve_incomplete_for_retry(&clone);
++ assert!(backup.join("marker").exists());
+ assert_eq!(add(), 0);
+ assert_eq!(
+ std::fs::read_to_string(clone.join("keep.txt")).unwrap(),
+ "tracked\n"
+ );
+ }
+
+ /// A finished clone that lost its HEAD commit object still has its
+ /// files and index: git cannot read it, so the run fails and keeps it
+ /// instead of deleting it as a clone that never got a commit.
+ #[test]
+ fn corpus_add_fails_on_a_clone_missing_its_head_commit() {
+ let home = tempfile::tempdir().unwrap();
+ let _h = code_home(home.path());
+ let origin = home.path().join("widget");
+ init_committed_repo(&origin, &[("keep.txt", "tracked\n")]);
+ let add = || run_corpus_add(&["lost".into(), origin.display().to_string()]);
+ let clone = home.path().join("corpora/lost/widget");
+ assert_eq!(add(), 0);
+ std::fs::remove_dir_all(clone.join(".git/objects")).unwrap();
+ std::fs::create_dir(clone.join(".git/objects")).unwrap();
+ assert_eq!(add(), 1);
+ assert_eq!(
+ std::fs::read_to_string(clone.join("keep.txt")).unwrap(),
+ "tracked\n"
+ );
+ }
+
+ /// A `.git` file (a linked worktree) has no `.git/index` of its own and
+ /// is never ours: it is left alone, not taken for an unfinished clone.
+ #[test]
+ fn corpus_add_leaves_a_linked_worktree_alone() {
+ let home = tempfile::tempdir().unwrap();
+ let _h = code_home(home.path());
+ let origin = home.path().join("widget");
+ init_committed_repo(&origin, &[("keep.txt", "tracked\n")]);
+ let clone = home.path().join("corpora/linked/widget");
+ let clone_s = clone.display().to_string();
+ let (rc, out) = git(Some(&origin), &["worktree", "add", "--quiet", &clone_s]).unwrap();
+ assert_eq!(rc, 0, "git worktree add: {out}");
+ std::fs::write(clone.join("keep.txt"), "edited\n").unwrap();
+
+ assert_eq!(
+ run_corpus_add(&["linked".into(), origin.display().to_string()]),
+ 0
+ );
+ assert_eq!(
+ std::fs::read_to_string(clone.join("keep.txt")).unwrap(),
+ "edited\n"
+ );
+ assert!(clone.join(".git").is_file());
+ }
+
+ /// A second `corpus add` of the same corpus refuses while the first holds
+ /// the lock, and touches nothing.
+ #[test]
+ fn corpus_add_refuses_while_another_run_holds_the_corpus() {
+ let home = tempfile::tempdir().unwrap();
+ let _h = code_home(home.path());
+ let origin = home.path().join("widget");
+ init_committed_repo(&origin, &[("keep.txt", "tracked\n")]);
+ let held = lock_corpus_add(home.path(), "busy").unwrap();
+ assert_eq!(
+ run_corpus_add(&["busy".into(), origin.display().to_string()]),
+ 1
+ );
+ assert!(!home.path().join("corpora/busy/widget").exists());
+ drop(held);
+ assert_eq!(
+ run_corpus_add(&["busy".into(), origin.display().to_string()]),
+ 0
+ );
+ }
+
+ /// `corpus add --from <pack>` takes the same lock.
+ #[test]
+ fn corpus_add_from_pack_refuses_while_another_run_holds_the_corpus() {
+ let home = tempfile::tempdir().unwrap();
+ let _h = code_home(home.path());
+ let pack = build_demo_pack(home.path());
+ let add = || run_corpus_add(&["--from".to_string(), pack.display().to_string()]);
+ let held = lock_corpus_add(home.path(), "demo").unwrap();
+ assert_eq!(add(), 1);
+ assert!(!home.path().join("corpora/demo").exists());
+ drop(held);
+ assert_eq!(add(), 0);
+ }
+
#[test]
fn local_checkout_root_is_a_directory_or_a_file_url() {
assert!(local_checkout_root("https://github.com/xerj-org/xerj").is_none());
@@@ -6425,250 -6788,4 +6928,385 @@@
"an escaping paths entry is refused before any directory is created"
);
}
+
+ /// #2486: a `paths` entry may name a file. The pandas time-series pack
+ /// needs `pandas/core/resample.py` without the rest of `pandas/core`, and
+ /// naming the parent directory crowds the documentation out of the top
+ /// hits. A file entry checks out that file and nothing beside it: not a
+ /// sibling whose name starts the same way, and not a file of the same
+ /// name deeper in the tree (the pattern is anchored at the root).
+ #[test]
+ fn corpus_add_from_paths_harvests_a_named_file() {
+ let home = tempfile::tempdir().unwrap();
+ let _hold = code_home(home.path());
+ let origin = home.path().join("origin");
+ init_committed_repo(
+ &origin,
+ &[
+ ("LICENSE", "bsd\n"),
+ ("pkg/core/resample.py", "def resample(): pass\n"),
+ ("pkg/core/resample.pyx", "cdef int x\n"),
+ ("pkg/core/frame.py", "class DataFrame: pass\n"),
+ ("other/pkg/core/resample.py", "def other(): pass\n"),
+ ("doc/timeseries.rst", "Time series\n"),
+ ],
+ );
+ let sha = head_sha(&origin);
+ let url = origin.display().to_string();
+ let manifest = home.path().join("pin.json");
+ let checkout = home.path().join("corpora/sparse-demo/vulndb");
+
+ write_pin(
+ &manifest,
+ &url,
+ &sha,
+ Some(&["pkg/core/resample.py", "doc"]),
+ );
+ assert_eq!(
+ run_corpus_add(&["--from".into(), manifest.display().to_string()]),
+ 0,
+ "a paths entry naming a file must be harvested"
+ );
+ assert_eq!(
+ worktree_files(&checkout),
+ vec![
+ "doc/timeseries.rst".to_string(),
+ "pkg/core/resample.py".to_string(),
+ ]
+ );
+ let recorded =
+ manifest::read_corpus_manifest(&home.path().join("corpora/sparse-demo/corpus.json"))
+ .unwrap();
+ assert_eq!(
+ recorded.repos[0].paths,
+ vec!["pkg/core/resample.py".to_string(), "doc".to_string()]
+ );
+ assert_eq!(recorded.repos[0].files, Some(2));
+
+ // Re-adding over the existing checkout narrows and widens it too.
+ write_pin(&manifest, &url, &sha, Some(&["doc"]));
+ assert_eq!(
+ run_corpus_add(&["--from".into(), manifest.display().to_string()]),
+ 0
+ );
+ assert_eq!(
+ worktree_files(&checkout),
+ vec!["doc/timeseries.rst".to_string()]
+ );
+ write_pin(&manifest, &url, &sha, Some(&["pkg/core/frame.py"]));
+ assert_eq!(
+ run_corpus_add(&["--from".into(), manifest.display().to_string()]),
+ 0
+ );
+ assert_eq!(
+ worktree_files(&checkout),
+ vec!["pkg/core/frame.py".to_string()]
+ );
+ }
+
+ /// Each tree entry kind gets its own answer, read from the mode, so a
+ /// submodule is not reported as a missing path.
+ #[test]
+ fn confirm_paths_exist_classifies_each_entry_kind() {
+ let home = tempfile::tempdir().unwrap();
+ let repo = home.path().join("repo");
+ init_committed_repo(&repo, &[("doc/a.rst", "a\n"), ("pkg/m.py", "x = 1\n")]);
+ let first = head_sha(&repo);
+ let gitlink = format!("160000,{first},vendor/sub");
+ let (rc, out) = git(
+ Some(&repo),
+ &["update-index", "--add", "--cacheinfo", &gitlink],
+ )
+ .unwrap();
+ assert_eq!(rc, 0, "git update-index: {out}");
+ let (rc, out) = git(
+ Some(&repo),
+ &[
+ "-c",
+ "-c",
+ "user.name=xerj-test",
+ "commit",
+ "--quiet",
+ "-m",
+ "gitlink",
+ ],
+ )
+ .unwrap();
+ assert_eq!(rc, 0, "git commit: {out}");
+ let sha = head_sha(&repo);
+ let paths = |list: &[&str]| list.iter().map(|p| p.to_string()).collect::<Vec<_>>();
+
+ assert_eq!(
+ confirm_paths_exist(&repo, &sha, &paths(&["pkg/m.py", "doc"])).unwrap(),
+ vec![PathKind::File, PathKind::Dir]
+ );
+ let err = confirm_paths_exist(&repo, &sha, &paths(&["vendor/sub"]))
+ .unwrap_err()
+ .to_string();
+ assert!(err.contains("is a submodule"), "{err}");
+ let err = confirm_paths_exist(&repo, &sha, &paths(&["doc/nope.rst"]))
+ .unwrap_err()
+ .to_string();
+ assert!(err.contains("has no such path"), "{err}");
+ }
+
+ /// A symlink entry is refused end to end. Naming one would hand
+ /// `corpus index` a link the manifest author chose, possibly pointing out
+ /// of the checkout, so it is refused and no corpus is recorded.
+ #[cfg(unix)]
+ #[test]
+ fn corpus_add_from_paths_refuses_a_symlink_entry() {
+ let home = tempfile::tempdir().unwrap();
+ let _hold = code_home(home.path());
+ let origin = home.path().join("origin");
+ init_committed_repo(&origin, &[("LICENSE", "bsd\n")]);
+ std::os::unix::fs::symlink("/etc/hostname", origin.join("link")).unwrap();
+ let (rc, out) = git(Some(&origin), &["add", "--", "link"]).unwrap();
+ assert_eq!(rc, 0, "git add link: {out}");
+ let (rc, out) = git(
+ Some(&origin),
+ &[
+ "-c",
+ "-c",
+ "user.name=xerj-test",
+ "commit",
+ "--quiet",
+ "-m",
+ "link",
+ ],
+ )
+ .unwrap();
+ assert_eq!(rc, 0, "git commit: {out}");
+ let sha = head_sha(&origin);
+ let manifest = home.path().join("pin.json");
+ write_pin(
+ &manifest,
+ &origin.display().to_string(),
+ &sha,
+ Some(&["link"]),
+ );
+ assert_eq!(
+ run_corpus_add(&["--from".into(), manifest.display().to_string()]),
+ 1
+ );
+ assert!(
+ !home.path().join("corpora/sparse-demo/corpus.json").exists(),
+ "a refused symlink entry must not record a corpus"
+ );
+ assert!(!home
+ .path()
+ .join("corpora/sparse-demo/vulndb/LICENSE")
+ .exists());
+ }
+ #[test]
+ fn corpus_bad_sparse_path_preserves_existing_checkout_and_manifest() {
+ let home = tempfile::tempdir().unwrap();
+ let _hold = code_home(home.path());
+ let origin = home.path().join("origin");
+ init_committed_repo(
+ &origin,
+ &[
+ ("doc/keep.txt", "retained content\n"),
+ ("pkg/code.rs", "fn f() {}\n"),
+ ],
+ );
+ let sha = head_sha(&origin);
+ let pin = home.path().join("pin.json");
+ let url = origin.display().to_string();
+ write_pin(&pin, &url, &sha, Some(&["doc"]));
+ let args = vec!["--from".to_string(), pin.display().to_string()];
+ assert_eq!(run_corpus_add(&args), 0);
+ let checkout = home.path().join("corpora/sparse-demo/vulndb");
+ let manifest = home.path().join("corpora/sparse-demo/corpus.json");
+ let before = std::fs::read(&manifest).unwrap();
+ let index_before = std::fs::read(checkout.join(".git/index")).unwrap();
+ let sparse_before = std::fs::read(checkout.join(".git/info/sparse-checkout")).unwrap();
+ std::fs::write(checkout.join("local-note.txt"), "uncommitted local note").unwrap();
+ write_pin(&pin, &url, &sha, Some(&["pkg/code.rs", "missing.txt"]));
+ assert_eq!(run_corpus_add(&args), 1);
+ assert_eq!(std::fs::read(&manifest).unwrap(), before);
+ assert_eq!(
+ std::fs::read(checkout.join(".git/index")).unwrap(),
+ index_before
+ );
+ assert_eq!(
+ std::fs::read(checkout.join(".git/info/sparse-checkout")).unwrap(),
+ sparse_before
+ );
+ assert_eq!(
+ std::fs::read_to_string(checkout.join("doc/keep.txt")).unwrap(),
+ "retained content\n"
+ );
+ assert_eq!(
+ std::fs::read_to_string(checkout.join("local-note.txt")).unwrap(),
+ "uncommitted local note"
+ );
+ assert!(!checkout.join("pkg/code.rs").exists());
+ assert_eq!(head_sha(&checkout), sha);
+ // Correcting the path performs the requested narrower harvest.
+ write_pin(&pin, &url, &sha, Some(&["pkg/code.rs"]));
+ assert_eq!(run_corpus_add(&args), 0);
+ assert!(checkout.join("pkg/code.rs").is_file());
+ assert!(!checkout.join("doc/keep.txt").exists());
+ }
+ #[test]
+ fn corpus_add_does_not_delete_an_unborn_repo_with_user_files() {
+ let home = tempfile::tempdir().unwrap();
+ let _hold = code_home(home.path());
+ let origin = home.path().join("widget");
+ init_committed_repo(&origin, &[("keep.txt", "remote content\n")]);
+ let target = home.path().join("corpora/preserve/widget");
+ std::fs::create_dir_all(&target).unwrap();
+ assert_eq!(git(Some(&target), &["init", "--quiet"]).unwrap().0, 0);
+ std::fs::write(target.join("local-note.txt"), "irreplaceable local content").unwrap();
+ let code = run_corpus_add(&["preserve".into(), origin.display().to_string()]);
- assert_eq!(std::fs::read_to_string(target.join("local-note.txt")).ok().as_deref(),
- Some("irreplaceable local content"), "an unborn repo is not proof of disposable state");
++ assert_eq!(
++ std::fs::read_to_string(target.join("local-note.txt"))
++ .ok()
++ .as_deref(),
++ Some("irreplaceable local content"),
++ "an unborn repo is not proof of disposable state"
++ );
+ assert_eq!(code, 1, "an ambiguous existing checkout must be refused");
+ assert!(!home.path().join("corpora/preserve/corpus.json").exists());
+ // Keeping the old directory separately makes a normal retry safe.
+ let backup = home.path().join("saved-incomplete-widget");
+ std::fs::rename(&target, &backup).unwrap();
- assert_eq!(run_corpus_add(&["preserve".into(), origin.display().to_string()]), 0);
- assert_eq!(std::fs::read_to_string(backup.join("local-note.txt")).unwrap(), "irreplaceable local content");
- assert_eq!(std::fs::read_to_string(target.join("keep.txt")).unwrap(), "remote content\n");
++ assert_eq!(
++ run_corpus_add(&["preserve".into(), origin.display().to_string()]),
++ 0
++ );
++ assert_eq!(
++ std::fs::read_to_string(backup.join("local-note.txt")).unwrap(),
++ "irreplaceable local content"
++ );
++ assert_eq!(
++ std::fs::read_to_string(target.join("keep.txt")).unwrap(),
++ "remote content\n"
++ );
+ }
+
++ #[test]
++ fn corpus_add_does_not_reset_user_edits_when_index_is_missing() {
++ let home = tempfile::tempdir().unwrap();
++ let _hold = code_home(home.path());
++ let origin = home.path().join("widget");
++ init_committed_repo(&origin, &[("keep.txt", "remote content\n")]);
++ let args = vec!["preserve".into(), origin.display().to_string()];
++ assert_eq!(run_corpus_add(&args), 0);
++ let target = home.path().join("corpora/preserve/widget");
++ let manifest = home.path().join("corpora/preserve/corpus.json");
++ let before = std::fs::read(&manifest).unwrap();
++ std::fs::write(target.join("keep.txt"), "irreplaceable local edit").unwrap();
++ std::fs::remove_file(target.join(".git/index")).unwrap();
++ let code = run_corpus_add(&args);
++ assert_eq!(
++ std::fs::read_to_string(target.join("keep.txt")).unwrap(),
++ "irreplaceable local edit",
++ "missing index does not authorize reset --hard"
++ );
++ assert_eq!(code, 1);
++ assert_eq!(std::fs::read(&manifest).unwrap(), before);
++ }
++
++ fn preserve_incomplete_for_retry(checkout: &Path) -> PathBuf {
++ let backup = checkout.with_extension("saved");
++ assert!(!backup.exists());
++ std::fs::rename(checkout, &backup).unwrap();
++ backup
++ }
++
++ #[test]
++ fn staged_clone_failure_never_publishes_a_partial_checkout() {
++ let home = tempfile::tempdir().unwrap();
++ let target = home.path().join("repo");
++ let error = stage_new_checkout(&target, |stage| {
++ assert!(!target.exists());
++ std::fs::create_dir_all(stage)?;
++ std::fs::write(stage.join("partial.txt"), "partial")?;
++ anyhow::bail!("injected clone failure")
++ })
++ .unwrap_err();
++ assert!(error.to_string().contains("injected clone failure"));
++ assert!(!target.exists());
++ assert_eq!(std::fs::read_dir(home.path()).unwrap().count(), 0);
++ stage_new_checkout(&target, |stage| {
++ assert!(!target.exists());
++ init_committed_repo(stage, &[("complete.txt", "complete\n")]);
++ Ok(())
++ })
++ .unwrap();
++ assert!(existing_checkout_is_complete(&target));
++ assert_eq!(std::fs::read_dir(home.path()).unwrap().count(), 1);
++ }
++
++ #[test]
++ fn staged_clone_does_not_replace_a_destination_created_during_clone() {
++ let home = tempfile::tempdir().unwrap();
++ let target = home.path().join("repo");
++ let error = stage_new_checkout(&target, |stage| {
++ init_committed_repo(stage, &[("remote.txt", "remote\n")]);
++ std::fs::create_dir(&target)?;
++ std::fs::write(target.join("local.txt"), "local content")?;
++ Ok(())
++ })
++ .unwrap_err();
++ assert!(error.to_string().contains("already exists"));
++ assert_eq!(
++ std::fs::read_to_string(target.join("local.txt")).unwrap(),
++ "local content"
++ );
++ assert!(!target.join("remote.txt").exists());
++ assert_eq!(std::fs::read_dir(home.path()).unwrap().count(), 1);
++ let error = stage_new_checkout(&target, |_| {
++ panic!("existing destination must be refused before cloning")
++ })
++ .unwrap_err();
++ assert!(error.to_string().contains("already exists"));
++ }
++
++ #[test]
++ fn corpus_failed_new_clone_can_be_retried_without_deleting_anything() {
++ let home = tempfile::tempdir().unwrap();
++ let _hold = code_home(home.path());
++ let origin = home.path().join("widget");
++ let args = vec!["retry".into(), origin.display().to_string()];
++ assert_eq!(run_corpus_add(&args), 1);
++ let corpus = home.path().join("corpora/retry");
++ assert_eq!(std::fs::read_dir(&corpus).unwrap().count(), 0);
++ init_committed_repo(&origin, &[("complete.txt", "complete\n")]);
++ assert_eq!(run_corpus_add(&args), 0);
++ assert!(corpus.join("widget/complete.txt").is_file());
++ assert!(corpus.join("corpus.json").is_file());
++ }
++
++ #[test]
++ fn a_committed_empty_tree_is_a_reusable_checkout() {
++ let home = tempfile::tempdir().unwrap();
++ let repo = home.path().join("empty");
++ std::fs::create_dir(&repo).unwrap();
++ assert_eq!(git(Some(&repo), &["init", "--quiet"]).unwrap().0, 0);
++ assert_eq!(
++ git(
++ Some(&repo),
++ &[
++ "-c",
++ "user.name=xerj-test",
++ "-c",
++ "commit",
++ "--allow-empty",
++ "--quiet",
++ "-m",
++ "empty"
++ ]
++ )
++ .unwrap()
++ .0,
++ 0
++ );
++ assert!(existing_checkout_is_complete(&repo));
++ }
}
diff --cc tools/xerj-code/README.md
index d9e1cd872,c91a54feb..0a00469dd
--- a/tools/xerj-code/README.md
+++ b/tools/xerj-code/README.md
@@@ -71,6 -71,16 +71,19 @@@ across two machines. A `review` block i
[`hub/README.md`](hub/README.md)) is preserved for every repo that lands at its
recorded SHA.
-A `corpus add` that was stopped partway (a tool timeout, Ctrl-C) can be run
-again (#2453). A clone stopped before its first checkout is cloned again;
-one stopped while writing files already holds every object, so its files are
-restored in place without the network. A pinned (`--from`) repo is instead
-fetched and checked out at its SHA as usual. A leftover `.git/index.lock`
-(git's sign that a git may still be writing; a hard kill leaves one) and a
-checkout git cannot read both fail the run with what to do, and the
-checkout is kept. One `corpus add` per corpus runs at a time: a second is
-refused.
++New clones are prepared in a private temporary directory and published only
++when checkout succeeds (#2453). An ordinary failure cleans that attempt's
++stage; a hard kill can leave a hidden `.xerj-clone-*` directory, but a retry
++uses a new stage instead of treating it as a completed checkout. One
++`corpus add` per corpus runs at a time; a second is refused.
++
++An existing checkout with an unreadable commit, a missing index, or an
++`index.lock` is preserved and refused. These states do not prove it is safe
++to delete the directory or overwrite local edits. Wait for active Git
++operations; for an incomplete checkout, move the directory to an unused
++backup location and rerun the original command. The backup retains local
++files for review. Completed linked worktrees remain reusable.
+
A local path (`/path/to/checkout` or `file:///path/to/checkout`) is cloned the
same way. Git checks out committed files only, so a root `.xerjignore` that is
untracked or has uncommitted edits would never reach the clone, and the index