AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.
Rust agent-memoryai-agentsbm25claude-codeclicode-searchcursordatabaseelasticsearchfull-text-searchhybrid-searchjsonllocal-firstmcpmcp-servermodel-context-protocolragrustsearch-enginevector-search
fix(autoindex): refuse unsupported corpus reconciliation
buger25f81e168bee
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e380144d1..191e86fa5 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -529,6 +529,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0`/v1/embedding/identity` reports `lexical` — the backend the server willreally use — rather than `proxy`.+### Changed — fail-closed autoindex restart semantics++- **`autoindex --fresh` no longer discards a durable resume plan.** A durable+ plan contains the alias, path, graph, and stale-record knowledge needed for+ safe reconciliation. `--fresh` is accepted only when the selected state+ directory has no durable plan and never cleans the destination. An+ independent rebuild must use a new state directory, new prefix, and new brain+ namespace when graph detection is enabled (or disable graph writes), be+ validated, and only then replace the old reader target. The shared catalog+ and old target require explicit, validated cleanup. Membership additions and+ removals are refused; same-path replacement remains supported.+- **`xerj brain` no longer turns an absent or zero node-count probe into an+ automatic reset.** Journal/server disagreement now fails with the journal,+ URL, prefix, and brain identity plus recovery instructions. Probe transport+ and malformed-response failures remain errors instead of being reported as+ an empty destination.+## [1.0.0-rc.10] - 2026-08-03### Security@@ -605,7 +622,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0caveats. They are tracked for the following release rather than rushed intothis one.-### Changed — runtime-field types (can break existing mappings)- **`mappings.runtime` is now validated against ES's runtime-field typediff --git a/demo/usecases/autoindex/RECIPE_DRAFT.md b/demo/usecases/autoindex/RECIPE_DRAFT.mdindex 927c88aa1..faa1b6ec8 100644--- a/demo/usecases/autoindex/RECIPE_DRAFT.md+++ b/demo/usecases/autoindex/RECIPE_DRAFT.md@@ -203,8 +203,13 @@ done in 0.1s — 3 datasets, 5801 records live, 0 junk records, 1 junk/skipped fjust polite re-runs: in the robustness evaluation, a `kill -9` at 18 s into a200 MB file followed by a re-run converged to **byte-identical counts acrossall 9 datasets** — no duplicates. `xerj autoindex status` shows the journal-and live index counts; `--fresh` ignores the journal and restarts (ids stay-idempotent).+and live index counts. `--fresh` starts without resume state only when the+selected state directory has no durable plan; it never removes stale+destination records. For an independent rebuild, use a new `--state-dir`, new+`--prefix`, and new `--brain` when graph detection is enabled (or add+`--no-graph`). Validate before switching readers. The shared+`autoindex-catalog` and old target require explicit, validated cleanup. Added+or removed content groups are refused; same-path replacement remains supported.## Reproduce it yourselfdiff --git a/demo/usecases/autoindex/run-eval.sh b/demo/usecases/autoindex/run-eval.shindex 51c2b4f4b..dc36277ec 100755--- a/demo/usecases/autoindex/run-eval.sh+++ b/demo/usecases/autoindex/run-eval.sh@@ -2,9 +2,9 @@# End-to-end eval of `xerj autoindex` against a corpus folder.## Boots a dedicated server on es_compat $PORT (rest PORT+100, grpc PORT+101),-# runs autoindex over $CORPUS, then re-runs twice to prove idempotency — the-# resume path (all files done) and a full --fresh re-extract — and requires the-# per-index doc counts to be byte-identical to run 1. Ends with the data map.+# runs autoindex over $CORPUS, proves same-state resume, then performs an+# isolated data/graph rebuild under a new state directory, prefix, and brain.+# The global autoindex-catalog remains shared and is excluded from comparison.## Nothing here is bound to one machine: every path is an env override with a# default under the repo or $TMPDIR, so the same script gates CI and drives a@@ -33,9 +33,19 @@ CFG="$WORK/server-$PORT.toml"LOG="$WORK/server-$PORT.log"URL="http://localhost:$PORT"STATE="$WORK/state"+REBUILD_STATE="$WORK/rebuild-state"+PREFIX="ax-eval-a"+REBUILD_PREFIX="ax-eval-b"+BRAIN="eval-a"+REBUILD_BRAIN="eval-b"[ -x "$BIN" ] || { echo "xerj binary not found at $BIN"; exit 1; }[ -d "$CORPUS" ] || { echo "corpus folder not found at $CORPUS"; exit 1; }+[ ! -e "$DATA" ] && [ ! -e "$STATE" ] && [ ! -e "$REBUILD_STATE" ] || {+ echo "work directory already contains eval state: $WORK"+ echo "choose a new XERJ_AUTOINDEX_WORK or explicitly remove the old isolated eval directory"+ exit 1+}mkdir -p "$WORK"cat >"$CFG" <<EOF@@ -66,7 +76,7 @@ curl -sf "$URL/" >/dev/null || { echo "server failed to boot"; tail -20 "$LOG";FAIL=0echo "=== autoindex run ($CORPUS) ==="-time "$BIN" autoindex "$CORPUS" --url "$URL" --state-dir "$STATE" --fresh+time "$BIN" autoindex "$CORPUS" --url "$URL" --state-dir "$STATE" --prefix "$PREFIX" --brain "$BRAIN"RC=$?echo "exit code: $RC"# 0 complete, 3 completed-with-junk (unreadable files recorded, never fatal).@@ -75,25 +85,35 @@ if [ "$RC" != "0" ] && [ "$RC" != "3" ]; thenFAIL=1fi-# Name + doc count only. The _cat row also carries on-disk size, which a-# --fresh re-extract legitimately changes (segments are rewritten), and the-# catalog is excluded outright because every run appends its own run record —-# a growing catalog is the design, not drift. Columns of the _cat row:+# Name + doc count only. The _cat row also carries on-disk size, which an+# isolated data/graph rebuild legitimately changes (segments are rewritten).+# The shared global catalog is excluded because every run appends its own run+# record — a growing catalog is the design, not drift. Columns of the _cat row:# green(1) open(2) name(3) uuid(4) pri(5) rep(6) docs(7).-counts() { curl -s "$URL/_cat/indices" | awk '$3 ~ /^ax-/ {print $3, $7}' | sort; }+counts() { curl -s "$URL/_cat/indices" | awk -v prefix="$1-" '$3 ~ ("^" prefix) {sub("^" prefix, "", $3); print $3, $7}' | sort; }echo "=== per-index counts (run 1) ==="curl -s "$URL/_cat/indices" | grep -E 'ax-|autoindex-catalog' | sort-counts > "$WORK/counts-run1.txt"+counts "$PREFIX" > "$WORK/counts-run1.txt"echo "=== idempotency: re-run (resume path — all files done) ==="-time "$BIN" autoindex "$CORPUS" --url "$URL" --state-dir "$STATE"+time "$BIN" autoindex "$CORPUS" --url "$URL" --state-dir "$STATE" --prefix "$PREFIX" --brain "$BRAIN"+RC=$?+if [ "$RC" != "0" ] && [ "$RC" != "3" ]; then+ echo "resume run exited $RC (expected 0 or 3)"+ FAIL=1+fi-echo "=== idempotency: re-run with --fresh (full re-extract, idempotent ids) ==="-time "$BIN" autoindex "$CORPUS" --url "$URL" --state-dir "$STATE" --fresh+echo "=== isolated data/graph rebuild reproducibility (new state, prefix, and brain; shared catalog excluded) ==="+time "$BIN" autoindex "$CORPUS" --url "$URL" --state-dir "$REBUILD_STATE" --prefix "$REBUILD_PREFIX" --brain "$REBUILD_BRAIN"+RC=$?+if [ "$RC" != "0" ] && [ "$RC" != "3" ]; then+ echo "isolated data/graph rebuild exited $RC (expected 0 or 3)"+ FAIL=1+fi-counts > "$WORK/counts-run3.txt"-echo "=== doc-count diff run1 vs run3 (must be empty) ==="+counts "$REBUILD_PREFIX" > "$WORK/counts-run3.txt"+echo "=== normalized data-index count diff original vs isolated data/graph rebuild (shared catalog excluded; must be empty) ==="cat "$WORK/counts-run3.txt"if diff "$WORK/counts-run1.txt" "$WORK/counts-run3.txt"; thenecho "IDENTICAL COUNTS ✓"diff --git a/docs/EXPERIMENTAL_ONNX.md b/docs/EXPERIMENTAL_ONNX.mdindex 21b902fba..4b8cdf9ee 100644--- a/docs/EXPERIMENTAL_ONNX.md+++ b/docs/EXPERIMENTAL_ONNX.md@@ -88,7 +88,7 @@ In another terminal, index a corpus:target/release/xerj autoindex /path/to/corpus \--url http://localhost:9200 \--prefix finance-onnx \- --fresh+ --state-dir /path/to/new-finance-onnx-statetarget/release/xerj autoindex map \--url http://localhost:9200 \@@ -152,9 +152,11 @@ with the same assets. XERJ refuses:- enabling ONNX in place on a populated marker-less semantic index;- caller-supplied derived vectors whose identity cannot be verified.-The error tells the operator to restore the original assets or re-run-autoindex with `--fresh` and a new prefix. XERJ never silently mixes vector-spaces.+The error tells the operator to restore the original assets or perform an+isolated autoindex rebuild with a new state directory, new prefix, and new+brain when graph detection is enabled (or `--no-graph`). Validate the new+target before switching readers; the shared catalog and old target require+explicit, validated cleanup. XERJ never silently mixes vector spaces.The transformer-fused graph produced by the offline recipe is a differentmodel identity from its source graph because its model hash differs. Do notdiff --git a/docs/design/second_brain_graph_wf.js b/docs/design/second_brain_graph_wf.jsindex d36886952..404b5d591 100644--- a/docs/design/second_brain_graph_wf.js+++ b/docs/design/second_brain_graph_wf.js@@ -99,7 +99,9 @@ heterogeneous content (code + PDFs + docs), and captured as a screencast.automaticPresenceSimulation:true})\`, then claim via the setup magic-link the server printsat first boot. A working reference script is ${REPO}/sb_capture.mjs.- \`xerj brain\` gotcha: a stale resume journal in \`~/.xerj/autoindex\` makes re-runs skip- detection. Use \`--fresh\` (or clear it) for clean runs.+ detection. For an independent clean run, choose a new \`--state-dir\`, new+ \`--prefix\`, and new \`--brain\` (or \`--no-graph\`); \`--fresh\` cannot+ discard a durable plan or clean the shared catalog or old target.- Commits authored \`xerj-org <[email protected]>\`, NO Claude co-author trailer, never mentionctrl-frk. Do NOT push. Commit on \`feat/second-brain\`.diff --git a/docs/recipes/zero-config-indexing.md b/docs/recipes/zero-config-indexing.mdindex b14b5bb95..d63a24e1b 100644--- a/docs/recipes/zero-config-indexing.md+++ b/docs/recipes/zero-config-indexing.md@@ -228,7 +228,13 @@ live indices at http://localhost:9280:autoindex-catalog 9 docs```-`--fresh` ignores the journal and restarts (ids stay idempotent).+`--fresh` starts without resume state only when the selected state directory+has no durable plan; it never removes stale destination records. For an+independent rebuild, use a new `--state-dir`, new `--prefix`, and new+`--brain` when graph detection is enabled (or add `--no-graph`). Validate+before switching readers. The shared `autoindex-catalog` and old target require+explicit, validated cleanup. Added or removed content groups are refused;+same-path replacement remains supported.## Reproduce it yourselfdiff --git a/docs/usecases/second-brain/README.md b/docs/usecases/second-brain/README.mdindex 58bc181d7..41c74feec 100644--- a/docs/usecases/second-brain/README.md+++ b/docs/usecases/second-brain/README.md@@ -206,7 +206,11 @@ other note tools. No such numbers are claimed.- **YAML-frontmatter markdown can sniff as YAML:** one `SKILL.md` withfrontmatter landed in junk/skipped instead of being indexed.- **Stale resume journals can pollute links** after a wiped data dir;- `--fresh` re-walks everything and is the mitigation.+ `--fresh` cannot discard a durable plan and is not stale-journal recovery.+ Restore the server data directory used by the journal. For an explicitly+ isolated rebuild, use a new state directory, prefix, and brain namespace,+ validate it, then switch readers. The shared `autoindex-catalog` and old+ target require explicit, validated cleanup.- **Wikilink detection was not exercised on this corpus** (real docs usemarkdown links); it is covered by the demo-corpus run (30 wikilinks) andthe autoindex test suite.diff --git a/engine/crates/xerj-autoindex/src/cli.rs b/engine/crates/xerj-autoindex/src/cli.rsindex 055c30b9d..e225b4732 100644--- a/engine/crates/xerj-autoindex/src/cli.rs+++ b/engine/crates/xerj-autoindex/src/cli.rs@@ -72,6 +72,10 @@ pub enum Cmd {Help,}+const FRESH_HELP: &str =+ "start without resume state only when the selected state directory has no \+durable plan; an existing plan is refused and destination records are never reset";+pub fn print_help() {println!("xerj autoindex — point it at any folder and make the contents AI-searchable, zero config\n\@@ -99,7 +103,7 @@ pub fn print_help() {valid range 1..=3600)\n\--prefix <P> index prefix (default ax)\n\--state-dir <PATH> resume journal location (default ~/.xerj/autoindex/<hash>/)\n\- --fresh ignore existing journal, restart (ids stay idempotent)\n\+ --fresh {fresh_help}\n\--follow-symlinks follow symlinks (loop-safe); off by default\n\--max-file-gb <N> skip+record oversized non-streamable files (default 2)\n\--sample <N> records sampled per file for inference (default 500)\n\@@ -165,8 +169,17 @@ pub fn print_help() {`pct`/`eta_s` are the literal word `unknown` (JSON null) whenever they\n\cannot be computed honestly, never a filler number.\n\\n\+ RESUME POLICY:\n\+ A durable plan supports no-op resume and same-path content replacement.\n\+ Added or removed content groups are refused before remote mutation.\n\+ An independent rebuild needs a new --state-dir, new --prefix, and, when\n\+ graph detection is enabled, new --brain (or --no-graph). Validate before\n\+ switching readers; the shared autoindex-catalog and old target require\n\+ explicit, validated cleanup.\n\+ \n\EXIT CODES: 0 complete; 3 completed-with-junk (junk recorded, never fatal);\n\- 2 usage; 1 endpoint unreachable / journal-config mismatch\n"+ 2 usage; 1 endpoint/journal failure or unsupported corpus delta\n",+ fresh_help = FRESH_HELP);}@@ -462,6 +475,13 @@ mod tests {assert_eq!(index(&["data"]).bulk_timeout_secs, 300);}+ #[test]+ fn fresh_help_warns_that_it_is_not_destination_reconciliation() {+ assert!(super::FRESH_HELP.contains("no durable plan"));+ assert!(super::FRESH_HELP.contains("existing plan is refused"));+ assert!(super::FRESH_HELP.contains("destination records are never reset"));+ }+#[test]fn graph_is_on_by_default_with_derived_brain() {let cfg = index(&["data"]);diff --git a/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs b/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rsindex ba2211a99..74188e21c 100644--- a/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs+++ b/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs@@ -69,6 +69,9 @@ struct MockState {/// what `_count`/`_search` answer with, and the run verifies live data/// counts against the journal (#195). Catalog rows are not data rows.catalog_docs: HashMap<String, Value>,+ /// Every (method, path) the run issued. The refusal tests assert on the+ /// ABSENCE of remote mutations, which no document count can express.+ requests: Vec<(String, String)>,data_bulk_number: usize,fail_data_bulk: usize,failed_once: bool,@@ -190,6 +193,11 @@ fn handle(mut stream: TcpStream, state: &Arc<Mutex<MockState>>) {let mut parts = request_line.split_whitespace();let method = parts.next().unwrap_or("");let path = parts.next().unwrap_or("");+ state+ .lock()+ .unwrap()+ .requests+ .push((method.to_owned(), path.to_owned()));let response_delay_ms = state.lock().unwrap().response_delay_ms;if response_delay_ms > 0 {thread::sleep(std::time::Duration::from_millis(response_delay_ms));@@ -500,6 +508,230 @@ fn dataset_catalog_docs(endpoint: &MockEndpoint) -> Vec<Value> {docs}+fn assert_unsupported_delta_without_remote_mutation(+ endpoint: &MockEndpoint,+ config: IndexCfg,+ expected_added: &[&str],+ expected_vanished: &[&str],+) {+ let request_start = endpoint.state.lock().unwrap().requests.len();+ let journal_path = config.state_dir.as_ref().unwrap().join("journal.ndjson");+ let journal_before = fs::read(&journal_path).unwrap();+ let error = run_index(config).unwrap_err();+ let attempted_requests = endpoint.state.lock().unwrap().requests[request_start..].to_vec();+ assert_eq!(+ attempted_requests,+ [("GET".to_owned(), "/".to_owned())],+ "a refused attempt may perform only the endpoint-readiness GET"+ );+ assert_eq!(+ fs::read(journal_path).unwrap(),+ journal_before,+ "preflight refusal must not append a resume event or rewrite the journal"+ );+ let message = format!("{error:#}");+ assert!(message.contains("made no remote mutations"), "{message}");+ assert!(+ message.contains("existing destination may already be partial or stale"),+ "{message}"+ );+ assert!(+ message.contains("`--fresh` is not recovery or destination reconciliation"),+ "{message}"+ );+ assert!(+ message.contains("new --state-dir, a new --prefix"),+ "{message}"+ );+ assert!(message.contains("new --brain"), "{message}");+ for path in expected_added {+ assert!(+ message.contains(path),+ "missing added path {path}: {message}"+ );+ }+ for path in expected_vanished {+ assert!(+ message.contains(path),+ "missing vanished path {path}: {message}"+ );+ }+}++#[test]+fn completed_plan_rejects_added_content_group_before_remote_mutation() {+ let _guard = FAILPOINT_TEST_LOCK.lock().unwrap();+ let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK.lock().unwrap();+ let corpus = tempfile::tempdir().unwrap();+ let state_dir = tempfile::tempdir().unwrap();+ fs::write(corpus.path().join("first.csv"), "id,value\n1,first\n").unwrap();+ let endpoint = MockEndpoint::start(usize::MAX);+ let config = cfg(corpus.path(), state_dir.path(), &endpoint.url);+ assert_eq!(run_index(config.clone()).unwrap(), 0);++ fs::write(corpus.path().join("second.csv"), "id,value\n2,second\n").unwrap();+ assert_unsupported_delta_without_remote_mutation(&endpoint, config, &["second.csv"], &[]);+}++#[test]+fn completed_plan_rejects_vanished_content_group_before_remote_mutation() {+ let _guard = FAILPOINT_TEST_LOCK.lock().unwrap();+ let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK.lock().unwrap();+ let corpus = tempfile::tempdir().unwrap();+ let state_dir = tempfile::tempdir().unwrap();+ fs::write(corpus.path().join("first.csv"), "id,value\n1,first\n").unwrap();+ fs::write(corpus.path().join("second.csv"), "id,value\n2,second\n").unwrap();+ let endpoint = MockEndpoint::start(usize::MAX);+ let config = cfg(corpus.path(), state_dir.path(), &endpoint.url);+ assert_eq!(run_index(config.clone()).unwrap(), 0);++ fs::remove_file(corpus.path().join("second.csv")).unwrap();+ assert_unsupported_delta_without_remote_mutation(&endpoint, config, &[], &["second.csv"]);+}++#[test]+fn completed_plan_rejects_mixed_membership_delta_in_stable_order() {+ let _guard = FAILPOINT_TEST_LOCK.lock().unwrap();+ let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK.lock().unwrap();+ let corpus = tempfile::tempdir().unwrap();+ let state_dir = tempfile::tempdir().unwrap();+ fs::write(corpus.path().join("b-old.csv"), "id,value\n1,b\n").unwrap();+ fs::write(corpus.path().join("a-old.csv"), "id,value\n2,a\n").unwrap();+ let endpoint = MockEndpoint::start(usize::MAX);+ let mut config = cfg(corpus.path(), state_dir.path(), &endpoint.url);+ assert_eq!(run_index(config.clone()).unwrap(), 0);++ fs::remove_file(corpus.path().join("b-old.csv")).unwrap();+ fs::remove_file(corpus.path().join("a-old.csv")).unwrap();+ fs::write(corpus.path().join("z-new.csv"), "id,value\n3,z\n").unwrap();+ fs::write(corpus.path().join("m-new.csv"), "id,value\n4,m\n").unwrap();+ config.json = true;+ let request_start = endpoint.state.lock().unwrap().requests.len();+ let error = run_index(config).unwrap_err();+ assert_eq!(+ endpoint.state.lock().unwrap().requests[request_start..],+ [("GET".to_owned(), "/".to_owned())]+ );++ let typed = error+ .downcast_ref::<UnsupportedInventoryDeltaError>()+ .unwrap();+ let value = typed.to_json();+ assert_eq!(value["schema"], "xerj.autoindex.unsupported_sync_delta.v1");+ assert_eq!(value["status"], "error");+ let added: Vec<&str> = value["added_content_groups"]+ .as_array()+ .unwrap()+ .iter()+ .map(|entry| entry["path"].as_str().unwrap())+ .collect();+ let vanished: Vec<&str> = value["vanished_content_groups"]+ .as_array()+ .unwrap()+ .iter()+ .map(|entry| entry["path"].as_str().unwrap())+ .collect();+ assert_eq!(added, ["m-new.csv", "z-new.csv"]);+ assert_eq!(vanished, ["a-old.csv", "b-old.csv"]);+}++#[test]+fn nonempty_fresh_cannot_erase_plan_and_bypass_membership_gate() {+ let _guard = FAILPOINT_TEST_LOCK.lock().unwrap();+ let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK.lock().unwrap();+ let corpus = tempfile::tempdir().unwrap();+ let state_dir = tempfile::tempdir().unwrap();+ fs::write(corpus.path().join("old.csv"), "id,value\n1,old\n").unwrap();+ let endpoint = MockEndpoint::start(usize::MAX);+ let mut config = cfg(corpus.path(), state_dir.path(), &endpoint.url);+ assert_eq!(run_index(config.clone()).unwrap(), 0);++ fs::remove_file(corpus.path().join("old.csv")).unwrap();+ fs::write(corpus.path().join("new.csv"), "id,value\n2,new\n").unwrap();+ config.fresh = true;+ assert_unsupported_delta_without_remote_mutation(&endpoint, config, &["new.csv"], &["old.csv"]);+}++#[test]+fn fresh_rejects_same_content_canonical_promotion_even_when_group_key_matches() {+ let _guard = FAILPOINT_TEST_LOCK.lock().unwrap();+ let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK.lock().unwrap();+ let corpus = tempfile::tempdir().unwrap();+ let state_dir = tempfile::tempdir().unwrap();+ let bytes = "id,value\n1,same\n";+ fs::write(corpus.path().join("a.csv"), bytes).unwrap();+ fs::write(corpus.path().join("b.csv"), bytes).unwrap();+ let endpoint = MockEndpoint::start(usize::MAX);+ let mut config = cfg(corpus.path(), state_dir.path(), &endpoint.url);+ assert_eq!(run_index(config.clone()).unwrap(), 0);++ // b.csv becomes canonical with the same content key. A key-only delta is+ // empty, but fresh would discard the alias/path cleanup knowledge.+ fs::remove_file(corpus.path().join("a.csv")).unwrap();+ config.fresh = true;+ assert_unsupported_delta_without_remote_mutation(&endpoint, config, &[], &[]);+}++#[test]+fn unchanged_planned_junk_is_not_reported_as_added_content() {+ let _guard = FAILPOINT_TEST_LOCK.lock().unwrap();+ let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK.lock().unwrap();+ let corpus = tempfile::tempdir().unwrap();+ let state_dir = tempfile::tempdir().unwrap();+ fs::write(corpus.path().join("rows.csv"), "id,value\n1,kept\n").unwrap();+ fs::write(+ corpus.path().join("opaque.bin"),+ [0_u8, 159, 146, 150, 0, 255],+ )+ .unwrap();+ let endpoint = MockEndpoint::start(usize::MAX);+ let config = cfg(corpus.path(), state_dir.path(), &endpoint.url);+ assert_eq!(run_index(config.clone()).unwrap(), 3);+ let result = run_index(config);+ assert!(+ result.is_ok(),+ "unchanged durable junk must not trip the membership gate: {result:?}"+ );+}++#[test]+fn deleted_planned_junk_fails_closed_before_catalog_can_stay_stale() {+ let _guard = FAILPOINT_TEST_LOCK.lock().unwrap();+ let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK.lock().unwrap();+ let corpus = tempfile::tempdir().unwrap();+ let state_dir = tempfile::tempdir().unwrap();+ fs::write(corpus.path().join("rows.csv"), "id,value\n1,kept\n").unwrap();+ fs::write(+ corpus.path().join("opaque.bin"),+ [0_u8, 159, 146, 150, 0, 255],+ )+ .unwrap();+ let endpoint = MockEndpoint::start(usize::MAX);+ let config = cfg(corpus.path(), state_dir.path(), &endpoint.url);+ assert_eq!(run_index(config.clone()).unwrap(), 3);++ fs::remove_file(corpus.path().join("opaque.bin")).unwrap();+ assert_unsupported_delta_without_remote_mutation(&endpoint, config, &[], &["opaque.bin"]);+}++#[test]+fn completed_plan_rejects_empty_current_folder_before_remote_mutation() {+ let _guard = FAILPOINT_TEST_LOCK.lock().unwrap();+ let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK.lock().unwrap();+ let corpus = tempfile::tempdir().unwrap();+ let state_dir = tempfile::tempdir().unwrap();+ fs::write(corpus.path().join("only.csv"), "id,value\n1,only\n").unwrap();+ let endpoint = MockEndpoint::start(usize::MAX);+ let mut config = cfg(corpus.path(), state_dir.path(), &endpoint.url);+ assert_eq!(run_index(config.clone()).unwrap(), 0);++ fs::remove_file(corpus.path().join("only.csv")).unwrap();+ // Even `--fresh` must not erase the only durable inventory evidence and+ // then report success while the destination still contains the document.+ config.fresh = true;+ assert_unsupported_delta_without_remote_mutation(&endpoint, config, &[], &["only.csv"]);+}+#[test]fn semantic_resume_rejects_embedding_identity_drift_before_another_bulk() {let _guard = FAILPOINT_TEST_LOCK.lock().unwrap();@@ -1286,12 +1518,12 @@ fn a_planned_key_never_gains_two_owners_when_old_content_moves_paths() {).unwrap();fs::write(corpus.path().join("b.csv"), original).unwrap();- assert_eq!(run_index(config.clone()).unwrap(), 3);+ assert_unsupported_delta_without_remote_mutation(&endpoint, config.clone(), &["b.csv"], &[]);{let locked = endpoint.state.lock().unwrap();assert_eq!(locked.docs.len(), 2);assert!(locked.docs.values().all(|doc| {- doc["ax_path"].as_str() == Some("a.csv") && doc["value"].as_str() == Some("rewritten")+ doc["ax_path"].as_str() == Some("a.csv") && doc["value"].as_str() == Some("original")}));}let replay = state::Journal::open(@@ -1306,24 +1538,20 @@ fn a_planned_key_never_gains_two_owners_when_old_content_moves_paths() {assert!(replay.pending_replacements.is_empty());assert_eq!(replay.done.len(), 1);let plan = replay.plan.clone().unwrap();- assert_eq!(plan.junk_files.len(), 1);- assert_eq!(plan.junk_files[0].rel, "b.csv");- assert!(plan.junk_files[0]- .reason- .contains("key ownership exclusive"));+ assert!(plan.junk_files.is_empty());drop(replay);- // The divergence is durable and deterministic: an identical rerun keeps- // the same owner, appends no new plan, and changes no documents.+ // The refusal is deterministic: an identical rerun keeps the old owner,+ // appends no new plan, and changes no documents.let plans_before = event_count(state_dir.path(), "plan");- assert_eq!(run_index(config).unwrap(), 3);+ assert_unsupported_delta_without_remote_mutation(&endpoint, config, &["b.csv"], &[]);assert_eq!(event_count(state_dir.path(), "plan"), plans_before);let locked = endpoint.state.lock().unwrap();assert_eq!(locked.docs.len(), 2);assert!(locked.docs.values()- .all(|doc| doc["value"].as_str() == Some("rewritten")));+ .all(|doc| doc["value"].as_str() == Some("original")));}/// #238: a file added after the plan was frozen is skipped and reported in the@@ -1442,7 +1670,12 @@ fn deleting_an_entire_duplicate_group_strands_no_pending_replacement() {fs::remove_file(corpus.path().join("dup-a.csv")).unwrap();fs::remove_file(corpus.path().join("dup-b.csv")).unwrap();for _ in 0..2 {- assert_eq!(run_index(config.clone()).unwrap(), 0);+ assert_unsupported_delta_without_remote_mutation(+ &endpoint,+ config.clone(),+ &[],+ &["dup-a.csv"],+ );assert_eq!(event_count(state_dir.path(), "file_replace_start"),starts,diff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rsindex afc1bbf19..618c2d6c0 100644--- a/engine/crates/xerj-autoindex/src/lib.rs+++ b/engine/crates/xerj-autoindex/src/lib.rs@@ -22,6 +22,7 @@ pub mod state;pub mod walk;use anyhow::{Context, Result};+use serde::Serialize;use serde_json::{json, Map, Value};use std::collections::HashMap;use std::io::{BufRead, BufReader, Seek, Write};@@ -39,6 +40,30 @@ use progress::Progress;use sniff::{Family, Sniffed};use state::{DuplicateFile, FileAssignment, FileDone, JunkFile, Plan, PlanDataset};+#[derive(Debug, PartialEq, Eq)]+struct CliErrorRoute {+ exit_code: i32,+ stdout: Option<String>,+ stderr: Option<String>,+}++fn route_cli_error(error: &anyhow::Error, json_output: bool) -> CliErrorRoute {+ if json_output {+ if let Some(delta) = error.downcast_ref::<UnsupportedInventoryDeltaError>() {+ return CliErrorRoute {+ exit_code: 1,+ stdout: Some(delta.to_json().to_string()),+ stderr: None,+ };+ }+ }+ CliErrorRoute {+ exit_code: 1,+ stdout: None,+ stderr: Some(format!("error: {error:#}")),+ }+}+/// Entry point for the `xerj autoindex` subcommand (blocking; the server/// binary calls this via spawn_blocking). Returns the process exit code.pub fn run_cli() -> i32 {@@ -51,6 +76,7 @@ pub fn run_cli() -> i32 {return 2;}};+ let json_output = matches!(&cmd, Cmd::Index(cfg) if cfg.json);let res = match cmd {Cmd::Help => {cli::print_help();@@ -63,8 +89,14 @@ pub fn run_cli() -> i32 {match res {Ok(code) => code,Err(e) => {- eprintln!("error: {e:#}");- 1+ let route = route_cli_error(&e, json_output);+ if let Some(stdout) = route.stdout {+ println!("{stdout}");+ }+ if let Some(stderr) = route.stderr {+ eprintln!("{stderr}");+ }+ route.exit_code}}}@@ -1002,8 +1034,10 @@ fn select_resume_plan_keys(for (key, assignment) in &plan.files {if let Some(previous) = planned_by_rel.insert(&assignment.rel, key) {anyhow::bail!(- "resume plan assigns path {} to both {} and {}; use --fresh after verifying the \- existing index",+ "resume plan assigns path {} to both {} and {}; refusing to discard history under \+ the same destination. For an isolated rebuild use a new --state-dir, new \+ --prefix, and new --brain when graph detection is enabled (or --no-graph); \+ explicitly validate and clean the shared catalog and old target",assignment.rel,previous,key@@ -1012,8 +1046,11 @@ fn select_resume_plan_keys(if !assignment.path_id.is_empty() {if let Some(previous) = planned_by_path_id.insert(&assignment.path_id, key) {anyhow::bail!(- "resume plan assigns one native path identity to both {} and {}; use --fresh \- after verifying the existing index",+ "resume plan assigns one native path identity to both {} and {}; refusing to \+ discard history under the same destination. For an isolated rebuild use a \+ new --state-dir, new --prefix, and new --brain when graph detection is \+ enabled (or --no-graph); explicitly validate and clean the shared catalog \+ and old target",previous,key);@@ -1051,9 +1088,11 @@ fn select_resume_plan_keys(anyhow::bail!("{} collides with legacy resume key {} already owned by {}. No documents \were changed; remove or move one of these two files out of the corpus \- and rerun — every other file keeps its resume state. Deleting the \- journal at {} (or rerunning with --fresh) also clears the collision, \- but re-extracts and re-embeds the entire corpus",+ and rerun — every other file keeps its resume state. Refusing to discard \+ history under the same destination. For an isolated rebuild use a new \+ --state-dir, new --prefix, and new --brain when graph detection is \+ enabled (or --no-graph); explicitly validate and clean the shared \+ catalog and old target. Journal: {}",file.rel,legacy_key,assignment.rel,@@ -1085,6 +1124,157 @@ fn select_resume_plan_keys(Ok(selected)}+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+struct InventoryDeltaEntry {+ file_key: String,+ path: String,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+struct UnsupportedInventoryDelta {+ added_content_groups: Vec<InventoryDeltaEntry>,+ vanished_content_groups: Vec<InventoryDeltaEntry>,+}++#[derive(Debug)]+struct UnsupportedInventoryDeltaError {+ delta: UnsupportedInventoryDelta,+ fresh_existing_plan: bool,+}++impl UnsupportedInventoryDeltaError {+ fn to_json(&self) -> Value {+ json!({+ "schema": "xerj.autoindex.unsupported_sync_delta.v1",+ "status": "error",+ "error": if self.fresh_existing_plan {+ "unsafe_fresh_existing_plan"+ } else {+ "unsupported_inventory_delta"+ },+ "message": if self.fresh_existing_plan {+ "this attempt made no remote mutations; --fresh cannot discard an existing plan under the same destination because alias, path, graph, and stale-record cleanup knowledge would be lost; the existing destination may already be partial or stale"+ } else {+ "this attempt made no remote mutations because this autoindex plan cannot safely reconcile corpus membership changes; the existing destination may already be partial or stale"+ },+ "added_content_groups": self.delta.added_content_groups,+ "vanished_content_groups": self.delta.vanished_content_groups,+ "recovery": {+ "exact_rebuild": "index with a new --state-dir, new --prefix, and (when graph detection is enabled) new --brain; alternatively add --no-graph. Validate the isolated target before switching readers",+ "warning": "--fresh is not recovery or destination reconciliation. The global autoindex-catalog and old target are not cleaned automatically; validate and clean them explicitly"+ }+ })+ }+}++impl std::fmt::Display for UnsupportedInventoryDeltaError {+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ let render = |entries: &[InventoryDeltaEntry]| {+ entries+ .iter()+ .map(|entry| format!("{} ({})", entry.path, entry.file_key))+ .collect::<Vec<_>>()+ .join(", ")+ };+ let reason = if self.fresh_existing_plan {+ "`--fresh` cannot discard an existing plan under the same destination because alias, \+ path, graph, and stale-record cleanup knowledge would be lost"+ } else {+ "corpus membership synchronization is not yet supported"+ };+ write!(+ formatter,+ "this attempt made no remote mutations; the existing destination may already be \+ partial or stale. {reason}. Added \+ content groups [{}]; vanished content groups [{}]. For an exact rebuild, index the \+ current folder with a new --state-dir, a new --prefix, and, when graph detection is \+ enabled, a new --brain (or use --no-graph). Validate the isolated target before \+ switching readers. `--fresh` is not recovery or destination reconciliation; the \+ global autoindex-catalog and old target require explicit validated cleanup",+ render(&self.delta.added_content_groups),+ render(&self.delta.vanished_content_groups)+ )+ }+}++impl std::error::Error for UnsupportedInventoryDeltaError {}++impl UnsupportedInventoryDelta {+ fn between(files: &[walk::FileEntry], keys: &[String], plan: &Plan) -> Self {+ let current_keys: std::collections::HashSet<&str> = keys+ .iter()+ .filter(|key| !key.is_empty())+ .map(String::as_str)+ .collect();+ let durable_keys: std::collections::HashSet<&str> = plan+ .files+ .keys()+ .map(String::as_str)+ .chain(plan.junk_files.iter().map(|junk| junk.file_key.as_str()))+ .collect();++ let mut added_content_groups: Vec<InventoryDeltaEntry> = files+ .iter()+ .zip(keys)+ .filter(|(_, key)| !key.is_empty() && !durable_keys.contains(key.as_str()))+ .map(|(file, key)| InventoryDeltaEntry {+ file_key: key.clone(),+ path: file.rel.clone(),+ })+ .collect();+ let mut vanished_content_groups: Vec<InventoryDeltaEntry> = plan+ .files+ .iter()+ .filter(|(key, _)| !current_keys.contains(key.as_str()))+ .map(|(key, assignment)| InventoryDeltaEntry {+ file_key: key.clone(),+ path: assignment.rel.clone(),+ })+ .collect();+ vanished_content_groups.extend(+ plan.junk_files+ .iter()+ .filter(|junk| !current_keys.contains(junk.file_key.as_str()))+ .map(|junk| InventoryDeltaEntry {+ file_key: junk.file_key.clone(),+ path: junk.rel.clone(),+ }),+ );++ let stable_order = |left: &InventoryDeltaEntry, right: &InventoryDeltaEntry| {+ left.path+ .cmp(&right.path)+ .then_with(|| left.file_key.cmp(&right.file_key))+ };+ added_content_groups.sort_by(stable_order);+ vanished_content_groups.sort_by(stable_order);+ Self {+ added_content_groups,+ vanished_content_groups,+ }+ }++ fn is_empty(&self) -> bool {+ self.added_content_groups.is_empty() && self.vanished_content_groups.is_empty()+ }++ fn into_error(self) -> anyhow::Error {+ UnsupportedInventoryDeltaError {+ delta: self,+ fresh_existing_plan: false,+ }+ .into()+ }++ fn into_fresh_error(self) -> anyhow::Error {+ UnsupportedInventoryDeltaError {+ delta: self,+ fresh_existing_plan: true,+ }+ .into()+ }+}+fn alias_keys_to_reindex(previous: &[state::DuplicateFile],current: &[state::DuplicateFile],@@ -1260,35 +1450,75 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {.with_bulk_concurrency(cfg.workers, pr.enabled());es.ping()?;- // Totals are unknown until the walk returns, so this phase honestly- // reports `pct=unknown` and proves liveness with the clock alone.- pr.phase("walk", 0, 0);- let discovered_files = walk::walk(&cfg.root, cfg.follow_symlinks)?;- if discovered_files.is_empty() {- println!("no files found under {}", cfg.root.display());- pr.finish(true, 0, "no-files", &[]);- return Ok((0, None));- }- let discovered_bytes: u64 = discovered_files.iter().map(|f| f.size).sum();let root_str = cfg.root.canonicalize().unwrap_or_else(|_| cfg.root.clone()).to_string_lossy().to_string();+ let state_dir = cfg+ .state_dir+ .clone()+ .unwrap_or_else(|| state::default_state_dir(&root_str, &cfg.url, &cfg.prefix));+ // Acquire state authority before discovery as well as hashing. A waiter+ // must never classify a path snapshot taken while another owner was+ // publishing or replacing the durable plan.+ let preflight = state::Journal::preflight(&state_dir, &root_str, &cfg.url, &cfg.prefix)?;+ // Totals are unknown until the walk returns, so this phase honestly+ // reports `pct=unknown` and proves liveness with the clock alone.+ pr.phase("walk", 0, 0);+ let discovered_files = walk::walk(&cfg.root, cfg.follow_symlinks)?;+ let discovered_bytes: u64 = discovered_files.iter().map(|f| f.size).sum();pr.note(&format!("autoindex: {} files ({} MB) under {}",discovered_files.len(),discovered_bytes / (1 << 20),root_str));-- let state_dir = cfg- .state_dir- .clone()- .unwrap_or_else(|| state::default_state_dir(&root_str, &cfg.url, &cfg.prefix));- let mut journal = state::Journal::open(- &state_dir,+ if discovered_files.is_empty() && !preflight.journal_exists {+ println!("no files found under {}", cfg.root.display());+ pr.finish(true, 0, "no-files", &[]);+ return Ok((0, None));+ }+ // Full hashing on every run is deliberate: size/mtime/inode fingerprints+ // cannot prove byte identity across all supported local and network+ // filesystems. A metadata-only shortcut could leave stale live documents+ // forever after a same-size rewrite with restored or stale timestamps.+ // Hashing reads every byte of the corpus. On a large tree it is minutes of+ // real work, and before #241 it was minutes with no output at all.+ pr.phase("hash", discovered_files.len() as u64, discovered_bytes);+ let mut inventory = content::resolve_reporting(discovered_files, &|bytes| pr.item_done(bytes))?;+ if let Some(prior_plan) = preflight.plan.as_ref() {+ let comparison_keys = if cfg.fresh {+ inventory.keys.clone()+ } else {+ // Ordinary resume preserves planned-key identity for supported+ // same-path replacement and legacy plans.+ select_resume_plan_keys(+ &inventory.files,+ &inventory.keys,+ prior_plan,+ &state_dir.join("journal.ndjson"),+ )?+ .into_iter()+ .zip(inventory.keys.iter())+ .map(|(planned, current)| planned.unwrap_or_else(|| current.clone()))+ .collect()+ };+ let delta =+ UnsupportedInventoryDelta::between(&inventory.files, &comparison_keys, prior_plan);+ if cfg.fresh {+ // Even an apparently unchanged content-key set can have alias,+ // path, graph, catalog, or partial-publication history that only+ // the old plan can reconcile. Route 1 cannot safely discard it.+ return Err(delta.into_fresh_error());+ }+ if !delta.is_empty() {+ return Err(delta.into_error());+ }+ }+ let mut journal = state::Journal::open_after_preflight(+ preflight,&root_str,&cfg.url,&cfg.prefix,@@ -1296,6 +1526,11 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {cfg.fresh,)?;let resumed_with_plan = journal.plan.is_some();+ if inventory.files.is_empty() && !resumed_with_plan {+ println!("no files found under {}", cfg.root.display());+ pr.finish(true, 0, "no-files", &[]);+ return Ok((0, None));+ }let run_id = journal.run_id.clone();if journal.resumed {pr.note(&format!(@@ -1304,14 +1539,6 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {journal.done.len()));}- // Full hashing on every run is deliberate: size/mtime/inode fingerprints- // cannot prove byte identity across all supported local and network- // filesystems. A metadata-only shortcut could leave stale live documents- // forever after a same-size rewrite with restored or stale timestamps.- // Hashing reads every byte of the corpus. On a large tree it is minutes of- // real work, and before #241 it was minutes with no output at all.- pr.phase("hash", discovered_files.len() as u64, discovered_bytes);- let mut inventory = content::resolve_reporting(discovered_files, &|bytes| pr.item_done(bytes))?;let journal_path = journal.path().to_path_buf();let mut content_changed = std::collections::HashSet::new();let mut stale_alias_ids = Vec::new();@@ -1514,6 +1741,23 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {plan};+ // A durable plan is a crash-resume boundary, not a folder-sync+ // generation. Fail before index creation/mapping, replacement intent,+ // graph invalidation, delete-by-query, bulk publication, refresh, or+ // catalog writes when the current inventory adds or removes an entire+ // canonical content group. Continuing would either silently skip new+ // data or leave vanished source records searchable. Existing planned-key+ // content replacement and crash repair remain supported.+ //+ // This runs before the junk sweep below on purpose: a refused rerun must+ // compute nothing and mutate nothing.+ if resumed_with_plan {+ let delta = UnsupportedInventoryDelta::between(&files, &keys, &plan);+ if !delta.is_empty() {+ return Err(delta.into_error());+ }+ }+// ── stale junk-catalog sweep (#238) ──────────────────────────────────//// A junk/skipped file is never indexed and never enters the graph corpus@@ -1686,7 +1930,9 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {rel: files[i].rel.clone(),format: "unknown".into(),status: "skipped".into(),- reason: "not in the frozen resume plan (re-run with --fresh to include new files)"+ reason: "not in the frozen resume plan; no destination change was made. For an \+ exact rebuild use a new --state-dir, a new --prefix, and, when graph \+ detection is enabled, a new --brain (or use --no-graph)".into(),bytes: files[i].size,});@@ -3360,6 +3606,115 @@ mod section_label_tests {}}+#[cfg(test)]+mod inventory_delta_tests {+ use super::*;+ use std::path::PathBuf;++ fn file(path: &str) -> walk::FileEntry {+ walk::FileEntry {+ path: PathBuf::from(path),+ rel: path.to_owned(),+ rel_id: format!("id:{path}"),+ is_symlink: false,+ size: 1,+ }+ }++ fn assignment(path: &str) -> FileAssignment {+ FileAssignment {+ rel: path.to_owned(),+ path_id: format!("id:{path}"),+ family: "csv".into(),+ gzip: false,+ content_digest: Some(format!("digest:{path}")),+ assignments: vec![(None, "rows".into())],+ as_document: false,+ }+ }++ #[test]+ fn classifier_is_empty_for_noop_and_sorts_added_and_vanished_groups() {+ let mut plan = Plan::default();+ plan.files.insert("keep".into(), assignment("keep.csv"));+ assert!(+ UnsupportedInventoryDelta::between(&[file("keep.csv")], &["keep".into()], &plan)+ .is_empty()+ );+ plan.junk_files.push(JunkFile {+ file_key: "junk".into(),+ rel: "broken.pdf".into(),+ format: "pdf".into(),+ status: "junk".into(),+ reason: "fixture".into(),+ bytes: 1,+ });+ assert!(+ UnsupportedInventoryDelta::between(+ &[file("keep.csv"), file("broken.pdf")],+ &["keep".into(), "junk".into()],+ &plan,+ )+ .is_empty(),+ "unchanged durable junk is not newly added content"+ );++ plan.files.insert("old-z".into(), assignment("z-old.csv"));+ plan.files.insert("old-a".into(), assignment("a-old.csv"));+ let delta = UnsupportedInventoryDelta::between(+ &[+ file("keep.csv"),+ file("broken.pdf"),+ file("z-new.csv"),+ file("m-new.csv"),+ ],+ &["keep".into(), "junk".into(), "new-z".into(), "new-m".into()],+ &plan,+ );+ assert_eq!(+ delta+ .added_content_groups+ .iter()+ .map(|entry| entry.path.as_str())+ .collect::<Vec<_>>(),+ ["m-new.csv", "z-new.csv"]+ );+ assert_eq!(+ delta+ .vanished_content_groups+ .iter()+ .map(|entry| entry.path.as_str())+ .collect::<Vec<_>>(),+ ["a-old.csv", "z-old.csv"]+ );+ }++ #[test]+ fn cli_error_routing_separates_typed_json_from_unrelated_human_errors() {+ let typed = UnsupportedInventoryDelta {+ added_content_groups: vec![InventoryDeltaEntry {+ file_key: "key".into(),+ path: "new.csv".into(),+ }],+ vanished_content_groups: Vec::new(),+ }+ .into_error();+ let route = route_cli_error(&typed, true);+ assert_eq!(route.exit_code, 1);+ assert!(route.stderr.is_none());+ let stdout = route.stdout.unwrap();+ let value: Value = serde_json::from_str(&stdout).unwrap();+ assert_eq!(value["schema"], "xerj.autoindex.unsupported_sync_delta.v1");+ assert_eq!(value["error"], "unsupported_inventory_delta");++ let unrelated = anyhow::anyhow!("endpoint unavailable");+ let route = route_cli_error(&unrelated, true);+ assert_eq!(route.exit_code, 1);+ assert!(route.stdout.is_none());+ assert_eq!(route.stderr.as_deref(), Some("error: endpoint unavailable"));+ }+}+#[cfg(test)]mod duplicate_integration_tests {use super::*;@@ -3410,11 +3765,11 @@ mod duplicate_integration_tests {.unwrap_err();let message = format!("{error:#}");assert!(message.contains("collides with legacy resume key"));- // Recovery advice must stay scoped to the two colliding files and be- // honest that discarding the journal re-embeds the whole corpus.+ // Recovery advice must stay scoped to the two colliding files and+ // keep an exact rebuild isolated from the old destination.assert!(message.contains("remove or move one of these two files"));assert!(message.contains("/state/journal.ndjson"));- assert!(message.contains("re-extracts and re-embeds the entire corpus"));+ assert!(message.contains("new --state-dir, new --prefix, and new --brain"));}#[test]diff --git a/engine/crates/xerj-autoindex/src/state.rs b/engine/crates/xerj-autoindex/src/state.rsindex c72621c05..7d4be6bec 100644--- a/engine/crates/xerj-autoindex/src/state.rs+++ b/engine/crates/xerj-autoindex/src/state.rs@@ -178,6 +178,21 @@ mod tests {);}}++ #[test]+ fn preflight_holds_the_same_exclusive_lock_through_authoritative_open() {+ let dir = tempfile::tempdir().unwrap();+ let preflight = Journal::preflight(dir.path(), "root", "url", "prefix").unwrap();+ let error = Journal::open(dir.path(), "root", "url", "prefix", 300, false)+ .err()+ .expect("a second opener must not pass the held preflight lock");+ assert!(format!("{error:#}").contains("already in use"));++ let journal =+ Journal::open_after_preflight(preflight, "root", "url", "prefix", 300, false).unwrap();+ drop(journal);+ assert!(Journal::open(dir.path(), "root", "url", "prefix", 300, false).is_ok());+ }}#[derive(Debug, Clone, Serialize, Deserialize)]@@ -280,15 +295,97 @@ pub fn default_state_dir(root: &str, url: &str, prefix: &str) -> PathBuf {.join(crate::ids::state_key(root, url, prefix))}+/// Read the last durable plan without locking, repairing, truncating or+/// appending to the journal. This is a preflight hint only: `Journal::open`+/// remains the authority after the caller passes its fail-closed inventory+/// gate and acquires the state lock.+fn read_plan_for_preflight(+ path: &Path,+ root: &str,+ url: &str,+ prefix: &str,+) -> Result<Option<Plan>> {+ let file = match std::fs::File::open(path) {+ Ok(file) => file,+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),+ Err(error) => return Err(error.into()),+ };+ let mut reader = std::io::BufReader::new(file);+ let mut plan = None;+ let mut offset = 0u64;+ loop {+ let record_start = offset;+ let mut bytes = Vec::new();+ let read = reader.read_until(b'\n', &mut bytes)?;+ if read == 0 {+ break;+ }+ offset += read as u64;+ if bytes.last() != Some(&b'\n') {+ // `Journal::open` will repair this torn final record after the+ // preflight accepts. It cannot be treated as durable here.+ break;+ }+ let value: Value =+ serde_json::from_slice(bytes.strip_suffix(b"\n").unwrap_or(bytes.as_slice()))+ .with_context(|| {+ format!(+ "journal corruption at byte {record_start} in {}: malformed \+ newline-terminated record. Refusing to discard later records. Restore \+ the journal from a backup, or truncate it to exactly {record_start} \+ bytes to keep every completion recorded before the corruption. For an \+ isolated rebuild use a new --state-dir, new --prefix, and new --brain \+ when graph detection is enabled (or --no-graph); explicitly validate \+ and clean the shared catalog and old target",+ path.display()+ )+ })?;+ match value.get("kind").and_then(Value::as_str) {+ Some("run") => {+ let recorded_root = value.get("root").and_then(Value::as_str).unwrap_or("");+ let recorded_url = value.get("url").and_then(Value::as_str).unwrap_or("");+ let recorded_prefix = value.get("prefix").and_then(Value::as_str).unwrap_or("");+ anyhow::ensure!(+ recorded_root == root && recorded_url == url && recorded_prefix == prefix,+ "journal at {} was created for root={} url={} prefix={}; current run has \+ root={} url={} prefix={}",+ path.display(),+ recorded_root,+ recorded_url,+ recorded_prefix,+ root,+ url,+ prefix+ );+ }+ Some("plan") => {+ if let Some(encoded) = value.get("plan") {+ plan =+ Some(serde_json::from_value(encoded.clone()).with_context(|| {+ format!("decode durable plan in {}", path.display())+ })?);+ }+ }+ _ => {}+ }+ }+ Ok(plan)+}++pub struct JournalPreflight {+ state_dir: PathBuf,+ state_lock: std::fs::File,+ pub plan: Option<Plan>,+ pub journal_exists: bool,+}+impl Journal {- pub fn open(+ pub fn preflight(state_dir: &Path,root: &str,url: &str,prefix: &str,- bulk_timeout_secs: u64,- fresh: bool,- ) -> Result<Journal> {+ ) -> Result<JournalPreflight> {std::fs::create_dir_all(state_dir).with_context(|| format!("create state dir {}", state_dir.display()))?;let lock_path = state_dir.join(".autoindex.lock");@@ -305,10 +402,46 @@ impl Journal {state_dir.display())})?;+ let journal_path = state_dir.join("journal.ndjson");+ let journal_exists = journal_path.exists();+ let plan = read_plan_for_preflight(&journal_path, root, url, prefix)?;+ Ok(JournalPreflight {+ state_dir: state_dir.to_owned(),+ state_lock,+ plan,+ journal_exists,+ })+ }++ pub fn open(+ state_dir: &Path,+ root: &str,+ url: &str,+ prefix: &str,+ bulk_timeout_secs: u64,+ fresh: bool,+ ) -> Result<Journal> {+ let preflight = Self::preflight(state_dir, root, url, prefix)?;+ Self::open_after_preflight(preflight, root, url, prefix, bulk_timeout_secs, fresh)+ }++ pub fn open_after_preflight(+ preflight: JournalPreflight,+ root: &str,+ url: &str,+ prefix: &str,+ bulk_timeout_secs: u64,+ fresh: bool,+ ) -> Result<Journal> {+ let JournalPreflight {+ state_dir,+ state_lock,+ ..+ } = preflight;// Hard kills cannot run NamedTempFile::drop. Stages are owned by this// journal directory and use a reserved prefix, so removing only// regular files with that prefix is deterministic and scope-safe.- for entry in std::fs::read_dir(state_dir)? {+ for entry in std::fs::read_dir(&state_dir)? {let entry = entry?;if entry.file_name()@@ -361,7 +494,10 @@ impl Journal {anyhow::bail!("journal at {} was created for root={jr} url={ju} prefix={jp}; \current run has root={root} url={url} prefix={prefix}. \- Use --fresh to discard it or --state-dir for a separate state.",+ Refusing to discard history under the same destination. For an \+ isolated rebuild use a new --state-dir, new --prefix, and new \+ --brain when graph detection is enabled (or --no-graph); \+ explicitly validate and clean the shared catalog and old target.",jpath.display());}@@ -470,9 +606,10 @@ impl Journal {after corruption. Restore the journal from a backup, or truncate it \to exactly {record_start} bytes to keep every completion recorded \before the corruption (files journaled after that point are \- re-verified, re-indexed and re-embedded on the next run). Deleting \- the whole journal (or rerunning with --fresh) also recovers, but \- re-extracts and re-embeds the entire corpus",+ re-verified, re-indexed and re-embedded on the next run). For an \+ isolated rebuild use a new --state-dir, new --prefix, and new --brain \+ when graph detection is enabled (or --no-graph); explicitly validate \+ and clean the shared catalog and old target",jpath.display());}@@ -902,9 +1039,10 @@ mod compatibility_tests {let message = format!("{error:#}");assert!(message.contains("journal corruption"));// Recovery guidance must stay scoped and honest: byte-exact truncation- // keeps prior completions; discarding the journal re-embeds everything.+ // keeps prior completions; an exact rebuild needs isolated state and+ // destination identities.assert!(message.contains("truncate it to exactly"));- assert!(message.contains("re-extracts and re-embeds the entire corpus"));+ assert!(message.contains("new --state-dir, new --prefix, and new --brain"));}#[test]diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rsindex 66a2a0ccf..6a6210fcc 100644--- a/engine/crates/xerj-engine/src/index.rs+++ b/engine/crates/xerj-engine/src/index.rs@@ -24573,7 +24573,9 @@ fn validate_embedding_identity("embedding identity mismatch for index {}: persisted backend={} \model={} tokenizer={}, configured backend={} model={} tokenizer={}. \Refusing to mix incompatible vector spaces. Restore the original assets \- or re-run autoindex with --fresh and a new index prefix.",+ or rebuild with a new autoindex state directory, new index prefix, and new \+ brain when graph detection is enabled (or --no-graph); validate before \+ switching readers and explicitly clean the shared catalog and old target.",index_dir.display(),persisted.backend,persisted.model_sha256,@@ -24587,7 +24589,9 @@ fn validate_embedding_identity(format!("index {} contains ONNX vectors but the server is configured for \embedding.mode={:?}. Restart with onnx-experimental and the original \- assets, or reindex under a new prefix.",+ assets, or rebuild with a new autoindex state directory, new prefix, and new \+ brain when graph detection is enabled (or --no-graph); validate before \+ switching readers and explicitly clean the shared catalog and old target.",index_dir.display(),cfg.mode),@@ -24602,8 +24606,9 @@ fn validate_embedding_identity(format!("existing semantic index {} has no embedding identity marker. It may contain \vectors from another backend, so ONNX cannot be enabled safely in place. \- Re-run autoindex with --fresh and a new --prefix, or rebuild the index from \- source.",+ Rebuild from source with a new autoindex state directory, new --prefix, and new \+ --brain when graph detection is enabled (or --no-graph); validate before \+ switching readers and explicitly clean the shared catalog and old target.",index_dir.display()),)));@@ -24999,6 +25004,9 @@ mod embedding_identity_tests {.to_string();assert!(error.contains("identity mismatch"), "{error}");assert!(error.contains("new index prefix"), "{error}");+ assert!(error.contains("new brain"), "{error}");+ assert!(error.contains("--no-graph"), "{error}");+ assert!(error.contains("shared catalog"), "{error}");}#[test]@@ -25017,6 +25025,9 @@ mod embedding_identity_tests {.unwrap_err().to_string();assert!(error.contains("no embedding identity marker"), "{error}");+ assert!(error.contains("new --brain"), "{error}");+ assert!(error.contains("--no-graph"), "{error}");+ assert!(error.contains("shared catalog"), "{error}");}#[cfg(feature = "onnx-experimental")]diff --git a/engine/crates/xerj-server/src/brain.rs b/engine/crates/xerj-server/src/brain.rsindex 3ab287bf8..6ba6474eb 100644--- a/engine/crates/xerj-server/src/brain.rs+++ b/engine/crates/xerj-server/src/brain.rs@@ -79,8 +79,8 @@ pub fn print_help() {--api-key <K> API key for an already-running secured server\n\(or env XERJ_API_KEY; a server booted by this command\n\needs neither — its key is read from <data-dir>/admin.key)\n\- --fresh ignore the resume journal, re-walk everything\n\- (ids stay idempotent; converges to the same brain)\n\+ --fresh start without resume state only when the selected\n\+ journal has no durable plan; never resets server data\n\--no-open print the links but do not open a browser\n\--help, -h this help\n\\n\@@ -267,7 +267,7 @@ fn run(cfg: BrainCfg) -> Result<i32> {}// ── index: the autoindex pipeline, graph detection on ────────────────- let (mut code, mut run_doc) =+ let (code, run_doc) =xerj_autoindex::run_index_report(index_cfg(&cfg, &brain, api_key.clone()))?;let run_u64 = |doc: &Option<Value>, key: &str| {@@ -279,30 +279,16 @@ fn run(cfg: BrainCfg) -> Result<i32> {// `records_total` is run-scoped: a resumed re-run over an already-indexed// folder legitimately reports 0. Server truth decides what that means.if run_u64(&run_doc, "records_total") == 0 {- let live_nodes = live_node_docs(&es, &brain);- if live_nodes == 0 && run_u64(&run_doc, "files_indexed") > 0 && !cfg.fresh {- // The resume journal says this folder is done, but the server has- // none of it (wiped data dir, or a different --url than the run- // that wrote the journal). Trusting the journal here would leave a- // silent, permanently-empty brain — with only structural edges,- // since text detectors ride the per-file indexing pass. Re-index- // from scratch once; ids are idempotent, so this converges.- eprintln!(- "\nresume journal says {} is already indexed, but the server at {} has none \- of it — re-indexing from scratch",- cfg.root.display(),- cfg.url- );- let mut fresh_cfg = index_cfg(&cfg, &brain, api_key);- fresh_cfg.fresh = true;- (code, run_doc) = xerj_autoindex::run_index_report(fresh_cfg)?;+ let live_nodes = live_node_docs(&es, &brain)?;+ if journal_server_disagrees(run_u64(&run_doc, "files_indexed"), live_nodes, cfg.fresh) {+ bail!("{}", journal_server_disagreement(&cfg, &brain));}}// Server truth for every surface below: run-scoped counters read 0 on a// converged re-run, but the brain is live on the server all the same.let records_live = match run_u64(&run_doc, "records_total") {- 0 => live_node_docs(&es, &brain),+ 0 => live_node_docs(&es, &brain)?.unwrap_or(0),n => n,};if records_live == 0 {@@ -391,12 +377,13 @@ fn run(cfg: BrainCfg) -> Result<i32> {/// Count the node documents live on the server behind `brain`, via the brain/// meta doc's `nodes_index` (SECOND_BRAIN_SPEC §2.5 — autoindex writes the-/// comma-list of its dataset indices there). 0 on any miss: an unreadable-/// meta doc and an empty brain call for the same honest answer.-fn live_node_docs(es: &Es, brain: &str) -> u64 {+/// comma-list of its dataset indices there). Absence is distinct from an+/// authoritative zero, and probe failures are never converted into reset+/// authorization.+fn live_node_docs(es: &Es, brain: &str) -> Result<Option<u64>> {let edges_index = detect::edges_index_name(brain);- let Ok(Some(meta)) = es.get_doc(&edges_index, detect::BRAIN_META_ID) else {- return 0;+ let Some(meta) = es.get_doc(&edges_index, detect::BRAIN_META_ID)? else {+ return Ok(None);};// `Es::get_doc` returns the document `_source` itself.let Some(nodes_index) = meta@@ -404,15 +391,46 @@ fn live_node_docs(es: &Es, brain: &str) -> u64 {.and_then(Value::as_str).filter(|s| !s.is_empty())else {- return 0;+ bail!(+ "brain metadata {edges_index}/{} has no usable nodes_index",+ detect::BRAIN_META_ID+ );};- es.search(+ let response = es.search(nodes_index,&json!({"size": 0, "track_total_hits": true, "query": {"match_all": {}}}),+ )?;+ response+ .pointer("/hits/total/value")+ .and_then(Value::as_u64)+ .map(Some)+ .context("node-count response has no numeric hits.total.value")+}++fn journal_server_disagreement(cfg: &BrainCfg, brain: &str) -> String {+ let root = std::fs::canonicalize(&cfg.root).unwrap_or_else(|_| cfg.root.clone());+ let state_dir =+ xerj_autoindex::state::default_state_dir(&root.to_string_lossy(), &cfg.url, "ax");+ format!(+ "the resume journal and server disagree: journal {} says {} is already indexed, \+ but {} has no confirmed live node documents for prefix ax and brain {brain}. No reset \+ was attempted: an absent or zero node probe does not prove that data, catalog, and \+ graph namespaces are empty. Restore the server data directory used by this journal. \+ Otherwise, after validating or cleaning the old destination, run an isolated rebuild:\n\+ xerj autoindex {} --url {} --state-dir <new-state-dir> --prefix <new-prefix> \+ --brain <new-brain>\n\+ For a secured endpoint, set XERJ_API_KEY or add --api-key without placing its value in \+ logs. Validate the new target before switching readers",+ state_dir.display(),+ root.display(),+ cfg.url,+ root.display(),+ cfg.url,)- .ok()- .and_then(|v| v.pointer("/hits/total/value").and_then(Value::as_u64))- .unwrap_or(0)+}++fn journal_server_disagrees(files_indexed: u64, live_nodes: Option<u64>, fresh: bool) -> bool {+ files_indexed > 0 && matches!(live_nodes, None | Some(0)) && !fresh}fn index_cfg(cfg: &BrainCfg, brain: &str, api_key: Option<String>) -> IndexCfg {@@ -665,6 +683,40 @@ mod tests {assert_eq!(cfg.url, "http://localhost:9200");}+ #[test]+ fn journal_server_disagreement_refuses_reset_with_executable_recovery() {+ let cfg = BrainCfg {+ root: PathBuf::from("/corpus/notes"),+ brain: Some("team-notes".into()),+ url: "http://localhost:9200".into(),+ data_dir: None,+ api_key: None,+ fresh: false,+ no_open: true,+ };+ let message = journal_server_disagreement(&cfg, "team-notes");+ assert!(message.contains("resume journal and server disagree"));+ assert!(message.contains("No reset was attempted"));+ assert!(message.contains("http://localhost:9200"));+ assert!(message.contains("prefix ax"));+ assert!(message.contains("brain team-notes"));+ assert!(message.contains("xerj autoindex /corpus/notes"));+ assert!(message.contains("--url http://localhost:9200"));+ assert!(message.contains("--state-dir <new-state-dir>"));+ assert!(message.contains("--prefix <new-prefix>"));+ assert!(message.contains("--brain <new-brain>"));+ assert!(message.contains("XERJ_API_KEY"));+ }++ #[test]+ fn disagreement_decision_refuses_absent_and_zero_but_not_positive_server_truth() {+ assert!(journal_server_disagrees(1, None, false));+ assert!(journal_server_disagrees(1, Some(0), false));+ assert!(!journal_server_disagrees(1, Some(7), false));+ assert!(!journal_server_disagrees(0, Some(0), false));+ assert!(!journal_server_disagrees(1, Some(0), true));+ }+#[test]fn setup_link_is_scraped_from_bordered_and_bare_banner_lines() {let dir = std::env::temp_dir().join(format!("xerj-brain-test-{}", std::process::id()));diff --git a/landing/docs/recipes/zero-config-autoindex.html b/landing/docs/recipes/zero-config-autoindex.htmlindex 1a91d3f6a..86d843b23 100644--- a/landing/docs/recipes/zero-config-autoindex.html+++ b/landing/docs/recipes/zero-config-autoindex.html@@ -239,7 +239,7 @@ live indices at http://localhost:9280:ax-docs 1 docsax-exports 800 docsautoindex-catalog 9 docs</pre>- <p><code class="inline">--fresh</code> ignores the journal and restarts (ids stay idempotent).</p>+ <p><code class="inline">--fresh</code> starts without resume state only when the selected state directory has no durable plan; it never removes stale destination records. For an independent rebuild, use a new <code class="inline">--state-dir</code>, new <code class="inline">--prefix</code>, and new <code class="inline">--brain</code> when graph detection is enabled (or add <code class="inline">--no-graph</code>). Validate before switching readers. The shared <code class="inline">autoindex-catalog</code> and old target require explicit, validated cleanup. Added or removed content groups are refused; same-path replacement remains supported.</p><hr>diff --git a/landing/llms-full.txt b/landing/llms-full.txtindex 4325807e8..301c382f4 100644--- a/landing/llms-full.txt+++ b/landing/llms-full.txt@@ -140,8 +140,16 @@ destabilize the server.xerj autoindex map [--url U] [--json] [--dataset SLUG]xerj autoindex status [--url U] [--state-dir P]+--fresh starts without resume state only when the selected state directory has+no durable plan. It never removes stale destination records. An independent+rebuild requires a new --state-dir, new --prefix, and new --brain when graph+detection is enabled (or --no-graph), followed by validation before switching+readers. The shared autoindex-catalog and old target require explicit,+validated cleanup. Added or removed content groups are refused; same-path+replacement remains supported.+Exit codes: 0 complete · 3 completed-with-junk (junk recorded, never fatal) ·-2 usage · 1 endpoint unreachable / journal-config mismatch.+2 usage · 1 endpoint/journal error or refused unsafe corpus-state transition.Pipeline: walk → sniff → sample → infer → map → extract → bulk → correlate →catalog → verify.