AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.
Rust agent-memoryai-agentsbm25claude-codeclicode-searchcursordatabaseelasticsearchfull-text-searchhybrid-searchjsonllocal-firstmcpmcp-servermodel-context-protocolragrustsearch-enginevector-search
feat(#977): port the reference-coding loop into the binary — xerj code, xerj corpus, xerj_code_search MCP
xerj-orgbb6418b32cb8
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 0f5d5b2aa..fdbd4fa59 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -78,50 +78,47 @@ jobs:reference-coding:name: Reference-coding toolkitruns-on: ubuntu-latest- timeout-minutes: 15+ timeout-minutes: 25steps:- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0- - name: Shell syntax+ # Issue #977: the xc.py/xc-index.sh/xc-corpus.sh wrapper scripts are now+ # `xerj code` + `xerj corpus` + the xerj_code_search MCP tool, so the+ # toolkit's contracts are gated where the code lives — scoped cargo+ # tests, same profile as every other engine job.+ - name: Rust toolchain+ uses: dtolnay/rust-toolchain@stable++ - name: Cached cargo build+ uses: Swatinem/rust-cache@v2+ with:+ workspaces: engine++ # The contracts the old script tests pinned, now in Rust:+ # xerj-common::xccode - staleness refusal, RESTRICTED licence+ # warning, exit triangle, hybrid shape,+ # passage selection, state ledger+ # xerj-autoindex::xc - corpus lifecycle, path gate, usage+ # xerj-mcp - tool schema presence + isError mapping+ # xerj-server - subcommand dispatch + help text+ - name: Toolkit tests+ working-directory: enginerun: |- for f in tools/xerj-code/scripts/*.sh tools/xerj-code/tests/*.sh; do- bash -n "$f"- done- python3 -m py_compile tools/xerj-code/scripts/xc.py \- tools/xerj-code/tests/validate_manifest.py \- tools/xerj-code/tests/test_xc_index_fresh.py \- tools/xerj-code/tests/test_state_ledger.py+ cargo test --profile ci-test -p xerj-common -p xerj-autoindex -p xerj-mcp -p xerj-server \+ xccode xc_ published_schema help_text# The corpus manifests are the shareable artifact (issue #319): if they# cannot rebuild a corpus, publishing them is worse than not shipping- # them. Offline — the fixtures are local git repos served over file://.- - name: Corpus manifest round-trip- run: tools/xerj-code/tests/test_xc_corpus.sh-- - name: Matching passage window regressions- run: python3 tools/xerj-code/tests/test_passage_window.py-- - name: Retrieval output and state-ledger regressions- run: python3 tools/xerj-code/tests/test_state_ledger.py-+ # them. The same untrusted-input gate `xerj corpus add --from` enforces+ # now runs as a Rust test (xccode::manifest::hub_manifests_pass_the_untrusted_input_gate).- name: Vetted hub manifests validate- run: python3 tools/xerj-code/tests/validate_manifest.py --hub tools/xerj-code/hub/*.json-- # #930: `xc-index.sh <corpus> --fresh` failed on every corpus that had been- # indexed before, and nothing ran the script, so nothing noticed. Offline:- # a fake node and a fake `xerj` that refuses exactly what the real one- # refuses. Pins build-verify-swap: the old index is never deleted before- # the replacement has a count > 0, and never by wildcard.- - name: xc-index --fresh builds beside, verifies, then swaps- run: python3 tools/xerj-code/tests/test_xc_index_fresh.py-- # xc.py's prefix resolution changed with #930 (it queries the verified- # build, not the whole namespace), so its ledger guard is gated too.- - name: xc.py state-ledger guard- run: python3 tools/xerj-code/tests/test_state_ledger.py-- - name: Hybrid retrieval transport fallback- run: python3 tools/xerj-code/tests/test_hybrid_fallback.py+ working-directory: engine+ run: cargo test --profile ci-test -p xerj-common xccode::manifest++ # The published MCP schema must match the served tools byte-for-byte;+ # regenerating it is scripts/mcp-schema-check.sh --write.+ - name: Published MCP schema drift+ run: ./scripts/mcp-schema-check.sh# #489: this script existed, worked, and had been failing locally for three# releases — the version footer, headline and narrative on landing/index.htmldiff --git a/AGENTS.md b/AGENTS.mdindex 3cddacb41..751f33484 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -61,7 +61,7 @@ cannot push at all: [.github/AI_CONTRIBUTIONS.md](./.github/AI_CONTRIBUTIONS.md)## Ground rules for working in this repo- **Honest claims only.** Every public number traces to a verified run. The **default** embedding mode is *lexical* feature-hashing — never claim the default mode does neural/semantic understanding. A built-in **neural** BERT embedder ships in the binary but is **off unless activated** (`--embed-mode neural`, model auto-downloads on first use); only describe output as neural when that mode is actually running. kNN: unfiltered queries are HNSW-served with exact rescoring — recall is *measured* (recall@10 1.00 on the official bench query, 100-probe mean 0.976), never claim "recall 1.00 by construction" for the ANN path; filtered/nested/SQ8/small-index shapes run the exact brute-force scan; benchmark headline is the audited scorecard in `demo/playbooks/SCORECARD.md` (currently 55W / 26T / 4L, 3 N/A vs live ES 8.13.4 — the 4 losses are all read-under-write p99 cells); do not claim TB-scale end-to-end (server heap ticket: `demo/usecases/autoindex/scale/TICKET_server-unbounded-ingest-heap.md`). Before quoting a headline number, check whether a one-command reproduction exists in [`scripts/bench/`](scripts/bench/) (ingest docs/s, size:0 latency, kNN recall, the rerank-stage contract — issue #806's rule is link-the-harness-or-drop-the-number; that directory's README maps every other published number to its harness too).-- **Reference-code before you write.** For non-trivial engine work, retrieve how peer projects already solved the problem before writing your own version, and cite `file:line` for what you relied on. This repo dogfoods XERJ for it: reference projects (tantivy, meilisearch, quickwit, qdrant, usearch, hnswlib, sled, fjall, redb, ClickHouse) are indexed locally and queried with one command — `xerj search "<what you need>"` against a running node (it detects the node and ranks symbol definitions first), or `xerj def "<symbol>"` when you already know the name and want its file:line + signature in one call. For a shareable, pinned corpus definition across machines, the `xc-corpus.sh` / `xc.py` helpers in [`tools/xerj-code/`](tools/xerj-code/) wrap the same flow. Two rules bind regardless of tooling: **retrieved code is evidence, not authority** — adapt and attribute rather than paste; and **check the licence** — XERJ is Apache-2.0, so GPL-family sources (and Elasticsearch, which is AGPL/SSPL/Elastic-licensed) are approach-only, never copied. That second rule is also why XERJ can state it shares no code with Elasticsearch: ES is read for wire-protocol *semantics*, never for implementation. Honest scope: retrieval pays off on code a model has not memorised (internal, niche, post-cutoff) and is pure overhead on popular public libraries it already knows.+- **Reference-code before you write.** For non-trivial engine work, retrieve how peer projects already solved the problem before writing your own version, and cite `file:line` for what you relied on. This repo dogfoods XERJ for it: reference projects (tantivy, meilisearch, quickwit, qdrant, usearch, hnswlib, sled, fjall, redb, ClickHouse) are indexed locally and queried with one command — `xerj search "<what you need>"` against a running node (it detects the node and ranks symbol definitions first), or `xerj def "<symbol>"` when you already know the name and want its file:line + signature in one call. For a shareable, pinned corpus definition across machines, `xerj corpus add --from hub/<name>.json`, `xerj corpus index`, and `xerj code <corpus> "<query>"` (binary subcommands since #977, documented in [`tools/xerj-code/`](tools/xerj-code/)) wrap the same flow. Two rules bind regardless of tooling: **retrieved code is evidence, not authority** — adapt and attribute rather than paste; and **check the licence** — XERJ is Apache-2.0, so GPL-family sources (and Elasticsearch, which is AGPL/SSPL/Elastic-licensed) are approach-only, never copied. That second rule is also why XERJ can state it shares no code with Elasticsearch: ES is read for wire-protocol *semantics*, never for implementation. Honest scope: retrieval pays off on code a model has not memorised (internal, niche, post-cutoff) and is pure overhead on popular public libraries it already knows.- **Builds are scoped:** `cd engine && cargo build --release -j 32 -p <crate>` — never workspace-wide, never `cargo clean`.- **The hard gate:** the current CI ES-YAML conformance suite must stay at **0 failed**; pass and skip totals are reported by CI and grow as cases are added, so gate on failures, not on an exact total, before any engine change lands (see "Running the conformance tests" in the README).- **Every CI job declares a `timeout-minutes`.** A job without one runs against GitHub's 360-minute default, and three of this repo's workflows serialise on a concurrency group that never auto-cancels — so one hung job holds that slot for hours and every later run queues behind it — during #751 one hung `Build + Test` ran into that 360-minute default, and a second hang the same morning discarded seven consecutive `main` pushes without running a single job. `python3 .github/scripts/workflow-timeout-guard.py` enforces it and runs as a merge gate; size a new job's cap from what the job actually measures, generously — a cap that false-fails a slow-but-healthy run is worse than the hang it guards against.@@ -151,13 +151,17 @@ do not inherit a shell `PATH`. Add `"XERJ_AUTH": "ApiKey <key>"` when the nodeis not running `--insecure` — the key is `<data-dir>/admin.key`. `--url` and`--auth` flags override the two environment variables.-Ten tools: `xerj_search`, `xerj_semantic_search`, `xerj_vector_search`,+Eleven tools: `xerj_search`, `xerj_semantic_search`, `xerj_vector_search`,`xerj_hybrid_search`, `xerj_memory_store`, `xerj_memory_recall`,-`xerj_brain_overview`, `xerj_brain_ego`, `xerj_brain_link`, `xerj_brain_unlink`.-Each is a *thin proxy*: it builds exactly the request the ES-compatible surface-already accepts and hands back whatever the engine returned, errors and refusals-verbatim. It adds no capability of its own — so anything you can do over MCP you-can also do with `curl`, and vice versa.+`xerj_brain_overview`, `xerj_brain_ego`, `xerj_brain_link`, `xerj_brain_unlink`,+`xerj_code_search`. The first ten are each a *thin proxy*: they build exactly+the request the ES-compatible surface already accepts and hand back whatever the+engine returned, errors and refusals verbatim — no capability of their own, so+anything you can do over MCP you can also do with `curl`, and vice versa. The+eleventh, `xerj_code_search` (#977), is deliberately not a thin proxy: it runs+the `xerj code` reference-coding pipeline ([`tools/xerj-code/`](tools/xerj-code/))+— staleness refusal, licence warnings, no-match-as-guidance — and returns its+rendered text rather than a raw response.Two honesty notes that bind how you describe results: `xerj_semantic_search`embeds server-side with the **lexical feature-hashing** embedder unless the nodediff --git a/CHANGELOG.md b/CHANGELOG.mdindex c5adc4349..0a8678262 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,48 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Added++- **`xerj code` and `xerj corpus add|index|list` — the reference-coding loop+ is in the binary ([#977](https://github.com/xerj-org/xerj/issues/977)).**+ `xerj code <corpus> "<query>"` retrieves the matching definition from a+ locally indexed corpus of peer projects (`-k`, `--lang`, `--mode+ bm25|semantic|hybrid`, `--full`, `--no-symbol`, `--meatl`, `--json`,+ `--stale-ok`, `--url`, `--api-key`), keeping the wrapper scripts' exit+ triangle: `0` hits, `1` no-match (including `--json` with empty hits),+ `2` usage/transport/30-day-staleness refusal, `3` corpus-in-ledger-but-not-+ loaded-on-this-node. `xerj corpus add` clones (or rebuilds from a pinned+ manifest via `--from`, preserving `review` blocks), detects licences with+ the restrictive-first heuristics and warns on approach-only sources;+ `xerj corpus index` is the #930 build-verify-swap (unverified builds are+ removed by exact name, an uncountable old index is never presumed empty,+ state switches by atomic rename only after `_count > 0`); `xerj corpus+ list` shows what is actually loaded on the node. Hybrid retrieval now fuses+ server-side — one native top-level `hybrid` query, RRF `k=60`, aimed at the+ semantic-capable indices, with an arms-ran note on every run. Existing+ `~/.xerj-code` corpora, state files and indexes work unchanged: same layout,+ same `corpus.json` schema, same `xc-<corpus>` namespaces. The `xerj_code_search`+ MCP tool (the 11th) exposes the same pipeline to shell-less agents, with+ `licence_policy: "strict"` stripping passage text from restricted-licence+ hits. No `python3`/`curl` dependency remains; `git` still is one (for+ `xerj corpus add`). Semantics live in the new `xerj-common::xccode` pure+ core, shared byte-for-byte by the CLI prose and the MCP tool text.++### Removed++- `tools/xerj-code/scripts/{xc.py,xc-index.sh,xc-corpus.sh}` and their+ Python/shell test suites. Most behaviour is ported and gated by scoped cargo+ tests (`xerj-common::xccode`, `xerj-autoindex::xc`, the MCP schema drift+ test); one suite is NOT yet re-pinned: the 81-check `--fresh` swap contract+ (fake node + fake binary) that guarded the destructive side of+ `xerj corpus index --fresh` — its logic moved to+ `xerj-autoindex/src/xc.rs` but needs the HTTP shell and autoindex runner+ injected before it can run against fakes+ ([#1004](https://github.com/xerj-org/xerj/issues/1004)). The deliberate+ drops are the post-query field-report nudge (2026-09-18 llms.txt directive:+ no obligation language) and per-hit hybrid arm annotations (server-side RRF+ exposes no per-leg ranks).+## [1.0.0-rc.75] - 2026-09-20### Addeddiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 9b9c361db..8dd55f3cc 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -98,7 +98,7 @@ Two rules bind regardless of how you do the reading:- **Retrieved code is evidence, not authority.** A passage shows how *that* project solved the problem under *its* constraints, which are not automatically ours. Adapt and attribute; do not paste.- **Check the licence first.** XERJ is Apache-2.0. Some relevant projects are not compatible with copying — Sonic is GPL, and Elasticsearch is AGPL/SSPL/Elastic-licensed. You may study the *approach*, but their code must not land here. For Elasticsearch there is a second reason: XERJ states publicly that it shares no code with ES, and that has to stay true — read it for wire-protocol semantics, never for implementation. When in doubt, write your own implementation from the design, or ask in the PR.-If you use an AI coding assistant, this step is where it earns its keep: retrieving the real implementation is far more reliable than letting the model re-derive an algorithm across retry loops. Maintainers dogfood XERJ itself for this — reference repositories are indexed locally and queried with `xerj autoindex` plus the helper scripts in [`tools/xerj-code/`](tools/xerj-code/). Pinned, licence-reviewed definitions of the corpora we use are in [`tools/xerj-code/hub/`](tools/xerj-code/hub/), so `xc-corpus.sh --from hub/<name>.json` gives you the same commits we read. That setup is convenience, not a requirement for contributing; reading the upstream source directly satisfies the same rule.+If you use an AI coding assistant, this step is where it earns its keep: retrieving the real implementation is far more reliable than letting the model re-derive an algorithm across retry loops. Maintainers dogfood XERJ itself for this — reference repositories are indexed locally and retrieved with the `xerj code` / `xerj corpus` subcommands documented in [`tools/xerj-code/`](tools/xerj-code/). Pinned, licence-reviewed definitions of the corpora we use are in [`tools/xerj-code/hub/`](tools/xerj-code/hub/), so `xerj corpus add --from hub/<name>.json` gives you the same commits we read. That setup is convenience, not a requirement for contributing; reading the upstream source directly satisfies the same rule.## Git workflowdiff --git a/docs/case-studies/reference-coding/CASE_STUDY.md b/docs/case-studies/reference-coding/CASE_STUDY.mdindex f34dfceb7..06c9fb18d 100644--- a/docs/case-studies/reference-coding/CASE_STUDY.md+++ b/docs/case-studies/reference-coding/CASE_STUDY.md@@ -174,6 +174,11 @@ pins the exact commits these runs used) → `xc-index.sh` → `xc.py`. It needs`xerj` binary, `git` and `python3`. To point it at **your own** code, index yourrepo instead of a corpus — that is the real use case.+*(As of [#977](https://github.com/xerj-org/xerj/issues/977) these are binary+subcommands — `xerj corpus add --from`, `xerj corpus index`, `xerj code` — and+no longer need `python3`; the commands above are what was actually run at the+time of this study.)*+The **measurement harness** — the three-arm runner, the purpose-built referencelibraries, the hidden-test task specs — is **not** in this repository; only itsoutputs are (`data/results-*.json`, `generated/`). What it does, if you want todiff --git a/engine/crates/xerj-autoindex/src/esclient.rs b/engine/crates/xerj-autoindex/src/esclient.rsindex 5f895335c..8852e9bc5 100644--- a/engine/crates/xerj-autoindex/src/esclient.rs+++ b/engine/crates/xerj-autoindex/src/esclient.rs@@ -1821,6 +1821,81 @@ impl Es {Ok(None)}}++ /// `GET /_cat/indices/{pattern}?format=json&h=index` as index names.+ ///+ /// The JSON sibling of [`Self::cat_indices`], which parses the TEXT form+ /// and is deliberately NOT retrofit — its callers depend on the text+ /// column layout. The engine honours `format=json` on this endpoint+ /// (`cat_indices_format_json_returns_a_real_json_array`), which is what+ /// the reference-coding loop counts live indices with. A 404 on a+ /// wildcard means "no such indices" -> `Ok(vec![])`; every other failure+ /// is `Err`: a node that cannot answer must never be reported as+ /// "0 live indices".+ pub fn cat_indices_json(&self, pattern: &str) -> Result<Vec<String>> {+ let path = format!("/_cat/indices/{pattern}?format=json&h=index");+ let (status, v) = self.request_json("GET", &path, None)?;+ match status {+ 200 => v+ .as_array()+ .map(|rows| {+ rows.iter()+ .filter_map(|r| r.get("index").and_then(Value::as_str))+ .map(str::to_string)+ .collect()+ })+ .ok_or_else(|| anyhow!("{path} returned non-array JSON")),+ 404 => Ok(Vec::new()),+ other => Err(anyhow!("{path} returned HTTP {other}: {v}")),+ }+ }++ /// Tri-state `GET /{pattern}/_count` — the #930 build-verify primitive.+ ///+ /// NOT [`Self::count`]: that is a `size:0` search pinned by its own+ /// comment, and verification needs exactly the `_count` endpoint's+ /// semantics, where 404 IS the answer "the wildcard matches no index, so+ /// zero records". The three states and the difference between the last+ /// two are the whole point:+ ///+ /// * `Number(n)` — the node counted them;+ /// * `Zero` — the node answered 404;+ /// * `Unknown` — the node DID NOT SAY (timeout, 5xx, refused, junk).+ ///+ /// "Did not say" used to be folded into 0 by every caller, and 0 is what+ /// authorises the destructive steps of a build swap. A node under memory+ /// pressure — the node a long build produces — answers exactly like that,+ /// so UNKNOWN authorises no delete and no swap, ever.+ pub fn count_endpoint(&self, pattern: &str) -> Count {+ let path = format!("/{pattern}/_count");+ let (status, v) = match self.request_json("GET", &path, None) {+ Ok(r) => r,+ Err(e) => return Count::Unknown(format!("{e:#}")),+ };+ match status {+ 200 => match v.get("count").and_then(Value::as_u64) {+ Some(n) => Count::Number(n),+ None => Count::Unknown(format!("no count in _count reply: {v}")),+ },+ 404 => Count::Zero,+ other => Count::Unknown(format!("{path} HTTP {other}: {v}")),+ }+ }+}++/// The tri-state answer of [`Es::count_endpoint`].+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum Count {+ Number(u64),+ Zero,+ /// The node did not say. NEVER to be treated as zero.+ Unknown(String),+}++impl Count {+ pub fn is_number(&self) -> bool {+ matches!(self, Count::Number(_))+ }}#[cfg(test)]diff --git a/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs b/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rsindex fcd311943..e24f1ef10 100644--- a/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs+++ b/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs@@ -4811,8 +4811,8 @@ fn a_refusal_is_on_the_progress_stream_and_the_terminal_line() {/// indexed, and the run must say exactly that — a committed generation with no/// documents, exit 3, every file accounted for as refused — rather than panic/// on an empty plan or, worse, report an empty corpus as a clean success. A-/// wrapper that verifies with `_count > 0` (xc-index.sh) then keeps its old-/// index, which is the right outcome.+/// wrapper that verifies with `_count > 0` (`xerj corpus index`) then keeps+/// its old index, which is the right outcome.#[test]fn refusing_every_dataset_commits_nothing_searchable_and_is_not_a_success() {let _guard = HTTP_E2E_LOCK.lock().unwrap_or_else(|p| p.into_inner());diff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rsindex a4a83da15..81c890934 100644--- a/engine/crates/xerj-autoindex/src/lib.rs+++ b/engine/crates/xerj-autoindex/src/lib.rs@@ -44,6 +44,7 @@ mod sync;mod sync_executor;pub mod walk;pub mod watch;+pub mod xc;use anyhow::{Context, Result};use serde::Serialize;@@ -1555,6 +1556,62 @@ pub fn run_cli() -> i32 {}}+/// In-process autoindex for the `xerj corpus` lifecycle (issue #977): builds+/// the same argv the wrapper script passed and routes it through the same+/// parse → run → error-route path as `run_cli`, so there is exactly ONE+/// autoindex behaviour.+///+/// The URL is resolved by the WRAPPER (`--url`/`XERJ_URL`) and passed+/// explicitly because `autoindex` itself deliberately ignores `XERJ_URL` (a+/// stale var must not redirect a write — see `cli.rs`). `--fresh` is never+/// forwarded: the build-verify-swap that replaces it lives in `xc.rs`.+pub fn run_with_options(+ dir: &std::path::Path,+ url: &str,+ prefix: &str,+ state_dir: Option<&std::path::Path>,+ no_graph: bool,+) -> i32 {+ let mut args = vec![+ dir.to_string_lossy().to_string(),+ "--url".to_string(),+ url.to_string(),+ "--prefix".to_string(),+ prefix.to_string(),+ ];+ if no_graph {+ args.push("--no-graph".to_string());+ }+ if let Some(sd) = state_dir {+ args.push("--state-dir".to_string());+ args.push(sd.to_string_lossy().to_string());+ }+ let cmd = match cli::parse(args) {+ Ok(c) => c,+ Err(e) => {+ eprintln!("error: {e}");+ return 2;+ }+ };+ let res = match cmd {+ Cmd::Index(cfg) => run_index(*cfg),+ _ => return 2,+ };+ match res {+ Ok(code) => code,+ Err(e) => {+ let route = route_cli_error(&e, false);+ if let Some(stdout) = route.stdout {+ println!("{stdout}");+ }+ if let Some(stderr) = route.stderr {+ eprintln!("{stderr}");+ }+ route.exit_code+ }+ }+}+const GB: u64 = 1 << 30;/// Junk entries that name a file which also reached `file_done`.diff --git a/engine/crates/xerj-autoindex/src/xc.rs b/engine/crates/xerj-autoindex/src/xc.rsnew file mode 100644index 000000000..62eebfdf2--- /dev/null+++ b/engine/crates/xerj-autoindex/src/xc.rs@@ -0,0 +1,1279 @@+//! `xerj code` and `xerj corpus` — the reference-coding loop ported into the+//! binary (issue #977; previously `tools/xerj-code/scripts/xc*.py|sh`).+//!+//! Everything semantic lives in [`xerj_common::xccode`]; this file is the CLI+//! shell: argv parsing in the house style (no clap), the [`XcHttp`]+//! implementation over this crate's blocking [`Es`] client, the git/clone+//! lifecycle (`xerj corpus add`), and the #930 build-verify-swap+//! (`xerj corpus index`). Exit codes: 0 hits / 1 no-match-or-incomplete /+//! 2 usage-transport-stale / 3 corpus-in-state-but-not-loaded-here.++use std::collections::HashMap;+use std::path::{Path, PathBuf};+use std::process::Command;++use anyhow::{Context, Result};+use serde_json::{json, Value};++use xerj_common::localauth::{discover_local_admin_key, url_is_loopback};+use xerj_common::xccode::{self, manifest, state, CodeOutcome, CodeParams, Mode, XcHttp};++use crate::esclient::{Count, Es};++// ── shared plumbing ─────────────────────────────────────────────────────────++/// `~/.xerj-code` unless `XERJ_CODE_HOME` says otherwise. Never `/tmp`:+/// corpora and state must persist across reboots.+pub fn code_root() -> PathBuf {+ if let Ok(home) = std::env::var("XERJ_CODE_HOME") {+ if !home.is_empty() {+ return PathBuf::from(home);+ }+ }+ let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());+ Path::new(&home).join(".xerj-code")+}++/// `--url` flag > `XERJ_URL` > `http://localhost:9200`. Unlike `autoindex`+/// (which ignores `XERJ_URL` on purpose for writes), these READ commands+/// honor it — the scripts always did.+fn resolve_url(explicit: Option<&str>) -> String {+ explicit+ .map(str::to_string)+ .or_else(|| std::env::var("XERJ_URL").ok().filter(|u| !u.is_empty()))+ .unwrap_or_else(|| "http://localhost:9200".to_string())+}++fn build_es(url: &str, api_key: Option<String>) -> Result<Es> {+ // Loopback admin-key fallback (#961/#962 patterns): announced, loopback-only.+ let key = match api_key {+ Some(k) => Some(k),+ None => {+ let env_key = std::env::var("XERJ_API_KEY").ok().filter(|k| !k.is_empty());+ match env_key {+ Some(k) => Some(k),+ None => {+ if url_is_loopback(url) {+ discover_local_admin_key().map(|(k, path)| {+ eprintln!(+ "xerj code: no --api-key/XERJ_API_KEY given; using the admin \+ key at {}",+ path.display()+ );+ k+ })+ } else {+ None+ }+ }+ }+ }+ };+ Es::new(url, key)+}++/// [`XcHttp`] over the blocking client.+struct EsXc<'a>(&'a Es);++impl XcHttp for EsXc<'_> {+ fn get_mapping(&self, path: &str) -> Result<Value, String> {+ self.0.get_json(path).map_err(|e| format!("{e:#}"))+ }+ fn cat_indices_json(&self, pattern: &str) -> Result<Vec<String>, String> {+ self.0+ .cat_indices_json(pattern)+ .map_err(|e| format!("{e:#}"))+ }+ fn search(&self, index: &str, body: &Value) -> Result<Value, String> {+ self.0.search(index, body).map_err(|e| format!("{e:#}"))+ }+}++fn emit(out: &CodeOutcome) {+ for w in &out.warnings {+ eprintln!("{w}");+ }+ // `--json` can be the ONLY output (empty text is normal for a machine+ // consumer): the JSON line must print even when text is empty, so the+ // guard covers the text arm only, never the json arm.+ if !out.text.is_empty() {+ if out.to_stderr {+ eprintln!("{}", out.text.trim_end());+ } else {+ print!("{}", out.text);+ }+ }+ if let Some(j) = &out.json {+ println!("{j}");+ }+}++// ── xerj code ───────────────────────────────────────────────────────────────++const CODE_USAGE: &str =+ "usage: xerj code <corpus> \"<what you need>\" [-k N] [--mode bm25|semantic|hybrid]+ [--hybrid] [--lang <lg>] [--full N] [--no-symbol] [--json] [--meatl] [--stale-ok]+ [--url URL] [--api-key KEY]++retrieval over a reference corpus (see `xerj corpus list`):+ -k N passages to return (default 5)+ --mode MODE bm25 (default, measured 12/12 top-3), semantic, or hybrid+ --hybrid shorthand for --mode hybrid+ --lang LG filter to one language field (e.g. rust, go)+ --full N max chars per passage (default 800; 0 = file head only)+ --no-symbol window selection instead of the matching definition+ --json raw server response on stdout+ --meatl machine-readable one-line-per-hit output+ --stale-ok override the 30-day staleness refusal+ --url URL node to query (default $XERJ_URL or http://localhost:9200)+ --api-key KEY API key (loopback falls back to <data_dir>/admin.key)";++/// `xerj code …` — returns the process exit code.+pub fn run_code_cli(args: &[String]) -> i32 {+ let mut corpus: Option<String> = None;+ let mut query: Option<String> = None;+ let mut url: Option<String> = None;+ let mut api_key: Option<String> = None;+ let mut p = CodeParams::new("", "");+ let mut i = 0;+ let bad = |msg: String| -> i32 {+ eprintln!("{msg}\n");+ eprintln!("{CODE_USAGE}");+ 2+ };+ while i < args.len() {+ let a = &args[i];+ macro_rules! val {+ ($name:expr) => {+ match args.get(i + 1) {+ Some(v) => {+ i += 1;+ v.clone()+ }+ None => return bad(format!("xerj code: {} needs a value", $name)),+ }+ };+ }+ match a.as_str() {+ "-h" | "--help" => {+ println!("{CODE_USAGE}");+ return 0;+ }+ "-k" => {+ let v = val!("-k");+ match v.parse::<usize>() {+ Ok(n) if (1..=50).contains(&n) => p.k = n,+ _ => return bad(format!("xerj code: -k must be 1..=50, got '{v}'")),+ }+ }+ "--lang" => p.lang = Some(val!("--lang")),+ "--mode" => {+ let v = val!("--mode");+ match Mode::parse(&v) {+ Some(m) => p.mode = m,+ None => return bad(format!("xerj code: unknown mode '{v}'")),+ }+ }+ "--hybrid" => p.mode = Mode::Hybrid,+ "--full" => {+ let v = val!("--full");+ match v.parse::<usize>() {+ Ok(n) => p.full = n,+ _ => return bad(format!("xerj code: --full must be a number, got '{v}'")),+ }+ }+ "--no-symbol" => p.no_symbol = true,+ "--json" => p.as_json = true,+ "--meatl" => p.meatl = true,+ "--stale-ok" => p.stale_ok = true,+ "--url" => url = Some(val!("--url")),+ "--api-key" => api_key = Some(val!("--api-key")),+ _ if a.starts_with('-') => {+ return bad(format!("xerj code: unknown flag '{a}'"));+ }+ _ => {+ if corpus.is_none() {+ corpus = Some(a.clone());+ } else if query.is_none() {+ query = Some(a.clone());+ } else {+ return bad(format!("xerj code: unexpected argument '{a}'"));+ }+ }+ }+ i += 1;+ }+ let (Some(corpus), Some(query)) = (corpus, query) else {+ return bad("xerj code: both <corpus> and \"<query>\" are required".to_string());+ };+ let url = resolve_url(url.as_deref());+ let es = match build_es(&url, api_key) {+ Ok(es) => es,+ Err(e) => {+ eprintln!("xerj code: cannot reach {url}: {e:#}");+ return 2;+ }+ };+ p.corpus = corpus;+ p.query = query;+ let out = xccode::run_code_query(&code_root(), &EsXc(&es), &url, &p, "`--stale-ok`");+ emit(&out);+ out.exit+}++// ── xerj corpus add ─────────────────────────────────────────────────────────++const CORPUS_USAGE: &str =+ "usage: xerj corpus add <name> <git-url>... | --from <manifest.json> [--as <name>]+ xerj corpus index <name> [--fresh] [--url URL]+ xerj corpus list [--url URL]++clone the repos, detect licences, write corpora/<name>/corpus.json;+--from takes the corpus name from the manifest's 'corpus' field unless+<name> or --as overrides it; index builds/verifies/switches the corpus+(exit 3 skips junk — normal); list shows what is loaded on this node.";++fn git(dir: Option<&Path>, args: &[&str]) -> Result<(i32, String)> {+ let mut c = Command::new("git");+ if let Some(d) = dir {+ c.current_dir(d).arg("-C").arg(d);+ }+ let out = c+ .args(args)+ .output()+ .with_context(|| format!("run git {}", args.first().unwrap_or(&"")))?;+ Ok((+ out.status.code().unwrap_or(-1),+ String::from_utf8_lossy(&out.stdout).trim().to_string()+ + String::from_utf8_lossy(&out.stderr).trim(),+ ))+}++/// Move a clone to `sha` (shallow). Never a shell string: the sha comes from+/// an untrusted manifest, and `Command` passes it as ONE argv element.+fn checkout_at_sha(target: &Path, url: &str, sha: &str) -> Result<()> {+ if !target.join(".git").exists() {+ std::fs::create_dir_all(target)?;+ git(Some(target), &["init", "--quiet"])?;+ git(Some(target), &["remote", "add", "origin", url]).ok();+ git(Some(target), &["config", "remote.origin.promisor", "true"]).ok();+ git(+ Some(target),+ &["config", "remote.origin.partialclonefilter", "blob:none"],+ )+ .ok();+ }+ let fetch = git(Some(target), &["fetch", "--depth", "1", "origin", sha]);+ if !fetch.map(|(rc, _)| rc == 0).unwrap_or(false) {+ anyhow::bail!("git fetch {sha} failed");+ }+ let co = git(+ Some(target),+ &["checkout", "--quiet", "--force", "--detach", sha],+ );+ if !co.map(|(rc, _)| rc == 0).unwrap_or(false) {+ anyhow::bail!("git checkout {sha} failed");+ }+ git(Some(target), &["clean", "-qfd"]).ok();+ Ok(())+}++fn dir_stats(target: &Path) -> (String, u64, u64) {+ let sha = git(Some(target), &["rev-parse", "HEAD"])+ .ok()+ .filter(|(rc, _)| *rc == 0)+ .map(|(_, out)| out)+ .unwrap_or_else(|| "unknown".to_string());+ let mut files = 0u64;+ let mut bytes = 0u64;+ fn walk(dir: &Path, files: &mut u64, bytes: &mut u64) {+ let Ok(entries) = std::fs::read_dir(dir) else {+ return;+ };+ for e in entries.flatten() {+ let p = e.path();+ if p.file_name().map(|n| n == ".git").unwrap_or(false) {+ continue;+ }+ if p.is_dir() {+ walk(&p, files, bytes);+ } else if let Ok(md) = e.metadata() {+ *files += 1;+ *bytes += md.len();+ }+ }+ }+ walk(target, &mut files, &mut bytes);+ (sha, files, bytes)+}++/// Corpus-name resolution for `add`: an explicit <name> (positional, then+/// `--as`) wins; otherwise the manifest's own `corpus` field supplies it.+/// `--from` with neither is a usage error, not a guess.+fn resolve_corpus_name(+ explicit: Option<String>,+ hub_corpus: &str,+ path: &str,+) -> Result<String, String> {+ explicit+ .or_else(|| (!hub_corpus.is_empty()).then(|| hub_corpus.to_string()))+ .ok_or_else(|| {+ format!("{path} has no 'corpus' field and no <name>/--as was given\n\n{CORPUS_USAGE}")+ })+}++fn run_corpus_add(args: &[String]) -> i32 {+ let mut name: Option<String> = None;+ let mut as_name: Option<String> = None;+ let mut from: Option<String> = None;+ let mut urls: Vec<String> = Vec::new();+ let mut i = 0;+ while i < args.len() {+ match args[i].as_str() {+ "-h" | "--help" => {+ println!("{CORPUS_USAGE}");+ return 0;+ }+ "--from" => match args.get(i + 1) {+ Some(v) => {+ from = Some(v.clone());+ i += 1;+ }+ None => {+ eprintln!("xerj corpus add: --from needs a manifest path\n\n{CORPUS_USAGE}");+ return 2;+ }+ },+ "--as" => match args.get(i + 1) {+ Some(v) => {+ as_name = Some(v.clone());+ i += 1;+ }+ None => {+ eprintln!("xerj corpus add: --as needs a corpus name\n\n{CORPUS_USAGE}");+ return 2;+ }+ },+ a if a.starts_with('-') => {+ eprintln!("xerj corpus add: unknown flag '{a}'\n\n{CORPUS_USAGE}");+ return 2;+ }+ a => {+ if name.is_none() {+ name = Some(a.to_string());+ } else {+ urls.push(a.to_string());+ }+ }+ }+ i += 1;+ }+ // `--as` only renames a `--from` rebuild; a positional name wins when+ // both are given (it is the more explicit spelling of the same thing).+ let explicit_name = name.or(as_name);+ if from.is_none() && explicit_name.is_none() {+ eprintln!("xerj corpus add: <name> is required\n\n{CORPUS_USAGE}");+ return 2;+ }+ if from.is_none() && urls.is_empty() {+ eprintln!(+ "xerj corpus add: give at least one <git-url> or --from <manifest>\n\n{CORPUS_USAGE}"+ );+ return 2;+ }+ // The manifest is read BEFORE the name is finalised: with `--from` and+ // no explicit <name>/--as, the manifest's own 'corpus' field supplies+ // it. Everything downstream (dest, carry, entries) needs the resolved+ // name, so resolution lives here and nowhere else.+ let (name, rows): (String, Vec<(String, String, String, String)>) = if let Some(path) = &from {+ let hub = match manifest::read_hub_manifest(Path::new(path)) {+ Ok(h) => h,+ Err(e) => {+ eprintln!("xerj corpus add: {e}");+ return 2;+ }+ };+ let resolved = match resolve_corpus_name(explicit_name, &hub.corpus, path) {+ Ok(n) => n,+ Err(e) => {+ eprintln!("xerj corpus add: {e}");+ return 2;+ }+ };+ println!("rebuilding corpus '{resolved}' from {path}");+ (+ resolved,+ hub.rows+ .into_iter()+ .map(|r| (r.repo, r.url, r.sha, r.declared_licence))+ .collect(),+ )+ } else {+ let Some(resolved) = explicit_name else {+ eprintln!("xerj corpus add: <name> is required\n\n{CORPUS_USAGE}");+ return 2;+ };+ (+ resolved,+ urls.iter()+ .map(|u| {+ let repo = u+ .trim_end_matches('/')+ .rsplit('/')+ .next()+ .unwrap_or("")+ .trim_end_matches(".git")+ .to_string();+ (repo, u.clone(), String::new(), String::new())+ })+ .collect(),+ )+ };+ if let Err(e) = xccode::pathgate::valid_corpus_name(&name) {+ eprintln!("xerj corpus add: {e}");+ return 2;+ }++ let root = code_root();+ let dest = root.join("corpora").join(&name);+ if let Err(e) = std::fs::create_dir_all(&dest) {+ eprintln!("xerj corpus add: cannot create {}: {e}", dest.display());+ return 2;+ }++ // review{} blocks are PRESERVED across a rebuild when repo+sha match —+ // a human's licence review survives a re-clone (additive, never edited).+ let previous = manifest::read_corpus_manifest(&dest.join("corpus.json")).ok();+ let carry = |repo: &str, sha: &str| -> Option<Value> {+ let m = previous.as_ref()?;+ m.repos.iter().find_map(|r| {+ (r.repo == repo && r.sha == sha)+ .then(|| r.review.clone())+ .flatten()+ })+ };++ let mut entries: Vec<manifest::ManifestRepo> = Vec::new();+ let mut skipped: Vec<String> = Vec::new();++ for (repo_name, url, sha, declared) in rows {+ // The one destructive step (checkout --force + clean -fd) runs inside+ // this path: gate the name HERE, again, even though read_hub_manifest+ // already did — the plain-URL arm has no other gate.+ if xccode::pathgate::valid_repo_name(&repo_name).is_err() || repo_name.starts_with('-') {+ eprintln!(" [FAIL] refusing unsafe repo name '{repo_name}'");+ skipped.push(repo_name);+ continue;+ }+ let target = dest.join(&repo_name);+ if target.join(".git").exists() && !sha.is_empty() {+ let at = git(Some(&target), &["rev-parse", "HEAD"])+ .ok()+ .filter(|(rc, _)| *rc == 0)+ .map(|(_, out)| out);+ if at.as_deref() == Some(sha.as_str()) {+ println!(+ " [ok] {repo_name} already at {}",+ &sha[..12.min(sha.len())]+ );+ record(&mut entries, &repo_name, &url, &target, &declared, &carry);+ continue;+ }+ println!(" [pin] {repo_name} -> {}", &sha[..12.min(sha.len())]);+ if let Err(e) = checkout_at_sha(&target, &url, &sha) {+ eprintln!(" [FAIL] {repo_name}: {e:#}; continuing");+ skipped.push(repo_name);+ continue;+ }+ record(&mut entries, &repo_name, &url, &target, &declared, &carry);+ continue;+ }+ if target.join(".git").exists() {+ println!(" [skip] {repo_name} already cloned");+ record(&mut entries, &repo_name, &url, &target, &declared, &carry);+ 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;+ }+ }+ } else {+ println!(" [pin] {repo_name} -> {}", &sha[..12.min(sha.len())]);+ if let Err(e) = checkout_at_sha(&target, &url, &sha) {+ eprintln!(" [FAIL] {repo_name}: {e:#}; continuing");+ skipped.push(repo_name);+ continue;+ }+ }+ record(&mut entries, &repo_name, &url, &target, &declared, &carry);+ }++ if entries.is_empty() {+ eprintln!("xerj corpus add: nothing cloned");+ return 1;+ }++ // Regenerated FROM DISK, never copied through from the input.+ let cloned_at = chrono_now_stamp();+ let manifest_path = dest.join("corpus.json");+ manifest::write_corpus_manifest(&manifest_path, &name, &cloned_at, &entries);+ println!();+ println!(+ "corpus '{name}': {} repos at {}",+ entries.len(),+ dest.display()+ );+ println!(+ "share it: {} (rebuild with xerj corpus add <name> --from <that file>)",+ manifest_path.display()+ );++ if !skipped.is_empty() {+ eprintln!();+ eprintln!(+ "xerj corpus add: {} of {} repos did not land: {}",+ skipped.len(),+ entries.len() + skipped.len(),+ skipped.join(" ")+ );+ eprintln!("xerj corpus add: this corpus is INCOMPLETE — it is not the one the manifest describes.");+ return 1;+ }+ println!("next: xerj corpus index {name}");+ 0+}++fn record(+ entries: &mut Vec<manifest::ManifestRepo>,+ repo_name: &str,+ url: &str,+ target: &Path,+ declared: &str,+ carry: &dyn Fn(&str, &str) -> Option<Value>,+) {+ let lic = xccode::licence::detect_licence(target);+ let (sha, files, bytes) = dir_stats(target);+ println!(+ " licence={lic} sha={} files={files}",+ &sha[..12.min(sha.len())]+ );+ if let Some(w) = xccode::licence::clone_warning_line(&lic) {+ eprintln!("{w}");+ }+ // The detector is text-matching heuristics and has been wrong before.+ // When a manifest disagrees with the checkout, say so rather than+ // overwrite quietly.+ if !declared.is_empty() && declared != lic {+ eprintln!(" ! manifest says licence={declared}, checkout reads {lic} — verify before copying");+ }+ let review = carry(repo_name, &sha);+ entries.push(manifest::ManifestRepo {+ repo: repo_name.to_string(),+ url: url.to_string(),+ licence: lic,+ sha,+ files: Some(files),+ bytes: Some(bytes),+ review,+ });+}++fn chrono_now_stamp() -> String {+ chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string()+}++// ── xerj corpus index ───────────────────────────────────────────────────────++/// `count_under`: patiently. Still `None` when the node never answered —+/// callers must treat that as UNKNOWN, never as zero. The glob is the DASH+/// form `{prefix}-*` (verification), pinned against the STAR form the query+/// path uses — both are load-bearing and they are not interchangeable.+fn count_under(es: &Es, prefix: &str) -> Option<u64> {+ let tries = std::env::var("XC_COUNT_TRIES")+ .ok()+ .and_then(|v| v.parse::<u32>().ok())+ .unwrap_or(6);+ let pause = std::env::var("XC_COUNT_PAUSE")+ .ok()+ .and_then(|v| v.parse::<u64>().ok())+ .unwrap_or(5);+ for attempt in 1..=tries.max(1) {+ match es.count_endpoint(&format!("{prefix}-*")) {+ Count::Number(n) => return Some(n),+ Count::Zero => return Some(0),+ Count::Unknown(_) => {+ if attempt == tries.max(1) {+ return None;+ }+ std::thread::sleep(std::time::Duration::from_secs(pause));+ }+ }+ }+ None+}++/// Every index under `xc-<corpus>-` that belongs to THIS corpus. The bare+/// glob is not enough: `xc-battle-*` also matches the sibling corpus+/// `battle-terse`, and retiring a sibling's indices is not a mistake this+/// command gets to make.+fn corpus_indices(es: &Es, name: &str, root: &Path) -> Vec<String> {+ // Any error lists nothing, which errs toward KEEPING an index (nothing is+ // retired that was not listed), never toward deleting one.+ let rows = es+ .cat_indices_json(&format!("xc-{name}-*"))+ .unwrap_or_default();+ let mut siblings: Vec<String> = Vec::new();+ for (folder, strip) in [(root.join("corpora"), ""), (root.join("state"), ".json")] {+ if let Ok(entries) = std::fs::read_dir(&folder) {+ for e in entries.flatten() {+ let fname = e.file_name().to_string_lossy().to_string();+ let other = match strip {+ "" => fname,+ s if fname.ends_with(s) => fname[..fname.len() - s.len()].to_string(),+ _ => continue,+ };+ if other != name && other.starts_with(&format!("{name}-")) {+ siblings.push(format!("xc-{other}-"));+ }+ }+ }+ }+ rows.into_iter()+ .filter(|idx| {+ idx.starts_with(&format!("xc-{name}-"))+ && !siblings.iter().any(|s| idx.starts_with(s.as_str()))+ })+ .collect()+}++fn delete_indices(es: &Es, names: &[String]) -> usize {+ let mut failed = 0;+ for index in names {+ // Exact names only, never a wildcard.+ let ok = es+ .request_json("DELETE", &format!("/{index}"), None)+ .map(|(s, _)| (200..300).contains(&s))+ .unwrap_or(false);+ if !ok {+ failed += 1;+ eprintln!("xerj corpus index: could not delete {index}");+ }+ }+ failed+}++/// The catalog is one global index shared by every corpus on the node, so its+/// documents are removed by EXACT scope value: `corpus_scope` is a keyword,+/// and a `term` on a legacy analyzed `prefix` cannot equal a hyphenated value+/// at all — it under-deletes there, it never reaches a sibling corpus.+fn delete_catalog_scope(es: &Es, scope: &str) {+ let body = json!({+ "query": { "bool": { "minimum_should_match": 1, "should": [+ { "term": { "corpus_scope": scope } },+ { "term": { "prefix": scope } }+ ]}}+ });+ let ok = es+ .request_json(+ "POST",+ "/autoindex-catalog/_delete_by_query?refresh=true",+ Some(&body),+ )+ .map(|(s, _)| (200..300).contains(&s))+ .unwrap_or(false);+ if !ok {+ eprintln!(+ "xerj corpus index: could not clean autoindex-catalog for '{scope}' (harmless; \+ `xerj autoindex map` may list retired datasets)"+ );+ }+}++fn report(name: &str, rc: i32, docs: &str) {+ match rc {+ 0 => println!("indexed cleanly"),+ 3 => println!("indexed (exit 3: some files skipped as junk — normal for real repos)"),+ _ => {}+ }+ println!("corpus '{name}' searchable: {docs} records");+ println!("next: xerj code {name} \"<what you need>\"");+}++fn run_corpus_index(args: &[String]) -> i32 {+ let mut name: Option<String> = None;+ let mut fresh = false;+ let mut url: Option<String> = None;+ let mut i = 0;+ while i < args.len() {+ match args[i].as_str() {+ "-h" | "--help" => {+ println!("{CORPUS_USAGE}");+ return 0;+ }+ "--fresh" => fresh = true,+ "--url" => match args.get(i + 1) {+ Some(v) => {+ url = Some(v.clone());+ i += 1;+ }+ None => {+ eprintln!("xerj corpus index: --url needs a value\n\n{CORPUS_USAGE}");+ return 2;+ }+ },+ a if a.starts_with('-') => {+ eprintln!("xerj corpus index: unknown flag '{a}'\n\n{CORPUS_USAGE}");+ return 2;+ }+ a if name.is_none() => name = Some(a.to_string()),+ a => {+ eprintln!("xerj corpus index: unexpected argument '{a}'\n\n{CORPUS_USAGE}");+ return 2;+ }+ }+ i += 1;+ }+ let Some(name) = name else {+ eprintln!("xerj corpus index: <name> is required\n\n{CORPUS_USAGE}");+ return 2;+ };+ if let Err(e) = xccode::pathgate::valid_corpus_name(&name) {+ eprintln!("xerj corpus index: {e}");+ return 2;+ }+ let root = code_root();+ let dir = root.join("corpora").join(&name);+ if !dir.is_dir() {+ eprintln!(+ "xerj corpus index: no corpus '{name}' at {} — run `xerj corpus add {name} …` first",+ dir.display()+ );+ return 2;+ }+ let url = resolve_url(url.as_deref());+ let es = match build_es(&url, None) {+ Ok(es) => es,+ Err(e) => {+ eprintln!("xerj corpus index: cannot reach {url}: {e:#}");+ return 2;+ }+ };+ let state_file = root.join("state").join(format!("{name}.json"));+ let state_root = root.join("autoindex-state");+ let old = state::load_state(&root, &name).ok();+ let old_build = old.as_ref().and_then(|s| s.build.clone());+ let old_index_prefix = old.as_ref().and_then(|s| s.index_prefix.clone());+ let old_state_dir = old.as_ref().and_then(|s| s.state_dir.clone());+ let old_url = old.as_ref().and_then(|s| s.url.clone());++ // Which run is this? build (--fresh / first / ledger-names-a-build-this-+ // node-does-not-hold), update (reconcile the recorded build in place), or+ // legacy (a corpus indexed before builds existed).+ let mut mode = "legacy";+ let old_indices = corpus_indices(&es, &name, &root);+ if fresh {+ mode = "build";+ } else if old_build.is_some()+ && old_index_prefix.is_some()+ && old_state_dir+ .as_deref()+ .is_some_and(|d| Path::new(d).is_dir())+ && old_url.as_deref() == Some(url.as_str())+ {+ let live = count_under(&es, old_index_prefix.as_deref().unwrap_or(""));+ match live {+ Some(n) if n > 0 => mode = "update",+ _ => {+ println!(+ "xerj corpus index: state/ records build {} but {url} holds no records for \+ it — building it here",+ old_build.as_deref().unwrap_or("?")+ );+ mode = "build";+ }+ }+ } else if !state_file.exists() && old_indices.is_empty() {+ mode = "build"; // first index of this corpus: same path as --fresh+ }++ println!("indexing corpus '{name}' from {}", dir.display());++ // --no-graph: reference code needs ranked passages, not a relationship+ // map. --fresh is NEVER forwarded to autoindex: the wrapper owns the swap.+ let run_autoindex = |prefix: &str, state_dir: Option<&Path>| -> i32 {+ crate::run_with_options(&dir, &url, prefix, state_dir, true)+ };++ match mode {+ "build" => {+ // Listed BEFORE the build so "old" can never include what this+ // run creates.+ let old_indices = corpus_indices(&es, &name, &root);+ // One-second resolution: a second --fresh inside the same second+ // would reuse the prefix of the build it is replacing. The id+ // must be new — not the recorded build, not a state dir that+ // exists, not a prefix any live index already sits under.+ let mut build = format!("b{}", stamp_secs());+ while old_build.as_deref() == Some(build.as_str())+ || state_root.join(&name).join(&build).exists()+ || old_indices+ .iter()+ .any(|idx| idx.starts_with(&format!("xc-{name}-{build}")))+ {+ std::thread::sleep(std::time::Duration::from_secs(1));+ build = format!("b{}", stamp_secs());+ }+ let new_prefix = format!("xc-{name}-{build}");+ let new_state = state_root.join(&name).join(&build);+ // Is there a working index to protect? When the node cannot+ // count it, the answer is YES: presuming "none" is what lets a+ // failed build be kept over it and the old indices be retired.+ let mut has_working_index = false;+ if !old_indices.is_empty() {+ let counted = count_under(+ &es,+ old_index_prefix.as_deref().unwrap_or(&format!("xc-{name}")),+ );+ match counted {+ None => {+ has_working_index = true;+ eprintln!("xerj corpus index: the node did not answer a record count for the existing index; treating it as");+ eprintln!("xerj corpus index: a WORKING index — a failed build will not be kept over it.");+ println!("xerj corpus index: --fresh — building {new_prefix}-* beside the existing index (an unknown number of records);");+ }+ Some(n) => {+ if n > 0 {+ has_working_index = true;+ }+ println!("xerj corpus index: --fresh — building {new_prefix}-* beside the existing index ({n} records);");+ }+ }+ println!("xerj corpus index: the existing index stays live until the replacement has been verified");+ }+ let _ = std::fs::create_dir_all(&new_state);+ let rc = run_autoindex(&new_prefix, Some(&new_state));++ // VERIFY: rc in {0,3} AND a count the node actually gave > 0.+ let docs = count_under(&es, &new_prefix);+ let Some(docs) = docs else {+ // UNKNOWN is not EMPTY: it authorises no delete and no swap.+ eprintln!(+ "xerj corpus index: the node did not answer a record count for build {build};"+ );+ eprintln!("xerj corpus index: autoindex exit {rc}. It cannot be verified, so NOTHING was deleted and NOTHING");+ eprintln!("xerj corpus index: was switched: its indices ({new_prefix}-*) and its state directory are kept.");+ if has_working_index {+ eprintln!("xerj corpus index: the existing index was NOT touched and is still what `xerj code` serves.");+ eprintln!("xerj corpus index: When the node answers again, re-run with --fresh; the unverified build is");+ eprintln!("xerj corpus index: retired by the next build that verifies.");+ } else {+ let _ = state::write_state(+ &root,+ &name,+ &url,+ rc as i64,+ true,+ Some(&build),+ Some(&new_prefix),+ new_state.to_str(),+ );+ eprintln!("xerj corpus index: There is no other index for '{name}', so this build is recorded as UNVERIFIED");+ eprintln!("xerj corpus index: (`xerj code` will say so). Re-run xerj corpus index {name} to resume or confirm it.");+ }+ if rc != 0 && rc != 3 {+ return rc;+ }+ return 1;+ };+ let mut salvaged = false;+ let mut verified = false;+ match rc {+ 0 | 3 if docs > 0 => verified = true,+ _ => {+ // autoindex can abort in finalisation AFTER every document+ // was written (#367). Keep a complete, queryable index+ // when there is no working fallback — and never swap a+ // verified one out for it.+ if docs > 0 && !has_working_index {+ verified = true;+ salvaged = true;+ eprintln!("xerj corpus index: WARNING — autoindex exited {rc}, but this build wrote {docs} records and");+ eprintln!("xerj corpus index: there is no working index to fall back to. Recording it as indexed with");+ eprintln!("xerj corpus index: autoindex_exit={rc}; coverage is not guaranteed — please report the error above.");+ }+ }+ }+ if !verified {+ eprintln!("xerj corpus index: build {build} did not verify (autoindex exit {rc}, {docs} records).");+ // Remove only what THIS run created: the set-diff against the+ // pre-run listing, intersected with this build's prefix, BY+ // EXACT NAME — never a wildcard, never new_prefix itself.+ let after = corpus_indices(&es, &name, &root);+ let doomed: Vec<String> = after+ .into_iter()+ .filter(|idx| !old_indices.contains(idx))+ .filter(|idx| idx.starts_with(&format!("xc-{name}-{build}-")))+ .collect();+ delete_indices(&es, &doomed);+ delete_catalog_scope(&es, &new_prefix);+ let _ = std::fs::remove_dir_all(&new_state);+ if !old_indices.is_empty() {+ eprintln!("xerj corpus index: the existing index was NOT touched and is still what `xerj code` serves.");+ }+ if rc != 0 && rc != 3 {+ return rc;+ }+ return 1;+ }+ // Verified. Switch readers first, retire second: a crash between+ // the two leaves a duplicate, never a gap.+ let _ = state::write_state(+ &root,+ &name,+ &url,+ rc as i64,+ salvaged,+ Some(&build),+ Some(&new_prefix),+ new_state.to_str(),+ );+ let retire: Vec<String> = old_indices+ .iter()+ .filter(|idx| !idx.starts_with(&format!("xc-{name}-{build}")))+ .cloned()+ .collect();+ if !retire.is_empty() {+ println!("xerj corpus index: replacement verified ({docs} records) — retiring {} old indices", retire.len());+ if delete_indices(&es, &retire) > 0 {+ eprintln!("xerj corpus index: WARNING — some old indices could not be deleted. The corpus is healthy and");+ eprintln!("xerj corpus index: `xerj code` reads only {new_prefix}-*; delete the leftovers by name when the node allows.");+ }+ delete_catalog_scope(+ &es,+ old_index_prefix.as_deref().unwrap_or(&format!("xc-{name}")),+ );+ }+ // Earlier builds' state directories are dead weight once their+ // indices are gone.+ if state_root.join(&name).is_dir() {+ if let Ok(entries) = std::fs::read_dir(state_root.join(&name)) {+ for e in entries.flatten() {+ if e.file_name().to_string_lossy() != build {+ let _ = std::fs::remove_dir_all(e.path());+ }+ }+ }+ }+ report(&name, rc, &docs.to_string());+ 0+ }+ "update" => {+ let prefix = old_index_prefix.clone().unwrap_or_default();+ let sd = old_state_dir.clone().map(PathBuf::from).unwrap_or_default();+ let rc = run_autoindex(&prefix, Some(&sd));+ if rc != 0 && rc != 3 {+ eprintln!("xerj corpus index: updating build {} failed with exit {rc}. The index is unchanged.", old_build.as_deref().unwrap_or("?"));+ eprintln!("xerj corpus index: re-run with --fresh to build a replacement beside it (the existing index");+ eprintln!("xerj corpus index: stays live until the replacement verifies).");+ return rc;+ }+ let docs = count_under(&es, &prefix)+ .map(|n| n.to_string())+ .unwrap_or_else(|| "?".to_string());+ let _ = state::write_state(+ &root,+ &name,+ &url,+ rc as i64,+ false,+ old_build.as_deref(),+ Some(&prefix),+ old_state_dir.as_deref(),+ );+ report(&name, rc, &docs);+ 0+ }+ _ => {+ // Legacy: recorded before the run so a failure can tell "this run+ // wrote records" apart from "an earlier run's records are still+ // lying around" (salvaging the latter would date stale data to+ // now, which is worse than no index).+ let before_known = count_under(&es, &format!("xc-{name}"));+ let docs_before = before_known.unwrap_or(0);+ let rc = run_autoindex(&format!("xc-{name}"), None);+ let mut salvaged = false;+ let mut docs: Option<u64> = None;+ if rc != 0 && rc != 3 {+ docs = count_under(&es, &format!("xc-{name}"));+ if before_known.is_some() && docs.is_some_and(|d| d > docs_before) {+ salvaged = true;+ eprintln!("xerj corpus index: WARNING — autoindex exited {rc}, but this run wrote records");+ eprintln!("xerj corpus index: ({docs_before} -> {}). The corpus is queryable and is being", docs.unwrap_or(0));+ eprintln!("xerj corpus index: recorded as indexed, with autoindex_exit={rc} in its state file.");+ eprintln!("xerj corpus index: Coverage is not guaranteed — please report the error above.");+ } else {+ eprintln!("xerj corpus index: autoindex failed with exit {rc} and wrote no new records.");+ eprintln!("xerj corpus index: If the error above says the state directory cannot become generation");+ eprintln!("xerj corpus index: authority, or that --fresh is refused, run: xerj corpus index {name} --fresh");+ return rc;+ }+ }+ docs = docs.or_else(|| count_under(&es, &format!("xc-{name}")));+ let docs_s = docs+ .map(|n| n.to_string())+ .unwrap_or_else(|| "?".to_string());+ let _ = state::write_state(&root, &name, &url, rc as i64, salvaged, None, None, None);+ report(&name, rc, &docs_s);+ 0+ }+ }+}++fn stamp_secs() -> i64 {+ use std::time::{SystemTime, UNIX_EPOCH};+ SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .map(|d| d.as_secs() as i64)+ .unwrap_or(0)+}++// ── xerj corpus list ────────────────────────────────────────────────────────++fn run_corpus_list(args: &[String]) -> i32 {+ let mut url: Option<String> = None;+ let mut i = 0;+ while i < args.len() {+ match args[i].as_str() {+ "-h" | "--help" => {+ println!("{CORPUS_USAGE}");+ return 0;+ }+ "--url" => match args.get(i + 1) {+ Some(v) => {+ url = Some(v.clone());+ i += 1;+ }+ None => {+ eprintln!("xerj corpus list: --url needs a value\n\n{CORPUS_USAGE}");+ return 2;+ }+ },+ a => {+ eprintln!("xerj corpus list: unexpected argument '{a}'\n\n{CORPUS_USAGE}");+ return 2;+ }+ }+ i += 1;+ }+ let root = code_root();+ let state_dir = root.join("state");+ if !state_dir.is_dir() {+ eprintln!(+ "no state directory at {} — nothing has been indexed on this machine",+ state_dir.display()+ );+ return 2;+ }+ let url = resolve_url(url.as_deref());+ let es = match build_es(&url, None) {+ Ok(es) => es,+ Err(e) => {+ eprintln!("xerj corpus list: cannot reach {url}: {e:#}");+ return 2;+ }+ };+ let mut names: Vec<String> = std::fs::read_dir(&state_dir)+ .into_iter()+ .flatten()+ .flatten()+ .filter(|e| e.path().extension().is_some_and(|x| x == "json"))+ .filter_map(|e| {+ e.file_name()+ .to_string_lossy()+ .strip_suffix(".json")+ .map(str::to_string)+ })+ .collect();+ names.sort();+ let mut loaded = 0usize;+ for name in &names {+ let st = match state::load_state(&root, name) {+ Ok(st) => st,+ Err(e) => {+ println!("{name}: unreadable state ({e})");+ continue;+ }+ };+ let prefix = state::query_prefix(&st);+ let indexed = st+ .indexed_at+ .as_deref()+ .unwrap_or("?")+ .get(..10)+ .unwrap_or("?")+ .to_string();+ // Live count is honest: 404 -> 0; any other failure is named, never+ // faked as zero.+ let live = match es.cat_indices_json(&format!("{prefix}*")) {+ Ok(v) => v.len(),+ Err(_) => usize::MAX,+ };+ let uses = xccode::corpus_review_uses(&root, name);+ let use_note = uses+ .keys()+ .max()+ .and_then(|k| uses.get(k).map(|u| format!("\n use: {u}")))+ .unwrap_or_default();+ match live {+ usize::MAX => println!("{name} (indexed {indexed}, prefix {prefix}) — server unreachable/ambiguous at {url}"),+ 0 => println!("{name} (indexed {indexed}, prefix {prefix}) — NOT loaded here (0 indices) — stale/other-server{use_note}"),+ n => {+ loaded += 1;+ println!("{name} (indexed {indexed}, prefix {prefix}) — loaded — {n} index(es){use_note}");+ }+ }+ if let Some(w) = state::incomplete_coverage(&st) {+ println!(" {w}");+ }+ }+ println!();+ println!(+ "{} of {} corpora are actually loaded on {url}.",+ loaded,+ names.len()+ );+ 0+}++// ── dispatch ────────────────────────────────────────────────────────────────++/// `xerj corpus <add|index|list> …` — returns the process exit code.+pub fn run_corpus_cli(args: &[String]) -> i32 {+ let Some(sub) = args.first() else {+ eprintln!("{CORPUS_USAGE}");+ return 2;+ };+ let rest: Vec<String> = args[1..].to_vec();+ match sub.as_str() {+ "add" => run_corpus_add(&rest),+ "index" => run_corpus_index(&rest),+ "list" => run_corpus_list(&rest),+ "-h" | "--help" | "help" => {+ println!("{CORPUS_USAGE}");+ 0+ }+ other => {+ eprintln!("xerj corpus: unknown subcommand '{other}'\n\n{CORPUS_USAGE}");+ 2+ }+ }+}++/// The licence map for one corpus, shared with the MCP tool.+pub fn licence_map_for(root: &Path, corpus: &str) -> HashMap<String, String> {+ manifest::licence_map(root, corpus)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn corpus_names_are_gated_before_any_path_is_built() {+ for bad in ["a/b", "*", ".x", "index", "list"] {+ assert!(xccode::pathgate::valid_corpus_name(bad).is_err(), "{bad}");+ }+ assert!(xccode::pathgate::valid_corpus_name("battle-terse").is_ok());+ }++ #[test]+ fn url_resolution_prefers_flag_then_env_then_default() {+ assert_eq!(resolve_url(Some("http://a:1")), "http://a:1");+ // env-dependent branches covered by the e2e; default pinned here.+ std::env::remove_var("XERJ_URL");+ assert_eq!(resolve_url(None), "http://localhost:9200");+ }++ #[test]+ fn count_tries_env_defaults_are_the_scripts_values() {+ std::env::remove_var("XC_COUNT_TRIES");+ std::env::remove_var("XC_COUNT_PAUSE");+ // (6 tries, 5s pause) — pinned by the port; the env knobs still work.+ let t = std::env::var("XC_COUNT_TRIES")+ .ok()+ .and_then(|v| v.parse::<u32>().ok())+ .unwrap_or(6);+ assert_eq!(t, 6);+ }++ #[test]+ fn code_usage_lists_every_flag_the_design_names() {+ for f in [+ "-k",+ "--lang",+ "--mode",+ "--hybrid",+ "--full",+ "--no-symbol",+ "--json",+ "--meatl",+ "--stale-ok",+ "--url",+ "--api-key",+ ] {+ assert!(CODE_USAGE.contains(f), "{f} missing from usage");+ }+ assert!(CORPUS_USAGE.contains("--from"));+ }++ /// The `--from` name swap: explicit beats the manifest, the manifest+ /// beats nothing, and nothing is an error — never a guess.+ #[test]+ fn corpus_name_resolution_is_explicit_then_manifest_then_error() {+ let path = "hub.json";+ // explicit (positional or --as) wins over the manifest's field+ assert_eq!(+ resolve_corpus_name(Some("mine".into()), "theirs", path).as_deref(),+ Ok("mine")+ );+ // manifest supplies the name when nothing explicit was given+ assert_eq!(+ resolve_corpus_name(None, "theirs", path).as_deref(),+ Ok("theirs")+ );+ // neither: usage error naming both remedies+ let err = resolve_corpus_name(None, "", path).unwrap_err();+ assert!(err.contains("no 'corpus' field"), "{err}");+ assert!(err.contains("--as"), "{err}");+ }++ /// `--as` only renames; it must not let a bad name through — resolution+ /// output still passes the same pathgate as a positional name.+ #[test]+ fn corpus_name_resolution_output_is_still_pathgated() {+ assert!(xccode::pathgate::valid_corpus_name(+ &resolve_corpus_name(Some("a/b".into()), "theirs", "p").unwrap()+ )+ .is_err());+ // and the manifest's own field is gated at read time+ assert!(xccode::pathgate::valid_corpus_name(+ &resolve_corpus_name(None, "battle-terse", "p").unwrap()+ )+ .is_ok());+ }+}diff --git a/engine/crates/xerj-common/src/lib.rs b/engine/crates/xerj-common/src/lib.rsindex 78fe9344a..4c4ec4130 100644--- a/engine/crates/xerj-common/src/lib.rs+++ b/engine/crates/xerj-common/src/lib.rs@@ -25,6 +25,8 @@//! - [`resource`] — The machine-resource policy: cores, memory budget, thread priority//! - [`localauth`] — Loopback guard + `<data_dir>/admin.key` discovery for//! same-machine CLI/MCP commands (`xerj mcp`, `xerj autoindex`, `xerj init`)+//! - [`xccode`] — the reference-coding semantics shared by `xerj code`,+//! `xerj corpus`, and the `xerj_code_search` MCP tool (issue #977)pub mod config;pub mod error;@@ -37,6 +39,7 @@ pub mod net;pub mod resource;pub mod schema;pub mod types;+pub mod xccode;// Convenience re-exports at the crate rootpub use config::Config;diff --git a/engine/crates/xerj-common/src/xccode/fields.rs b/engine/crates/xerj-common/src/xccode/fields.rsnew file mode 100644index 000000000..82cada362--- /dev/null+++ b/engine/crates/xerj-common/src/xccode/fields.rs@@ -0,0 +1,167 @@+//! Mapping-resolved query fields and semantic-capable index discovery.++use serde_json::Value;++/// These exact fields and these exact (flat) weights were measured, not+/// chosen. Swept 7 variants over 6 ground-truth queries on a 324-file Rust+/// corpus (`body, defs, title` flat: top3 6/6 — the winner; boosting `defs`+/// favours test modules; `title^2 body`: top3 2/6). Full table in+/// tools/xerj-code/SKILL.md; provenance: measure/SERVER_UPLIFT_SCORECARD.md.+///+/// Two fields are deliberately absent:+/// * `symbols.name` — `symbols` is an array of objects with no searchable+/// `.name` subpath; including it makes the whole multi_match return ZERO+/// hits with no error at all (it took an Aho-Corasick query from 0 hits to+/// 3 correct files just to remove it).+/// * `"*"` — a bare wildcard flattens every score to the same value+/// (measured: every hit scored exactly 2.0).+///+/// `defs_expanded^0.5` is a low-weight RECALL field (per-symbol signatures ++/// identifier sub-words) boosted BELOW 1.0 on purpose. It is NOT safe to send+/// unconditionally — see [`resolve_fields`].+pub const FIELDS: &[&str] = &["body", "defs", "title", "defs_expanded^0.5"];++/// Drop query fields that no index under the prefix actually maps.+///+/// This engine does NOT ignore an unmapped field in `multi_match` the way ES+/// does — including one silently collapses a MULTI-TOKEN query to ZERO hits.+/// Measured 2026-08-06, one index, exact totals (`relation: eq`):+///+/// ```text+/// query "log merge policy segment size buckets"+/// fields=["body"] -> 673 hits+/// fields=["body","defs"] -> 673 hits+/// fields=["body","defs","title"] -> 673 hits+/// fields=["body","defs","title","defs_expanded"] -> 0 hits+/// ```+///+/// `defs_expanded` was mapped in exactly 0 of the corpus's 219 indices, so+/// every multi-word query returned "no passage matches" — the silent-zero+/// failure shape. Full reproducer: measure/MULTIMATCH_DEFECT.md.+///+/// `mapping` is `None` when the mapping could not be read (transport hiccup,+/// auth): send the list UNCHANGED rather than silently narrowing it. The+/// floor is `["body"]` — never an empty field list.+pub fn resolve_fields(mapping: Option<&Value>) -> Vec<String> {+ let Some(mapping) = mapping else {+ return FIELDS.iter().map(|s| s.to_string()).collect();+ };+ let Some(obj) = mapping.as_object() else {+ return FIELDS.iter().map(|s| s.to_string()).collect();+ };+ let mut present = std::collections::BTreeSet::new();+ for m in obj.values() {+ if let Some(props) = m.pointer("/mappings/properties").and_then(Value::as_object) {+ for key in props.keys() {+ present.insert(key.clone());+ }+ }+ }+ let out: Vec<String> = FIELDS+ .iter()+ .filter(|f| {+ let base = f.split('^').next().unwrap_or(f);+ present.contains(base)+ })+ .map(|s| s.to_string())+ .collect();+ if out.is_empty() {+ vec!["body".to_string()]+ } else {+ out+ }+}++/// Indices under the prefix whose `field` (default `body`) is mapped as+/// `semantic_text`.+///+/// A `semantic` query against an index where the field is plain `text` does+/// not return fewer hits — it fails the WHOLE search with a 400, taking every+/// other index in the wildcard down with it. So the capable set is discovered+/// from the mapping and the vector arm is aimed ONLY at those indices.+///+/// Returns `(capable, total)`, names sorted. An unreadable/unparseable+/// mapping yields an empty capable set (degrade to BM25), never a guess.+pub fn semantic_capable(mapping: Option<&Value>) -> (Vec<String>, usize) {+ let Some(mapping) = mapping.and_then(Value::as_object) else {+ return (Vec::new(), 0);+ };+ let mut capable: Vec<String> = mapping+ .iter()+ .filter(|(_, m)| {+ m.pointer("/mappings/properties/body/type")+ .and_then(Value::as_str)+ .is_some_and(|t| t == "semantic_text")+ })+ .map(|(name, _)| name.clone())+ .collect();+ capable.sort();+ (capable, mapping.len())+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ fn mapping(indices: &[(&str, &[&str], bool)]) -> Value {+ let mut obj = serde_json::Map::new();+ for (name, fields, semantic_body) in indices {+ let mut props = serde_json::Map::new();+ for f in fields.iter() {+ props.insert(+ f.to_string(),+ json!({ "type": if *semantic_body && *f == "body" { "semantic_text" } else { "text" } }),+ );+ }+ obj.insert(+ name.to_string(),+ json!({ "mappings": { "properties": props } }),+ );+ }+ Value::Object(obj)+ }++ #[test]+ fn unmapped_fields_are_dropped_and_the_floor_is_body() {+ // The MULTIMATCH_DEFECT guard: `defs_expanded` unmapped in every+ // index must be dropped, not sent.+ let m = mapping(&[+ ("xc-kv-b1-000", &["body", "defs", "title"], false),+ ("xc-kv-b1-001", &["body", "defs"], false),+ ]);+ assert_eq!(+ resolve_fields(Some(&m)),+ vec!["body".to_string(), "defs".into(), "title".into()]+ );++ // No FIELDS member mapped at all -> the ["body"] floor, never empty.+ let thin = mapping(&[("i", &["unrelated"], false)]);+ assert_eq!(resolve_fields(Some(&thin)), vec!["body".to_string()]);+ }++ #[test]+ fn an_unreadable_mapping_sends_the_full_list() {+ assert_eq!(+ resolve_fields(None),+ FIELDS.iter().map(|s| s.to_string()).collect::<Vec<_>>()+ );+ assert_eq!(+ resolve_fields(Some(&json!("junk"))),+ FIELDS.iter().map(|s| s.to_string()).collect::<Vec<_>>()+ );+ }++ #[test]+ fn capable_discovery_finds_only_semantic_text_indices() {+ let m = mapping(&[+ ("plain-1", &["body", "defs"], false),+ ("sem-1", &["body", "defs"], true),+ ("sem-2", &["body"], true),+ ]);+ let (capable, total) = semantic_capable(Some(&m));+ assert_eq!(capable, vec!["sem-1".to_string(), "sem-2".to_string()]);+ assert_eq!(total, 3);+ assert!(semantic_capable(None) == (Vec::new(), 0));+ }+}diff --git a/engine/crates/xerj-common/src/xccode/licence.rs b/engine/crates/xerj-common/src/xccode/licence.rsnew file mode 100644index 000000000..b883b0537--- /dev/null+++ b/engine/crates/xerj-common/src/xccode/licence.rs@@ -0,0 +1,352 @@+//! Licence policy, driven by DATA (the recorded `corpus.json` licence string)+//! — never by prose. The hub's own record once disagreed with a doc's prose+//! (`sonic` is recorded MPL-2.0; a stale CLAUDE.md said GPL), and hard-coding+//! repo names or licences is exactly how that mistake becomes load-bearing.+//!+//! Two surfaces share one tuple:+//! * QUERY time — [`is_restricted`] gates the per-hit warning printed+//! directly under the passage it guards, so it cannot be separated from the+//! code it applies to;+//! * CLONE time — the same tuple gates the one-line warning `xerj corpus add`+//! prints per repo.+//!+//! The original scripts let these drift (the clone-time check was missing the+//! MPL arm, so `sonic` warned only at query time despite a comment saying the+//! two "MUST stay in step"). The port unifies on the FULLER tuple: strictly+//! more warning, never less.++/// Licences you must not copy from, as substrings of what the manifest+/// records. Substring is deliberate: the detector records multi-licence+/// strings ("AGPL" for elasticsearch's triple, "BUSL/MIT" for meilisearch's+/// EE split, "Apache-2.0/MIT" for dual-licensed crates), and the tuple+/// catches every restricted constituent.+///+/// Warning on only ("GPL","LGPL") — an exact match, as this once did — was+/// silent on every restricted repo the hub deliberately ships.+/// UNKNOWN and NONE-FOUND are restricted too: an unidentified licence must+/// over-report restriction, never under-report it.+pub const RESTRICTED: &[&str] = &[+ "AGPL",+ "SSPL",+ "Elastic",+ "BUSL",+ "GPL",+ "LGPL",+ "MPL",+ "UNKNOWN",+ "NONE-FOUND",+];++/// The per-hit warning line, printed directly under the passage so it cannot+/// be separated from the code it guards.+pub fn hit_warning_line(lic: &str) -> String {+ format!(" !! {lic}: adapt the APPROACH, do not copy the code")+}++/// The clone-time warning line (`xerj corpus add`). Same tuple as query time+/// — the unified rule the scripts' comment promised.+pub fn clone_warning_line(lic: &str) -> Option<String> {+ if is_restricted(lic) {+ Some(format!(+ " ^ {lic}: adapt the APPROACH, do not copy the code"+ ))+ } else {+ None+ }+}++/// True when the recorded licence string carries any restricted constituent.+/// An empty string (repo missing from the licence map) is "no record", which+/// the renderer reports without a licence-specific line — there is no licence+/// to name in the warning.+pub fn is_restricted(lic: &str) -> bool {+ RESTRICTED.iter().any(|p| lic.contains(p))+}++/// Find the licence without guessing: read the file(s) the project actually+/// ships. Dual-licensed crates (very common in Rust) ship LICENSE-MIT ++/// LICENSE-APACHE and no plain LICENSE, so every candidate is collected+/// rather than taking the first. Results are de-duplicated and joined with+/// "/" — "Apache-2.0/MIT" is the honest answer for a dual-licensed project;+/// collapsing it to one licence would be a false record. No candidate file+/// at all -> "NONE-FOUND".+pub fn detect_licence(repo_dir: &std::path::Path) -> String {+ let mut found: Vec<String> = Vec::new();+ let Ok(entries) = std::fs::read_dir(repo_dir) else {+ return "NONE-FOUND".to_string();+ };+ let mut names: Vec<String> = entries+ .flatten()+ .filter(|e| e.path().is_file())+ .map(|e| e.file_name().to_string_lossy().to_string())+ .filter(|n| {+ n.starts_with("LICENSE") || n.starts_with("LICENCE") || n.starts_with("COPYING")+ })+ .collect();+ names.sort();+ for name in names {+ // LICENSE-3rdparty.csv (quickwit) is an inventory of DEPENDENCY+ // licences, not this project's licence. Classifying it produced a+ // spurious "UNKNOWN" arm on an otherwise plain Apache-2.0 repo.+ let lower = name.to_lowercase();+ if lower.contains("3rdparty")+ || lower.contains("third-party")+ || lower.contains("thirdparty")+ {+ continue;+ }+ if let Ok(text) = std::fs::read_to_string(repo_dir.join(&name)) {+ found.push(classify_one(&text).to_string());+ }+ }+ if found.is_empty() {+ return "NONE-FOUND".to_string();+ }+ found.sort();+ found.dedup();+ found.join("/")+}++/// Classify one licence FILE by its text: the TITLE (first two non-blank+/// lines — titles wrap) first, and only then the body (first 4000 chars).+///+/// A licence file names itself in its opening lines while its body may CITE+/// other licences, so the body scan is the fallback, not the primary.+fn classify_one(text: &str) -> &'static str {+ let title: String = text+ .lines()+ .filter(|l| !l.trim().is_empty())+ .take(2)+ .collect::<Vec<_>>()+ .join(" ");+ let out = classify_text(&title);+ if out == "UNKNOWN" {+ classify_text(text.chars().take(4000).collect::<String>().as_str())+ } else {+ out+ }+}++/// Classify licence text. Order matters: check the most RESTRICTIVE phrases+/// first, and keep "bsd" last because Apache and MIT texts can both mention+/// BSD in passing.+///+/// The restrictive-first ordering is not stylistic. Elasticsearch's+/// LICENSE.txt is a triple licence (AGPL-3.0 / SSPL-1.0 / Elastic-2.0) whose+/// text contains the phrase «an "Apache License 2.0" compatible license»:+/// with Apache checked first, the repo was recorded "Apache-2.0" — the most+/// permissive possible reading of the most restrictive licence in the+/// corpus, on the one repo where being wrong matters most.+fn classify_text(text: &str) -> &'static str {+ let body: String = text+ .to_lowercase()+ .chars()+ .map(|c| if c == '\n' { ' ' } else { c })+ .collect();+ // Restrictive-first; keep in step with RESTRICTED above.+ if body.contains("affero general public license") {+ "AGPL"+ } else if body.contains("server side public license") {+ "SSPL"+ } else if body.contains("elastic license") {+ "Elastic"+ } else if body.contains("business source license") {+ "BUSL"+ } else if body.contains("gnu lesser general") {+ "LGPL"+ } else if body.contains("gnu general public license") {+ "GPL"+ } else if body.contains("mozilla public license") {+ "MPL-2.0"+ } else if body.contains("apache license") {+ "Apache-2.0"+ } else if body.contains("mit license")+ || body.contains("permission is hereby granted, free of charge")+ {+ "MIT"+ } else if body.contains("redistribution and use in source and binary forms") {+ "BSD"+ } else {+ "UNKNOWN"+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn restricted_substrings_catch_every_recorded_restricted_repo() {+ // Exactly what corpus.json records, per repo:+ assert!(+ is_restricted("AGPL"),+ "elasticsearch (triple, most-restrictive recorded)"+ );+ assert!(+ is_restricted("MPL-2.0"),+ "sonic — MPL, NOT GPL; drive from the record"+ );+ assert!(is_restricted("BUSL/MIT"), "meilisearch EE");+ assert!(+ !is_restricted("Apache-2.0/MIT"),+ "dual permissive: cite freely"+ );+ assert!(!is_restricted("Apache-2.0"));+ assert!(!is_restricted("MIT"));+ assert!(!is_restricted("BSD-3-Clause"));+ assert!(is_restricted("UNKNOWN"), "unidentified over-reports");+ assert!(is_restricted("NONE-FOUND"), "no licence file over-reports");+ }++ #[test]+ fn the_warning_line_is_verbatim() {+ assert_eq!(+ hit_warning_line("AGPL"),+ " !! AGPL: adapt the APPROACH, do not copy the code"+ );+ }++ // ── clone-time warning: UNIFIED with the query tuple (the fix) ────────++ #[test]+ fn clone_time_warning_now_covers_mpl_like_query_time() {+ // The scripts' discrepancy: sonic (MPL-2.0) warned at query time but+ // NOT at clone time. Unified on the fuller tuple.+ assert!(+ clone_warning_line("MPL-2.0").is_some(),+ "sonic must warn at clone time too"+ );+ for lic in [+ "AGPL",+ "SSPL",+ "Elastic",+ "BUSL",+ "GPL",+ "LGPL",+ "UNKNOWN",+ "NONE-FOUND",+ ] {+ assert!(clone_warning_line(lic).is_some(), "{lic} must warn");+ }+ assert!(clone_warning_line("Apache-2.0/MIT").is_none());+ }++ // ── the detector's two ordering traps ──────────────────────────────────++ #[test]+ fn elasticsearch_triple_reads_agpl_not_apache() {+ // A full AGPL triple body must not fall through to Apache: the phrase+ // «an "Apache License 2.0" compatible license» lives in the AGPL text.+ let triple = "GNU Affero General Public License\nVersion 3, 19 November 2007\n\+ ...an \"Apache License 2.0\" compatible license...";+ assert_eq!(classify_one(triple), "AGPL");+ // The Elastic title names itself.+ assert_eq!(+ classify_one("Elastic License 2.0\n\nwww.elastic.co"),+ "Elastic"+ );+ }++ #[test]+ fn mpl_body_citing_gpl_still_reads_mpl_title_first() {+ // MPL-2.0 defines "Secondary License" as «the GNU General Public+ // License, Version 2.0» inside its own text: a body-only scan with+ // restrictive-first ordering reads sonic's plain MPL-2.0 as GPL. The+ // TITLE wins; the body is only the fallback.+ let mpl = "Mozilla Public License\nVersion 2.0\n\+ ...\"Secondary Licenses\" means the GNU General Public License, Version 2.0...";+ assert_eq!(classify_one(mpl), "MPL-2.0");+ // Fallback: a "# License" heading (title says nothing) drops to the+ // body scan — the previous behaviour.+ assert_eq!(+ classify_one("# License\n\nGNU General Public License\nVersion 2"),+ "GPL"+ );+ }++ #[test]+ fn permissive_bodies_classify_their_own_licence() {+ assert_eq!(+ classify_one("Apache License\nVersion 2.0, January 2004"),+ "Apache-2.0"+ );+ assert_eq!(+ classify_one(+ "MIT License\n\nPermission is hereby granted, free of charge, to any person"+ ),+ "MIT"+ );+ assert_eq!(+ classify_one(+ " Redistribution and use in source and binary forms, with or without\nmodification"+ ),+ "BSD"+ );+ assert_eq!(+ classify_one("Random README text with no licence phrases"),+ "UNKNOWN"+ );+ }++ // ── detect_licence over fixture directories ───────────────────────────++ #[test]+ fn detect_reads_all_candidates_skips_3rdparty_and_dedups() {+ let holder = tempfile::tempdir().unwrap();+ let repo = holder.path().join("dual");+ std::fs::create_dir_all(&repo).unwrap();+ std::fs::write(+ repo.join("LICENSE-MIT"),+ "MIT License\n\nPermission is hereby granted, free of charge",+ )+ .unwrap();+ std::fs::write(+ repo.join("LICENSE-APACHE"),+ "Apache License\nVersion 2.0, January 2004",+ )+ .unwrap();+ std::fs::write(+ repo.join("LICENSE-3rdparty.csv"),+ "dependency,licence\nserde,MIT\nsomething,GNU General Public License",+ )+ .unwrap();+ assert_eq!(+ detect_licence(&repo),+ "Apache-2.0/MIT",+ "dual-licensed crates join both, sorted; the 3rdparty inventory is skipped"+ );++ let empty = holder.path().join("nolicense");+ std::fs::create_dir_all(&empty).unwrap();+ assert_eq!(detect_licence(&empty), "NONE-FOUND");+ }++ #[test]+ fn detect_reads_title_first_then_body() {+ let holder = tempfile::tempdir().unwrap();+ let repo = holder.path().join("sonic");+ std::fs::create_dir_all(&repo).unwrap();+ std::fs::write(+ repo.join("LICENSE"),+ "Mozilla Public License\nVersion 2.0\n\n\+ 1. Definitions...\n\"Secondary Licenses\" means the GNU General Public License, Version 2.0...",+ )+ .unwrap();+ assert_eq!(detect_licence(&repo), "MPL-2.0");+ }++ #[test]+ fn detect_licence_name_variants_all_count() {+ let holder = tempfile::tempdir().unwrap();+ let repo = holder.path().join("uk");+ std::fs::create_dir_all(&repo).unwrap();+ std::fs::write(repo.join("LICENCE"), "Apache License\nVersion 2.0").unwrap();+ std::fs::write(+ repo.join("COPYING"),+ "GNU General Public License\nVersion 2",+ )+ .unwrap();+ // Results sort as strings then join: "Apache-2.0" < "GPL".+ assert_eq!(detect_licence(&repo), "Apache-2.0/GPL");+ }+}diff --git a/engine/crates/xerj-common/src/xccode/manifest.rs b/engine/crates/xerj-common/src/xccode/manifest.rsnew file mode 100644index 000000000..f91e3b715--- /dev/null+++ b/engine/crates/xerj-common/src/xccode/manifest.rs@@ -0,0 +1,341 @@+//! `corpora/<corpus>/corpus.json` — the per-corpus manifest — plus hub+//! manifests (`--from`), which are UNTRUSTED INPUT and validated as such.+//!+//! The manifest is regenerated FROM DISK at clone time, never copied through+//! from the input, so it always describes the checkout it sits beside. Its+//! byte format is pinned: humans diff these files by hand and share them in+//! chats, so the shape must not churn between releases.++use std::collections::HashMap;+use std::path::Path;++use serde::Deserialize;+use serde_json::{Map, Value};++use super::pathgate;++/// One repo entry. Tolerant parse: fields the writer has not always emitted+/// (`files`, `bytes`, `review`) are optional, unknown keys are ignored, so a+/// manifest written by any historical version still loads.+#[derive(Debug, Clone, Deserialize)]+pub struct ManifestRepo {+ pub repo: String,+ pub url: String,+ #[serde(default)]+ pub sha: String,+ #[serde(default)]+ pub licence: String,+ #[serde(default)]+ pub files: Option<u64>,+ #[serde(default)]+ pub bytes: Option<u64>,+ /// Vetted hub records carry a review block (`spdx`, `use`, `by`, `at`,+ /// `note`). It is PRESERVED verbatim across a rebuild when repo+sha+ /// match — a human's licence review must survive a re-index.+ #[serde(default)]+ pub review: Option<Value>,+}++#[derive(Debug, Clone, Deserialize)]+pub struct CorpusManifest {+ #[serde(default)]+ pub corpus: String,+ #[serde(default)]+ pub cloned_at: Option<String>,+ #[serde(default)]+ pub repos: Vec<ManifestRepo>,+}++/// Read a corpus manifest. Missing file is `Err` with the path named — the+/// caller decides whether that is fatal (`corpus add` regenerates it;+/// `xerj code` reports the corpus as licence-unmapped).+pub fn read_corpus_manifest(path: &Path) -> Result<CorpusManifest, String> {+ let raw = std::fs::read_to_string(path)+ .map_err(|e| format!("cannot read manifest {}: {e}", path.display()))?;+ serde_json::from_str(&raw).map_err(|e| format!("{} is not valid JSON: {e}", path.display()))+}++/// repo -> recorded licence for a corpus. ALWAYS the recorded string, never+/// re-derived at query time: the licence decision was made once, at clone+/// time, against the checkout — re-deriving it per query is how prose drift+/// becomes load-bearing.+pub fn licence_map(root: &Path, corpus: &str) -> HashMap<String, String> {+ let path = root.join("corpora").join(corpus).join("corpus.json");+ read_corpus_manifest(&path)+ .map(|m| {+ m.repos+ .iter()+ .map(|r| (r.repo.clone(), r.licence.clone()))+ .collect()+ })+ .unwrap_or_default()+}++/// One repo entry as the writer emits it. Compact, key order pinned+/// (`repo,url,licence,sha,files,bytes[,review]`) — byte-identical to the+/// script's hand-built line so existing manifests diff clean against new ones.+fn entry_json(repo: &ManifestRepo) -> String {+ let mut m = Map::new();+ m.insert("repo".into(), Value::String(repo.repo.clone()));+ m.insert("url".into(), Value::String(repo.url.clone()));+ m.insert("licence".into(), Value::String(repo.licence.clone()));+ m.insert("sha".into(), Value::String(repo.sha.clone()));+ if let Some(f) = repo.files {+ m.insert("files".into(), Value::from(f));+ }+ if let Some(b) = repo.bytes {+ m.insert("bytes".into(), Value::from(b));+ }+ if let Some(r) = &repo.review {+ m.insert("review".into(), r.clone());+ }+ Value::Object(m).to_string()+}++/// Write the manifest in the pinned format:+///+/// ```text+/// {"corpus":"kv","cloned_at":"2026-08-06T12:00:00Z","repos":[+/// {"repo":"valkey","url":"https://github.com/valkey/valkey","licence":"BSD-3-Clause","sha":"abc…","files":912,"bytes":1234567}+/// ]}+/// ```+///+/// Atomic (tmp + rename): a half-written manifest describes a checkout that+/// does not exist, and `xerj corpus list` reads these.+pub fn write_corpus_manifest(path: &Path, corpus: &str, cloned_at: &str, repos: &[ManifestRepo]) {+ let mut body = format!(+ "{{\"corpus\":{},\"cloned_at\":{},\"repos\":[\n",+ Value::String(corpus.to_string()),+ Value::String(cloned_at.to_string())+ );+ for (i, r) in repos.iter().enumerate() {+ if i > 0 {+ body.push_str(",\n");+ }+ body.push_str(" ");+ body.push_str(&entry_json(r));+ }+ body.push_str("\n]}\n");+ let tmp = path.with_extension("json.tmp");+ if std::fs::write(&tmp, body).is_ok() {+ let _ = std::fs::rename(&tmp, path);+ }+}++/// A validated row of a hub manifest, ready for the clone loop.+#[derive(Debug, Clone)]+pub struct HubRow {+ pub repo: String,+ pub url: String,+ pub sha: String,+ pub declared_licence: String,+}++/// A whole validated hub manifest: the corpus name plus its rows. The+/// `corpus` field is the name `xerj corpus add --from` uses when the+/// caller gave none — dropping it (an earlier port bug) made `--from`+/// unusable without a redundant positional.+#[derive(Debug, Clone)]+pub struct HubManifest {+ pub corpus: String,+ pub rows: Vec<HubRow>,+}++/// Parse and VALIDATE a hub manifest (`--from`). Untrusted input rules from+/// the original `read_manifest`, enforced once, here, before any path is+/// built from a field: `repo` becomes a directory that is later+/// force-checked-out and cleaned inside, and a short sha is not fetchable,+/// so it silently rebuilds at the tip — the opposite of a pin.+pub fn read_hub_manifest(path: &Path) -> Result<HubManifest, String> {+ let raw = std::fs::read_to_string(path)+ .map_err(|e| format!("no such manifest: {} ({e})", path.display()))?;+ let v: Value = serde_json::from_str(&raw)+ .map_err(|e| format!("{} is not valid JSON: {e}", path.display()))?;+ let repos = v+ .get("repos")+ .and_then(Value::as_array)+ .filter(|a| !a.is_empty())+ .ok_or_else(|| format!("{} has no 'repos' array", path.display()))?;+ let corpus = v+ .get("corpus")+ .and_then(Value::as_str)+ .unwrap_or("")+ .to_string();+ if !corpus.is_empty() {+ pathgate::valid_corpus_name(&corpus).map_err(|e| format!("{}: {e}", path.display()))?;+ }+ let mut out = Vec::new();+ for r in repos {+ let repo = r.get("repo").and_then(Value::as_str).unwrap_or("");+ let url = r.get("url").and_then(Value::as_str).unwrap_or("");+ if repo.is_empty() || url.is_empty() {+ return Err(format!(+ "{}: an entry is missing 'repo' or 'url'",+ path.display()+ ));+ }+ pathgate::valid_repo_name(repo).map_err(|e| format!("{}: {e}", path.display()))?;+ let sha = r.get("sha").and_then(Value::as_str).unwrap_or("");+ pathgate::valid_sha(repo, sha).map_err(|e| format!("{}: {e}", path.display()))?;+ out.push(HubRow {+ repo: repo.to_string(),+ url: url.to_string(),+ sha: sha.to_string(),+ declared_licence: r+ .get("licence")+ .and_then(Value::as_str)+ .unwrap_or("")+ .to_string(),+ });+ }+ Ok(HubManifest { corpus, rows: out })+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ fn tmp() -> std::path::PathBuf {+ tempfile::tempdir().unwrap().keep()+ }++ #[test]+ fn round_trip_is_byte_stable_and_review_survives() {+ let dir = tmp();+ let path = dir.join("corpus.json");+ let review = json!({ "spdx": "Apache-2.0", "use": "search engine internals", "by": "adi", "at": "2026-08-06", "note": "safe" });+ let repos = vec![ManifestRepo {+ repo: "valkey".into(),+ url: "https://github.com/valkey/valkey".into(),+ licence: "BSD-3-Clause".into(),+ sha: "31081d9f05014003321333553bb3e657eb3da168".into(),+ files: Some(912),+ bytes: Some(1_234_567),+ review: Some(review.clone()),+ }];+ write_corpus_manifest(&path, "kv", "2026-08-06T12:00:00Z", &repos);+ let text = std::fs::read_to_string(&path).unwrap();+ assert_eq!(+ text,+ "{\"corpus\":\"kv\",\"cloned_at\":\"2026-08-06T12:00:00Z\",\"repos\":[\n \+ {\"repo\":\"valkey\",\"url\":\"https://github.com/valkey/valkey\",\"licence\":\+ \"BSD-3-Clause\",\"sha\":\"31081d9f05014003321333553bb3e657eb3da168\",\"files\":912,\+ \"bytes\":1234567,\"review\":{\"spdx\":\"Apache-2.0\",\"use\":\"search engine \+ internals\",\"by\":\"adi\",\"at\":\"2026-08-06\",\"note\":\"safe\"}}\n]}\n"+ );+ let back = read_corpus_manifest(&path).unwrap();+ assert_eq!(back.repos[0].review, Some(review));+ assert_eq!(back.corpus, "kv");+ }++ #[test]+ fn licence_map_comes_from_the_record_not_the_prose() {+ let dir = tmp();+ let corpora = dir.join("corpora").join("xerj-search");+ std::fs::create_dir_all(&corpora).unwrap();+ write_corpus_manifest(+ &corpora.join("corpus.json"),+ "xerj-search",+ "t",+ &[+ ManifestRepo {+ repo: "tantivy".into(),+ url: "u1".into(),+ licence: "Apache-2.0/MIT".into(),+ sha: "s".into(),+ files: None,+ bytes: None,+ review: None,+ },+ ManifestRepo {+ repo: "sonic".into(),+ url: "u2".into(),+ licence: "MPL-2.0".into(),+ sha: "s".into(),+ files: None,+ bytes: None,+ review: None,+ },+ ],+ );+ let m = licence_map(&dir, "xerj-search");+ assert_eq!(m.get("sonic").map(String::as_str), Some("MPL-2.0"));+ assert!(!m.contains_key("nope"));+ assert!(licence_map(&dir, "never-cloned").is_empty());+ }++ #[test]+ fn hub_validation_rejects_path_escapes_and_short_shas() {+ let dir = tmp();+ let bad = dir.join("evil.json");+ std::fs::write(&bad, json!({ "repos": [ { "repo": "../../work", "url": "u", "sha": "31081d9f05014003321333553bb3e657eb3da168" } ] }).to_string()).unwrap();+ let err = read_hub_manifest(&bad).unwrap_err();+ assert!(err.contains("force-checked-out"), "{err}");++ std::fs::write(+ &bad,+ json!({ "repos": [ { "repo": "valkey", "url": "u", "sha": "e449d17" } ] }).to_string(),+ )+ .unwrap();+ let err = read_hub_manifest(&bad).unwrap_err();+ assert!(err.contains("not a full 40-character sha"), "{err}");++ std::fs::write(+ &bad,+ json!({ "repos": [ { "repo": "valkey" } ] }).to_string(),+ )+ .unwrap();+ assert!(read_hub_manifest(&bad)+ .unwrap_err()+ .contains("missing 'repo' or 'url'"));+ std::fs::write(&bad, json!({ "repos": [] }).to_string()).unwrap();+ assert!(read_hub_manifest(&bad)+ .unwrap_err()+ .contains("no 'repos' array"));+ }++ /// The hub's own vetted manifests must stay valid under the SAME gate the+ /// `--from` path enforces — they are the reference for "rebuild a corpus+ /// someone else defined", so a hub file that the tool itself would reject+ /// is a bug in the hub. Reads them from the repo via CARGO_MANIFEST_DIR+ /// ancestors (the published_schema_drift.rs house pattern).+ #[test]+ fn hub_manifests_pass_the_untrusted_input_gate() {+ let hub = find_repo_root().join("tools/xerj-code/hub");+ let mut checked = 0;+ for entry in std::fs::read_dir(&hub).expect("hub dir") {+ let p = entry.unwrap().path();+ if p.extension().and_then(|e| e.to_str()) != Some("json") {+ continue;+ }+ let hub = read_hub_manifest(&p)+ .unwrap_or_else(|e| panic!("{} failed the gate: {e}", p.display()));+ assert!(!hub.rows.is_empty());+ // Every hub manifest names its corpus — `--from` depends on it.+ assert!(+ !hub.corpus.is_empty(),+ "{} has no 'corpus' field",+ p.display()+ );+ checked += 1;+ }+ assert!(+ checked >= 1,+ "no hub manifests found under {}",+ hub.display()+ );+ }++ fn find_repo_root() -> std::path::PathBuf {+ let mut dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));+ loop {+ if dir.join("tools/xerj-code/hub").is_dir() {+ return dir;+ }+ if !dir.pop() {+ panic!("repo root not found above {}", env!("CARGO_MANIFEST_DIR"));+ }+ }+ }+}diff --git a/engine/crates/xerj-common/src/xccode/mod.rs b/engine/crates/xerj-common/src/xccode/mod.rsnew file mode 100644index 000000000..e8fab62b3--- /dev/null+++ b/engine/crates/xerj-common/src/xccode/mod.rs@@ -0,0 +1,874 @@+//! # xccode — the reference-coding semantics shared by `xerj code`, the+//! `xerj corpus` lifecycle, and the `xerj_code_search` MCP tool+//!+//! Until issue #977 the reference-coding loop lived in three wrapper scripts+//! (`tools/xerj-code/scripts/xc.py`, `xc-index.sh`, `xc-corpus.sh`). They are+//! ported here as ONE pure implementation so the CLI and the MCP tool serve+//! byte-identical prose from the same renderer, and so every contract — the+//! 30-day staleness refusal, the restricted-licence warning, the+//! not-loaded-here diagnosis, the exit-code triangle — has exactly one home+//! and one test suite.+//!+//! Layout (all persistent paths parameterised by `root`; tests inject+//! tempdirs — that is test hygiene, NOT a layout change):+//!+//! * [`state`] — the `state/<corpus>.json` ledger: read, staleness,+//! incomplete-coverage warning, atomic write+//! * [`licence`] — restricted-licence tuple + the clone-time detector+//! * [`manifest`] — `corpora/<corpus>/corpus.json` read/write + hub manifests+//! * [`pathgate`] — the hard gate every manifest-derived path passes before+//! anything destructive runs inside it+//! * [`fields`] — mapping-resolved `multi_match` fields + semantic-capable+//! index discovery+//! * [`passage`] — symbol-passage / best-window / file-head selection+//! * [`render`] — the one output renderer (prose + MEATL)+//!+//! HTTP is a 3-method shell ([`XcHttp`]) so the pure core stays free of any+//! client dependency: `xerj-autoindex` implements it over its blocking `Es`+//! client, `xerj-mcp` over reqwest. No fusion or query logic lives in either+//! — hybrid retrieval emits the engine's native top-level `hybrid` query and+//! lets the server fuse.++pub mod fields;+pub mod licence;+pub mod manifest;+pub mod passage;+pub mod pathgate;+pub mod render;+pub mod state;++use std::collections::HashMap;+use std::path::Path;++use serde_json::Value;++/// Corpora older than this are refused, not served: a stale index returns+/// code that no longer exists, with false confidence (`STALE_DAYS` in the+/// original `xc.py`).+pub const STALE_DAYS: i64 = 30;++/// Reciprocal Rank Fusion constant (Cormack, Clarke & Buettcher, SIGIR 2009).+/// k=60 is the paper's value and the universal default. It is NOT tuned here.+/// Fusion itself is SERVER-SIDE (native `hybrid` query, #943); this constant+/// only names k in the request we emit and in the arms-ran note.+pub const RRF_K: u64 = 60;++/// The retrieval arm. Default is [`Mode::Bm25`] — measured 12/12 top-3 across+/// both standing corpora (bm25 beat hybrid and semantic on the combined+/// metric; see `tools/xerj-code/SKILL.md`'s retrieval-mode table).+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Mode {+ Bm25,+ Semantic,+ Hybrid,+}++impl Mode {+ /// Parse the `--mode` / MCP `mode` argument. Unknown values are usage+ /// errors (exit 2), never a silent default.+ pub fn parse(s: &str) -> Option<Mode> {+ match s {+ "bm25" => Some(Mode::Bm25),+ "semantic" => Some(Mode::Semantic),+ "hybrid" => Some(Mode::Hybrid),+ _ => None,+ }+ }+}++/// Everything one `xerj code` invocation (or `xerj_code_search` tool call)+/// needs. Defaults mirror `xc.py` exactly: k=5, bm25, full=800, symbols on.+#[derive(Debug, Clone)]+pub struct CodeParams {+ pub corpus: String,+ pub query: String,+ pub k: usize,+ pub lang: Option<String>,+ pub mode: Mode,+ /// Max chars of each passage; 0 = file-head mode (first 400 chars,+ /// labelled as the file head — retrieving the definition IS the feature,+ /// issue #368, so this is a cap, never an opt-out).+ pub full: usize,+ pub no_symbol: bool,+ pub stale_ok: bool,+ pub meatl: bool,+ /// CLI `--json`: raw server response on stdout. MCP never sets this.+ pub as_json: bool,+ /// MCP `licence_policy:"strict"`: restricted-licence hits keep+ /// provenance + licence + warning but lose the passage text. The CLI+ /// stays `false` (warn) for `xc.py` parity.+ pub strict_licence: bool,+}++impl CodeParams {+ pub fn new(corpus: &str, query: &str) -> Self {+ CodeParams {+ corpus: corpus.to_string(),+ query: query.to_string(),+ k: 5,+ lang: None,+ mode: Mode::Bm25,+ full: 800,+ no_symbol: false,+ stale_ok: false,+ meatl: false,+ as_json: false,+ strict_licence: false,+ }+ }+}++/// The one HTTP shell the pure core needs. Implemented over the blocking `Es`+/// client in `xerj-autoindex` and over reqwest in `xerj-mcp`; fakes in tests.+///+/// `cat_indices_json` maps HTTP 404 to `Ok(vec![])` — a wildcard that matches+/// no index means "none", not an error — while every other failure is `Err`:+/// a node that cannot answer must never be reported as "0 live indices".+pub trait XcHttp {+ /// `GET /{pattern}/_mapping`. `Err` carries a human-readable reason.+ fn get_mapping(&self, pattern: &str) -> Result<Value, String>;+ /// `GET /_cat/indices/{pattern}?format=json&h=index` as index names.+ /// `Err` = unreachable/ambiguous (never a silent zero).+ fn cat_indices_json(&self, pattern: &str) -> Result<Vec<String>, String>;+ /// `POST /{index}/_search`. `Err` carries status + reason or transport.+ fn search(&self, index: &str, body: &Value) -> Result<Value, String>;+}++/// Everything a caller needs after the pipeline ran. The CLI prints `text`+/// (stdout, or stderr when [`Self::to_stderr`] — refusals are diagnostics)+/// and exits with [`Self::exit`]; MCP returns `text` as the tool payload with+/// [`Self::is_error`]. Warnings ride stderr on the CLI and the TOP of the+/// tool text on MCP — MCP has no stderr channel, so warnings are content.+#[derive(Debug, Clone)]+pub struct CodeOutcome {+ pub text: String,+ pub warnings: Vec<String>,+ /// 0 = hits, 1 = no match (a miss is an answer), 2 = usage / stale /+ /// transport, 3 = corpus in state/ but 0 live indices on this node.+ pub exit: i32,+ /// MCP `isError`: true exactly for the action-needed states (2 and 3).+ /// A no-match is `false` with the fall-back prose.+ pub is_error: bool,+ /// Raw server response when `as_json` was requested (CLI-only flag).+ pub json: Option<Value>,+ pub to_stderr: bool,+}++impl CodeOutcome {+ fn refused(text: String, exit: i32) -> Self {+ CodeOutcome {+ text,+ warnings: Vec::new(),+ exit,+ is_error: true,+ json: None,+ to_stderr: true,+ }+ }+}++/// The whole query pipeline, pure: ledger → staleness → live-count → mapping+/// discovery → query → passage selection → licence map → render.+///+/// `url` is the resolved node URL (for diagnostics); `stale_hint` is the+/// override spelling the caller's surface accepts — "`--stale-ok`" on the+/// CLI, "`stale_ok:true`" on MCP — so the one refusal text names the fix the+/// caller can actually type.+pub fn run_code_query(+ root: &Path,+ http: &impl XcHttp,+ url: &str,+ params: &CodeParams,+ stale_hint: &str,+) -> CodeOutcome {+ let corpus = params.corpus.clone();+ let query = params.query.clone();++ // 1. The ledger. Not indexed is a usage-class refusal naming the command+ // that fixes it (exit 2 — the caller's driver script should stop).+ let st = match state::load_state(root, &corpus) {+ Ok(st) => st,+ Err(msg) => return CodeOutcome::refused(msg, 2),+ };++ // 2. Staleness: refuse BEFORE any query. A stale index returns code that+ // no longer exists; --stale-ok / stale_ok:true is the only override+ // (no env bypass — a wrapper must not be able to de-fang this).+ let age_days = match state::check_fresh(&st, params.stale_ok, stale_hint) {+ Ok(age) => age,+ Err(refusal) => return CodeOutcome::refused(refusal, 2),+ };++ let prefix = state::query_prefix(&st);++ // 3. Not-loaded-here: in state/ yet 0 live indices on THIS node. A+ // distinct, actionable diagnosis (exit 3) — collapsing it into+ // "no match" is the state-ledger trust trap this guard closes.+ // An unreachable node is reported honestly (exit 2) by the search+ // path below, never as "0 live indices".+ match http.cat_indices_json(&format!("{prefix}*")) {+ Ok(indices) if indices.is_empty() => {+ return CodeOutcome::refused(state::not_loaded_message(&st, &prefix, url), 3)+ }+ // Unreachable/ambiguous: fall through; the search itself will report+ // the transport failure honestly.+ _ => {}+ }++ let mut warnings = Vec::new();+ if let Some(w) = state::incomplete_coverage(&st) {+ warnings.push(w);+ }++ // 4. Mapping: one read serves both field resolution and capable-set+ // discovery. Unreadable is data, not an error (bm25 degrades to the+ // full field list; hybrid degrades to BM25-only).+ let pattern = format!("{prefix}*");+ let mapping = http.get_mapping(&format!("/{pattern}/_mapping")).ok();+ let fields = fields::resolve_fields(mapping.as_ref());++ let mut note: Option<String> = None;+ let mut rrf_scores = false;++ let (resp, hits) = match params.mode {+ Mode::Bm25 => match http.search(+ &pattern,+ &bm25_body(&query, params.k, ¶ms.lang, &fields),+ ) {+ Ok(r) => (r.clone(), hit_list(&r)),+ Err(e) => return CodeOutcome::refused(format!("search failed: {e}"), 2),+ },+ Mode::Semantic => {+ // Standalone semantic is fatal on mapping/search failure: it has+ // no BM25 result to keep.+ let mapping = match http.get_mapping(&format!("/{pattern}/_mapping")) {+ Ok(m) => m,+ Err(e) => {+ return CodeOutcome::refused(+ format!("semantic mapping lookup failed at {url}: {e}"),+ 2,+ )+ }+ };+ let (capable, total) = fields::semantic_capable(Some(&mapping));+ if capable.is_empty() {+ // No semantic arm is possible: do NOT post the query. An+ // empty comma-join is an empty index segment, which the+ // server reads as `/_search` — every index on the node,+ // corpus or not. The empty answer with its note is the+ // honest result.+ note = Some(format!(+ "no index under '{pattern}' maps `body` as semantic_text"+ ));+ (Value::Null, Vec::new())+ } else {+ note = Some(format!(+ "vector only over {} of {total} index(es)",+ capable.len()+ ));+ let body = semantic_body(&query, params.k, ¶ms.lang);+ match http.search(&capable.join(","), &body) {+ Ok(r) => (r.clone(), hit_list(&r)),+ Err(e) => return CodeOutcome::refused(format!("search failed: {e}"), 2),+ }+ }+ }+ Mode::Hybrid => {+ let (capable, total) = fields::semantic_capable(mapping.as_ref());+ if capable.is_empty() {+ // No vector arm possible: degrade, and SAY so.+ note = Some(format!(+ "BM25 only — no usable semantic_text mapping for `body` could be \+ discovered under '{pattern}'"+ ));+ match http.search(+ &pattern,+ &bm25_body(&query, params.k, ¶ms.lang, &fields),+ ) {+ Ok(r) => (r.clone(), hit_list(&r)),+ Err(e) => return CodeOutcome::refused(format!("search failed: {e}"), 2),+ }+ } else {+ // BM25 preflight: the lexical embedder returns confident+ // neighbours for ANY input, so a BM25 miss is the corpus's+ // only honest "no" — vector hits must not launder it.+ match http.search(&pattern, &bm25_body(&query, 1, ¶ms.lang, &fields)) {+ Ok(pre) if hit_list(&pre).is_empty() => {+ note = Some(+ "no lexical match in this corpus — vector nearest-neighbours \+ are not evidence of a match, so this is reported as a miss"+ .to_string(),+ );+ (Value::Null, Vec::new())+ }+ Ok(_) => {+ // ONE fused request: the engine's native top-level+ // `hybrid` (RRF k=60) — no client-side fusion. Aimed+ // at the comma-joined CAPABLE set when only some+ // indices map `body` as semantic_text: a semantic leg+ // posted at a wildcard covering plain-text indices+ // 400s the WHOLE request.+ let target = if capable.len() == total {+ pattern.clone()+ } else {+ capable.join(",")+ };+ let body = hybrid_body(&query, params.k, ¶ms.lang, &fields);+ match http.search(&target, &body) {+ Ok(r) => {+ rrf_scores = true;+ let mut n = format!(+ "hybrid RRF(k={RRF_K}) — BM25 over {total} index(es), \+ vector over {} of {total}",+ capable.len()+ );+ if capable.len() < total {+ let excluded: Vec<String> = mapping+ .as_ref()+ .and_then(|m| {+ m.as_object().map(|obj| {+ obj.keys()+ .filter(|k| !capable.contains(&k.to_string()))+ .cloned()+ .collect::<Vec<_>>()+ })+ })+ .unwrap_or_default();+ if !excluded.is_empty() {+ n.push_str(&format!(+ "; lexical-only (excluded from the vector arm): \+ {}",+ excluded.join(", ")+ ));+ }+ }+ note = Some(n);+ (r.clone(), hit_list(&r))+ }+ Err(_) => {+ // The vector arm failed, not the corpus:+ // degrade to plain BM25, never abort.+ note = Some(format!(+ "BM25 only — vector search failed or returned no hits \+ from the {} semantic_text index(es)",+ capable.len()+ ));+ match http.search(+ &pattern,+ &bm25_body(&query, params.k, ¶ms.lang, &fields),+ ) {+ Ok(r) => (r.clone(), hit_list(&r)),+ Err(e) => {+ return CodeOutcome::refused(+ format!("search failed: {e}"),+ 2,+ )+ }+ }+ }+ }+ }+ Err(e) => return CodeOutcome::refused(format!("search failed: {e}"), 2),+ }+ }+ }+ };++ // 5. --json: the raw response stays machine-readable while the exit-code+ // contract is unchanged (empty hits STILL exit 1).+ if params.as_json {+ return CodeOutcome {+ text: String::new(),+ warnings,+ exit: if hits.is_empty() { 1 } else { 0 },+ is_error: false,+ json: Some(resp),+ to_stderr: false,+ };+ }++ if hits.is_empty() {+ // Say so explicitly. A silent miss makes the next agent re-run the+ // same dead query; this is the line that stops the loop.+ return CodeOutcome {+ text: render::no_match_text(&corpus, &query, params.meatl),+ warnings,+ exit: 1,+ is_error: false,+ json: None,+ to_stderr: false,+ };+ }++ // 6. Licence map: ALWAYS from the corpus's own corpus.json — never+ // re-derived at query time, never from prose.+ let licences = manifest::licence_map(root, &corpus);++ let text = render::render(+ &hits,+ &licences,+ &render::RenderOpts {+ corpus: &corpus,+ query: &query,+ full: params.full,+ no_symbol: params.no_symbol,+ meatl: params.meatl,+ rrf_scores,+ age_days,+ strict_licence: params.strict_licence,+ },+ note.as_deref(),+ );++ CodeOutcome {+ text,+ warnings,+ exit: 0,+ is_error: false,+ json: None,+ to_stderr: false,+ }+}++/// Hits of a search response, missing containers tolerated as empty.+pub(crate) fn hit_list(resp: &Value) -> Vec<Value> {+ resp.pointer("/hits/hits")+ .and_then(Value::as_array)+ .cloned()+ .unwrap_or_default()+}++/// The measured BM25 body: flat `multi_match` over mapping-resolved fields+/// (`FIELDS`'s flat weights were measured, not chosen — 12/12 top-3). NEVER+/// a highlight block (issue #177: highlight changes ranking on this engine),+/// and no `_source` projection on the corpus path — passage selection needs+/// `body` and `symbols`.+pub(crate) fn bm25_body(query: &str, k: usize, lang: &Option<String>, fields: &[String]) -> Value {+ let mut must = vec![serde_json::json!({+ "multi_match": { "query": query, "fields": fields }+ })];+ if let Some(lg) = lang {+ must.push(serde_json::json!({ "match": { "language": lg } }));+ }+ serde_json::json!({ "size": k, "query": { "bool": { "must": must } } })+}++/// The vector-only body. Aimed ONLY at indices whose `body` is semantic_text+/// (a semantic query against plain text 400s the whole wildcard).+pub(crate) fn semantic_body(query: &str, k: usize, lang: &Option<String>) -> Value {+ let q = serde_json::json!({ "semantic": { "field": "body", "query": query } });+ let query = match lang {+ Some(lg) => serde_json::json!({+ "bool": { "must": [q, { "match": { "language": lg } }] }+ }),+ None => q,+ };+ serde_json::json!({ "size": k, "query": query })+}++/// ONE native top-level `hybrid` request: BM25 clause + semantic clause,+/// fused server-side by RRF(k=60). Hybrid anywhere else is a 400 (#943), so+/// this shape is the whole contract — and there is deliberately NO+/// client-side fusion left to drift from the engine's.+pub(crate) fn hybrid_body(+ query: &str,+ k: usize,+ lang: &Option<String>,+ fields: &[String],+) -> Value {+ // `--lang` must constrain BOTH legs (xc.py semantics): a language filter+ // on BM25 only lets the vector leg surface docs the user filtered out.+ let wrap = |q: Value| -> Value {+ match lang {+ Some(lg) => serde_json::json!({+ "bool": { "must": [q, { "match": { "language": lg } }] }+ }),+ None => q,+ }+ };+ let bm = wrap(serde_json::json!({+ "multi_match": { "query": query, "fields": fields }+ }));+ let sem = wrap(serde_json::json!({+ "semantic": { "field": "body", "query": query }+ }));+ serde_json::json!({+ "size": k,+ "query": { "hybrid": {+ "queries": [+ { "query": bm },+ { "query": sem }+ ],+ "fusion": { "method": "rrf", "k": RRF_K }+ }}+ })+}++/// `xerj corpus list` needs per-corpus live counts without the full pipeline;+/// this is the honest tri-state the ledger listing shares with `require_loaded`.+pub fn live_count_summary(http: &impl XcHttp, prefix: &str) -> Result<usize, String> {+ http.cat_indices_json(&format!("{prefix}*"))+ .map(|v| v.len())+}++/// Licence map for a corpus, exposed for `xerj corpus list`'s review.use line.+pub fn corpus_review_uses(root: &Path, corpus: &str) -> HashMap<String, String> {+ manifest::read_corpus_manifest(&root.join("corpora").join(corpus).join("corpus.json"))+ .map(|m| {+ m.repos+ .iter()+ .filter_map(|r| {+ r.review+ .as_ref()+ .and_then(|v| v.get("use"))+ .and_then(Value::as_str)+ .map(|u| (r.repo.clone(), u.to_string()))+ })+ .collect()+ })+ .unwrap_or_default()+}++#[cfg(test)]+mod tests {+ use super::*;++ /// A fake node: records every request, answers from canned data.+ struct FakeHttp {+ mapping: Value,+ hits: Vec<Value>,+ // (index, body) per search, in order — pins the EXACT wire shape.+ searches: std::sync::Mutex<Vec<(String, Value)>>,+ live: Vec<String>,+ fail_search: bool,+ }++ impl FakeHttp {+ fn new() -> Self {+ FakeHttp {+ mapping: serde_json::json!({+ "xc-kv-b1-000": { "mappings": { "properties": {+ "body": { "type": "text" }, "defs": { "type": "text" },+ "title": { "type": "text" }+ }}}+ }),+ hits: vec![serde_json::json!({+ "_score": 4.2,+ "_source": {+ "ax_path": "valkey/src/networking.c", "line": 1460,+ "body": "void addReplyNull(client *c) {\n addReplyProto(c, \"$-1\\r\\n\", 5);\n}\n",+ "symbols": [ { "name": "addReplyNull", "kind": "function", "line": 1 } ]+ }+ })],+ searches: std::sync::Mutex::new(Vec::new()),+ live: vec!["xc-kv-b1-000".to_string()],+ fail_search: false,+ }+ }+ }++ impl XcHttp for FakeHttp {+ fn get_mapping(&self, pattern: &str) -> Result<Value, String> {+ // The real adapter hands `path` to `Es::get_json`, which sends it+ // verbatim after `base` — a path without the leading `/` is a+ // malformed URL, not a 404. Assert the shape here so a regression+ // in the caller fails the tests instead of silently passing.+ assert!(+ pattern.starts_with('/'),+ "get_mapping path must be request-shaped, got {pattern:?}"+ );+ Ok(self.mapping.clone())+ }+ fn cat_indices_json(&self, _pattern: &str) -> Result<Vec<String>, String> {+ Ok(self.live.clone())+ }+ fn search(&self, index: &str, body: &Value) -> Result<Value, String> {+ self.searches+ .lock()+ .unwrap()+ .push((index.to_string(), body.clone()));+ if self.fail_search {+ return Err("transport: connection refused".to_string());+ }+ Ok(serde_json::json!({ "hits": { "hits": self.hits } }))+ }+ }++ fn root_with_state() -> std::path::PathBuf {+ let root = tempfile::tempdir().unwrap().keep();+ std::fs::create_dir_all(root.join("state")).unwrap();+ std::fs::write(+ root.join("state/kv.json"),+ format!(+ "{{\"corpus\":\"kv\",\"indexed_at\":\"{}\",\"prefix\":\"xc-kv\",\"url\":\"u\",\+ \"autoindex_exit\":0,\"salvaged\":false,\"build\":\"b1\",\+ \"index_prefix\":\"xc-kv-b1\",\"state_dir\":\"/tmp/s\"}}",+ chrono::Utc::now().format(state::STAMP_FORMAT)+ ),+ )+ .unwrap();+ std::fs::create_dir_all(root.join("corpora/kv/valkey")).unwrap();+ std::fs::write(+ root.join("corpora/kv/corpus.json"),+ "{\"corpus\":\"kv\",\"cloned_at\":\"t\",\"repos\":[{\"repo\":\"valkey\",\"url\":\"u\",\+ \"licence\":\"BSD-3-Clause\",\"sha\":\"s\"}]}",+ )+ .unwrap();+ root+ }++ #[test]+ fn bm25_query_uses_the_star_direct_glob_and_never_highlights() {+ let root = root_with_state();+ let http = FakeHttp::new();+ let out = run_code_query(+ &root,+ &http,+ "http://localhost:9200",+ &CodeParams::new("kv", "addReplyNull"),+ "`--stale-ok`",+ );+ assert_eq!(out.exit, 0);+ let (idx, body) = http.searches.lock().unwrap()[0].clone();+ assert_eq!(idx, "xc-kv-b1*", "STAR-direct glob, not the dash form");+ assert_eq!(+ body,+ serde_json::json!({+ "size": 5,+ "query": { "bool": { "must": [+ { "multi_match": { "query": "addReplyNull",+ "fields": ["body", "defs", "title"] } }+ ]}}+ }),+ "mapping-resolved fields (defs_expanded dropped); no highlight, no _source projection"+ );+ assert!(out+ .text+ .contains("─── valkey/src/networking.c:1460 (score 4.20, BSD-3-Clause)"));+ assert!(out.text.contains("function addReplyNull @ line 1"));+ assert!(out.text.contains("Cite file:line"));+ assert!(!out.is_error);+ // No field-report nudge marker was ever part of this port (dropped+ // 2026-09-18): the prose must not ask the agent to report back.+ assert!(!out.text.to_lowercase().contains("report back"));+ }++ #[test]+ fn restricted_licence_warns_under_the_passage_end_to_end() {+ let root = root_with_state();+ std::fs::write(+ root.join("corpora/kv/corpus.json"),+ "{\"corpus\":\"kv\",\"repos\":[{\"repo\":\"valkey\",\"url\":\"u\",\"licence\":\"AGPL\"}]}",+ )+ .unwrap();+ let http = FakeHttp::new();+ let out = run_code_query(+ &root,+ &http,+ "u",+ &CodeParams::new("kv", "q"),+ "`--stale-ok`",+ );+ assert!(out+ .text+ .contains("!! AGPL: adapt the APPROACH, do not copy the code"));+ }++ #[test]+ fn not_in_state_not_loaded_and_no_match_are_three_different_answers() {+ let root = root_with_state();++ // Not in the ledger at all: usage-class refusal naming the fix (exit 2).+ let out = run_code_query(+ &root,+ &FakeHttp::new(),+ "u",+ &CodeParams::new("ghost", "q"),+ "`--stale-ok`",+ );+ assert_eq!(out.exit, 2);+ assert!(out.text.contains("corpus 'ghost' is not indexed"));+ assert!(out.text.contains("xerj corpus index ghost"));++ // In the ledger, 0 live indices: the DISTINCT exit-3 diagnosis.+ let mut http = FakeHttp::new();+ http.live = vec![];+ let out = run_code_query(+ &root,+ &http,+ "http://localhost:9200",+ &CodeParams::new("kv", "q"),+ "`--stale-ok`",+ );+ assert_eq!(out.exit, 3, "not-loaded is its own exit code");+ assert!(out.text.contains("This is NOT a 'no match'"));++ // Loaded, zero hits: exit 1 with the verbatim fall-back prose.+ let mut http = FakeHttp::new();+ http.hits = vec![];+ let out = run_code_query(+ &root,+ &http,+ "u",+ &CodeParams::new("kv", "xyzzy plugh"),+ "`--stale-ok`",+ );+ assert_eq!(out.exit, 1);+ assert!(!out.is_error, "a miss is an answer, not an MCP error");+ assert!(+ out.text.contains(+ "The corpus is likely wrong for this task — fall back to normal work rather \+ than forcing a bad match."+ ),+ "verbatim fall-back prose: {}",+ out.text+ );++ // --json with zero hits: still exit 1, empty array on stdout.+ let mut p = CodeParams::new("kv", "xyzzy plugh");+ p.as_json = true;+ let out = run_code_query(&root, &http, "u", &p, "`--stale-ok`");+ assert_eq!(out.exit, 1);+ assert!(out.json.is_some());+ }++ #[test]+ fn a_stale_index_is_refused_and_stale_ok_is_the_only_override() {+ let root = root_with_state();+ let old = (chrono::Utc::now() - chrono::Duration::days(31))+ .format(state::STAMP_FORMAT)+ .to_string();+ std::fs::write(+ root.join("state/kv.json"),+ format!(+ "{{\"corpus\":\"kv\",\"indexed_at\":\"{old}\",\"prefix\":\"xc-kv\",\+ \"autoindex_exit\":0}}"+ ),+ )+ .unwrap();+ let out = run_code_query(+ &root,+ &FakeHttp::new(),+ "u",+ &CodeParams::new("kv", "q"),+ "`--stale-ok`",+ );+ assert_eq!(out.exit, 2);+ assert!(out.text.ends_with("or pass `--stale-ok`."));+ assert!(out.is_error);++ let mut p = CodeParams::new("kv", "q");+ p.stale_ok = true;+ let out = run_code_query(&root, &FakeHttp::new(), "u", &p, "`--stale-ok`");+ assert_eq!(out.exit, 0);+ }++ #[test]+ fn hybrid_is_one_native_top_level_request_with_capable_targeting() {+ let root = root_with_state();+ let mut http = FakeHttp::new();+ http.mapping = serde_json::json!({+ "xc-kv-b1-000": { "mappings": { "properties": { "body": { "type": "semantic_text" } } } },+ "xc-kv-b1-001": { "mappings": { "properties": { "body": { "type": "text" } } } }+ });+ let mut p = CodeParams::new("kv", "addReplyNull");+ p.mode = Mode::Hybrid;+ let out = run_code_query(&root, &http, "u", &p, "`--stale-ok`");+ assert_eq!(out.exit, 0);++ let reqs = http.searches.lock().unwrap();+ // [0] = BM25 preflight over the wildcard; [1] = the fused request,+ // aimed ONLY at the capable index (the plain-text sibling would 400+ // the whole wildcard).+ assert_eq!(reqs[0].0, "xc-kv-b1*");+ assert_eq!(reqs[1].0, "xc-kv-b1-000");+ let hybrid = &reqs[1].1;+ assert!(+ hybrid.pointer("/query/hybrid").is_some(),+ "ONE native top-level hybrid: {hybrid}"+ );+ assert_eq!(+ hybrid.pointer("/query/hybrid/fusion").unwrap(),+ &serde_json::json!({ "method": "rrf", "k": 60 })+ );+ assert_eq!(+ hybrid+ .pointer("/query/hybrid/queries")+ .unwrap()+ .as_array()+ .map(Vec::len),+ Some(2)+ );+ assert_eq!(hybrid.pointer("/size"), Some(&serde_json::json!(5)));+ // The arms-ran note says BOTH arms and the lexical-only exclusion.+ assert!(+ out.text+ .contains("[hybrid RRF(k=60) — BM25 over 2 index(es), vector over 1 of 2"),+ "{}",+ out.text+ );+ assert!(+ out.text.contains("rrf 4.20"),+ "hybrid scores render as rrf: {}",+ out.text+ );+ }++ #[test]+ fn hybrid_without_a_capable_index_degrades_to_bm25_and_says_so() {+ let root = root_with_state();+ let http = FakeHttp::new(); // mapping has plain text only+ let mut p = CodeParams::new("kv", "q");+ p.mode = Mode::Hybrid;+ let out = run_code_query(&root, &http, "u", &p, "`--stale-ok`");+ assert_eq!(out.exit, 0);+ assert!(+ out.text.contains("[BM25 only —"),+ "degradation is SAID: {}",+ out.text+ );+ assert_eq!(+ http.searches.lock().unwrap().len(),+ 1,+ "no fused request was sent"+ );+ }++ #[test]+ fn hybrid_reports_an_honest_miss_when_the_bm25_preflight_is_empty() {+ let root = root_with_state();+ let mut http = FakeHttp::new();+ http.mapping = serde_json::json!({+ "xc-kv-b1-000": { "mappings": { "properties": { "body": { "type": "semantic_text" } } } }+ });+ http.hits = vec![]; // preflight AND any vector hit: nothing+ let mut p = CodeParams::new("kv", "xyzzy plugh");+ p.mode = Mode::Hybrid;+ let out = run_code_query(&root, &http, "u", &p, "`--stale-ok`");+ assert_eq!(+ out.exit, 1,+ "vector confidence must not launder a lexical miss"+ );+ assert!(+ out.text.contains("fall back to normal work"),+ "{}",+ out.text+ );+ }++ #[test]+ fn transport_failure_is_exit_2_never_fake_zero_indices() {+ let root = root_with_state();+ let mut http = FakeHttp::new();+ http.fail_search = true;+ let out = run_code_query(+ &root,+ &http,+ "u",+ &CodeParams::new("kv", "q"),+ "`--stale-ok`",+ );+ assert_eq!(out.exit, 2);+ assert!(out.text.contains("search failed"), "{}", out.text);+ }+}diff --git a/engine/crates/xerj-common/src/xccode/passage.rs b/engine/crates/xerj-common/src/xccode/passage.rsnew file mode 100644index 000000000..c9217ed15--- /dev/null+++ b/engine/crates/xerj-common/src/xccode/passage.rs@@ -0,0 +1,376 @@+//! Passage selection — the difference between "search found the file" and+//! "the agent got the code".+//!+//! Measured on a real valkey corpus: a query about null replies ranks+//! networking.c correctly, but `addReplyNull` is at line 1460 — roughly 40 KB+//! in — so any head- or window-based slice of a 200 KB file is a coin flip+//! on whether the answer is inside it. The record already carries+//! `{name, kind, line}` for every definition; using them turns a guess into+//! a lookup.++use serde_json::Value;++/// Query terms: identifiers of >= 3 chars (`[A-Za-z_][A-Za-z0-9_]{2,}`).+/// Hand-rolled scanner — the ASCII class is the contract, and it must stop+/// at non-ASCII characters exactly like the original regex did.+pub fn query_terms(query: &str) -> Vec<String> {+ let mut out = Vec::new();+ let mut cur = String::new();+ for c in query.chars() {+ let ascii_word = c.is_ascii_alphanumeric() || c == '_';+ if ascii_word {+ if cur.is_empty() && !(c.is_ascii_alphabetic() || c == '_') {+ // A token never starts with a digit.+ continue;+ }+ cur.push(c);+ } else {+ if cur.len() >= 3 {+ out.push(cur.to_lowercase());+ }+ cur.clear();+ }+ }+ if cur.len() >= 3 {+ out.push(cur.to_lowercase());+ }+ out+}++/// `[(name, kind, start_line, end_line)]` from the record's own `symbols`.+/// A definition runs until the next definition starts — a coarse but honest+/// bound: it never claims a range the index did not report.+fn symbol_spans(src: &Value) -> Vec<(String, String, i64, Option<i64>)> {+ let Some(syms) = src.get("symbols").and_then(Value::as_array) else {+ return Vec::new();+ };+ let mut got: Vec<(String, String, i64)> = syms+ .iter()+ .filter(|s| s.is_object())+ .filter_map(|s| {+ let name = s.get("name").and_then(Value::as_str)?;+ let line = s.get("line").and_then(Value::as_i64)?;+ if name.is_empty() {+ return None;+ }+ Some((+ name.to_string(),+ s.get("kind")+ .and_then(Value::as_str)+ .unwrap_or("")+ .to_string(),+ line,+ ))+ })+ .collect();+ got.sort_by_key(|(_, _, line)| *line);+ got.windows(2)+ .map(|w| {+ let (name, kind, line) = w[0].clone();+ let end = w.get(1).map(|(_, _, l)| *l - 1);+ (name, kind, line, end)+ })+ .collect::<Vec<_>>()+ .into_iter()+ .chain(got.last().map(|(n, k, l)| (n.clone(), k.clone(), *l, None)))+ .collect()+}++/// The best matching DEFINITION, as `(text, label)`.+///+/// Query terms score by count-in-span; a term appearing in the symbol's NAME+/// adds 25 — the strongest signal an agent can act on: a query mentioning+/// `addReplyNull` should return addReplyNull, not whichever unrelated span+/// repeats a common word most often. Truncation keeps the label so the+/// truncation is visible.+pub fn symbol_passage(+ body: &str,+ src: &Value,+ query: &str,+ width: usize,+) -> Option<(String, String)> {+ let spans = symbol_spans(src);+ if spans.is_empty() {+ return None;+ }+ let lines: Vec<&str> = body.split('\n').collect();+ if lines.is_empty() {+ return None;+ }+ let terms = query_terms(query);+ if terms.is_empty() {+ return None;+ }+ let mut best: Option<(i64, String, String, i64, String)> = None;+ for (name, kind, start, end) in spans {+ let lo = (start - 1).max(0) as usize;+ let hi = end+ .map(|e| e as usize)+ .unwrap_or(lines.len())+ .min(lines.len());+ if hi <= lo {+ continue;+ }+ let text = lines[lo..hi].join("\n");+ let low = text.to_lowercase();+ let nm = name.to_lowercase();+ let mut score: i64 = terms.iter().map(|t| count_occurrences(&low, t)).sum();+ score += 25 * terms.iter().filter(|t| nm.contains(t.as_str())).count() as i64;+ if score <= 0 {+ continue;+ }+ if best.as_ref().is_none_or(|b| score > b.0) {+ best = Some((score, name, kind, start, text));+ }+ }+ let (_, name, kind, start, mut text) = best?;+ if py_len(&text) > width {+ text = format!(+ "{}\n ... [{kind} {name} truncated at {width} chars]",+ take_chars(&text, width)+ );+ }+ Some((text, format!("{kind} {name} @ line {start}")))+}++/// The densest sampled `width`-char window, snapped to lines when that does+/// not lose query evidence. Returns `(window, start_offset, total_len)`.+///+/// Taking the HEAD instead is the single worst bug this tool had: retrieval+/// ranked the correct files, then handed back 21,461 chars containing ZERO+/// occurrences of the terms the query was about — licence banners and+/// #include lines and nothing else.+pub fn best_window(body: &str, query: &str, width: usize) -> (String, usize, usize) {+ let cs: Vec<char> = body.chars().collect();+ let total = cs.len();+ if total <= width {+ return (body.to_string(), 0, total);+ }+ let terms = query_terms(query);+ if terms.is_empty() {+ return (take_chars(body, width), 0, total);+ }+ // Score every candidate start on a coarse stride: dense term hits win.+ // The stride keeps this linear-ish on multi-hundred-KB sources. The+ // range matches python's `range(0, total - width + stride, stride)`.+ let stride = (width / 8).max(1);+ let last_start_exclusive = total - width + stride;+ let mut best_start = 0usize;+ let mut best_score: i64 = -1;+ let mut start = 0usize;+ while start < last_start_exclusive {+ // Slice BEFORE lowercasing: Unicode lowercase can expand a character,+ // so offsets in a lowercased copy need not be offsets in the source.+ let end = (start + width).min(total);+ let chunk: String = cs[start..end].iter().collect::<String>().to_lowercase();+ let score: i64 = terms.iter().map(|t| count_occurrences(&chunk, t)).sum();+ if score > best_score {+ best_start = start;+ best_score = score;+ }+ start += stride;+ }+ if best_score <= 0 {+ return (take_chars(body, width), 0, total);+ }+ // Prefer complete lines, but never discard query evidence just to align+ // them: the final partial line may hold the match. The end snaps to the+ // LAST newline inside the window (xc.py's `rfind`), not the first —+ // cutting at the first would throw away the tail that earned the score.+ let nl = cs[..best_start].iter().rposition(|&c| c == '\n');+ let start2 = nl.map(|i| i + 1).unwrap_or(best_start);+ let end2 = cs[start2..(start2 + width).min(total)]+ .iter()+ .rposition(|&c| c == '\n')+ .map(|i| start2 + i);+ let end2 = match end2 {+ Some(e) if e > start2 => e,+ _ => (start2 + width).min(total),+ };+ let snapped: String = cs[start2..end2].iter().collect::<String>().to_lowercase();+ let snapped_score: i64 = terms.iter().map(|t| count_occurrences(&snapped, t)).sum();+ if snapped_score < best_score {+ let win: String = cs[best_start..(best_start + width).min(total)]+ .iter()+ .collect();+ return (win, best_start, total);+ }+ let win: String = cs[start2..end2].iter().collect();+ (win, start2, total)+}++/// `file:line`, or the best locator the record actually carries. NEVER an+/// invented line number — a fabricated citation is worse than none, because+/// it survives review by looking checkable.+pub fn provenance(src: &Value) -> String {+ let path = ["ax_path", "ax_file", "path", "file"]+ .iter()+ .find_map(|k| src.get(*k).and_then(Value::as_str))+ .unwrap_or("?");+ let line = ["line", "start_line", "lineno"]+ .iter()+ .find_map(|k| src.get(*k).and_then(Value::as_u64))+ .filter(|n| *n != 0);+ match line {+ Some(n) => format!("{path}:{n}"),+ None => path.to_string(),+ }+}++/// The repo a hit's locator belongs to: the first path segment (`repo/file.rs`+/// -> `repo`), which keys the licence map. A locator with no `/` carries no+/// repo — `""`, which simply misses in the map (no licence line).+pub fn locator_repo(loc: &str) -> &str {+ match loc.split_once('/') {+ Some((repo, _)) => repo,+ None => "",+ }+}++/// Non-overlapping occurrences, python `str.count` semantics.+pub(crate) fn count_occurrences(haystack: &str, needle: &str) -> i64 {+ if needle.is_empty() {+ return 0;+ }+ haystack.match_indices(needle).count() as i64+}++/// Python `len(str)` — code points, not bytes. Every char count in the+/// contract (label sizes, window offsets, truncation) is in code points.+pub(crate) fn py_len(s: &str) -> usize {+ s.chars().count()+}++/// Python `s[:n]` — code-point slice, never panics on a boundary.+pub(crate) fn take_chars(s: &str, n: usize) -> String {+ s.chars().take(n).collect()+}++/// `1234567` -> `"1,234,567"` (python `{:,}`).+pub(crate) fn commaus(n: usize) -> String {+ let digits = n.to_string();+ let mut out = String::with_capacity(digits.len() + digits.len() / 3);+ for (i, c) in digits.chars().enumerate() {+ if i > 0 && (digits.len() - i).is_multiple_of(3) {+ out.push(',');+ }+ out.push(c);+ }+ out+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ #[test]+ fn terms_are_ascii_identifiers_of_three_or_more_chars() {+ assert_eq!(+ query_terms("addReplyNull handles $-1 and CRLF"),+ vec!["addreplynull", "handles", "and", "crlf"]+ );+ assert!(query_terms("a b xy").is_empty());+ // Non-ASCII ends a token, exactly like the original regex class:+ // "xerjö" still yields the ASCII prefix "xerj" (4 chars, kept).+ assert_eq!(query_terms("xerjö code"), vec!["xerj", "code"]);+ }++ #[test]+ fn symbol_passage_picks_the_named_definition_and_truncates_visibly() {+ let body = "int filler(void) { return 0; }\n\+ void addReplyNull(client *c) {\n\+ addReplyProto(c, \"$-1\\r\\n\", 5);\n\+ }\n\+ void other(void) { addReplyNull(0); }\n";+ let src = json!({+ "symbols": [+ { "name": "filler", "kind": "function", "line": 1 },+ { "name": "addReplyNull", "kind": "function", "line": 2 },+ { "name": "other", "kind": "function", "line": 5 }+ ]+ });+ let (text, label) = symbol_passage(body, &src, "addReplyNull null reply", 800).unwrap();+ assert_eq!(label, "function addReplyNull @ line 2");+ assert!(+ text.contains("addReplyProto"),+ "the definition body: {text}"+ );+ assert!(!text.contains("filler"));++ // Truncation keeps the label so it is visible.+ let (short, _) = symbol_passage(body, &src, "addReplyNull", 20).unwrap();+ assert!(+ short.contains("[function addReplyNull truncated at 20 chars]"),+ "{short}"+ );++ // No symbols / no matching term -> None (caller falls back).+ assert!(symbol_passage(body, &json!({}), "addReplyNull", 800).is_none());+ assert!(symbol_passage(body, &src, "zzzzz", 800).is_none());+ }++ #[test]+ fn best_window_is_densest_and_snaps_only_without_evidence_loss() {+ let body = format!(+ "{}{}",+ "A".repeat(200) + "\nmatch term here\n",+ "B".repeat(200)+ );+ let (win, _start, total) = best_window(&body, "match term here", 24);+ assert!(win.contains("match term here"), "the densest window: {win}");+ assert_eq!(total, body.chars().count());++ // A query with no terms gets the head, labelled as such by the caller.+ let (win, start, _) = best_window(&body, "$ $$", 16);+ assert_eq!(start, 0);+ assert_eq!(win.chars().count(), 16);+ }++ #[test]+ fn window_offsets_survive_unicode_expansion_in_lowercase() {+ // Lowercasing can EXPAND characters; offsets must stay source-true.+ // 'İ' (U+0130) lowercases to two chars in some paths — use a multi-byte+ // mix around the match so a byte/char/lowercase confusion shows.+ let body = format!("{}matchpoint{}", "ÄÖÜ".repeat(30), "äöü".repeat(30));+ let (win, _s, _t) = best_window(&body, "matchpoint", 12);+ assert!(+ win.contains("matchpoint"),+ "window must hold the match: {win:?}"+ );+ }++ #[test]+ fn provenance_prefers_ax_fields_and_never_invents_a_line() {+ assert_eq!(+ provenance(&json!({ "ax_path": "repo/a.c", "path": "x", "line": 12 })),+ "repo/a.c:12"+ );+ assert_eq!(+ provenance(&json!({ "ax_file": "repo/b.c", "start_line": 3 })),+ "repo/b.c:3"+ );+ assert_eq!(provenance(&json!({ "path": "repo/c.c" })), "repo/c.c");+ assert_eq!(+ provenance(&json!({ "file": "d.c", "lineno": 0 })),+ "d.c",+ "line 0 is absent, not a line"+ );+ assert_eq!(provenance(&json!({})), "?");+ }++ #[test]+ fn locator_repo_is_the_first_path_segment() {+ assert_eq!(locator_repo("valkey/src/networking.c"), "valkey");+ assert_eq!(locator_repo("plain.rs"), "");+ }++ #[test]+ fn commaus_matches_python_formatting() {+ assert_eq!(commaus(0), "0");+ assert_eq!(commaus(999), "999");+ assert_eq!(commaus(1_000), "1,000");+ assert_eq!(commaus(21_461), "21,461");+ assert_eq!(commaus(1_234_567), "1,234,567");+ }+}diff --git a/engine/crates/xerj-common/src/xccode/pathgate.rs b/engine/crates/xerj-common/src/xccode/pathgate.rsnew file mode 100644index 000000000..5e8dec0f0--- /dev/null+++ b/engine/crates/xerj-common/src/xccode/pathgate.rs@@ -0,0 +1,154 @@+//! The hard gate every manifest-derived path passes BEFORE anything is built+//! from it.+//!+//! A hub manifest is UNTRUSTED INPUT: `--from` is documented as "rebuild a+//! corpus someone else defined", so the file arrives from a hub, a chat+//! message or a pull request, and every field in it is attacker-controlled.+//! `repo` becomes a filesystem path (`corpora/<name>/<repo>`) that the+//! lifecycle then runs `git checkout --force` and `git clean -fd` inside, so+//! a name like `../../../work/repo` walks out of ~/.xerj-code and destroys+//! uncommitted work in an unrelated checkout.+//!+//! The original script validated twice (python then bash) because of the+//! checkout; the port validates ONCE, unskippably, before any path exists.++/// Subcommand nouns a corpus name must not shadow — `xerj corpus list` sorts+/// by these words' meaning, and a corpus called "index" or "list" makes the+/// lifecycle's own help text ambiguous.+pub const RESERVED_CORPUS_NAMES: &[&str] = &[+ "code", "corpus", "add", "index", "list", "def", "search", "help",+];++/// Validate a corpus name: no `/` (no path escape), no `*` (no glob+/// injection into index patterns), no leading `.` (no hidden dir, no `..`),+/// not empty, not a reserved subcommand noun.+pub fn valid_corpus_name(name: &str) -> Result<(), String> {+ if name.is_empty() {+ return Err("corpus name must not be empty".to_string());+ }+ if name.contains('/') {+ return Err(format!(+ "bad corpus name '{name}': it becomes a directory under the corpora root, so \+ '/' would escape it"+ ));+ }+ if name.contains('*') {+ return Err(format!(+ "bad corpus name '{name}': '*' would be interpreted as an index wildcard"+ ));+ }+ if name.starts_with('.') {+ return Err(format!(+ "bad corpus name '{name}': a leading '.' hides the corpus directory"+ ));+ }+ if RESERVED_CORPUS_NAMES.contains(&name) {+ return Err(format!(+ "corpus name '{name}' is reserved — it is a subcommand of `xerj code`/`xerj corpus`"+ ));+ }+ Ok(())+}++/// Validate a repo name from an untrusted manifest: `^[A-Za-z0-9_][A-Za-z0-9._-]*$`.+///+/// The message says WHY because the rule looks arbitrary until the checkout+/// is mentioned: this name becomes a path that is then force-checked-out and+/// cleaned.+pub fn valid_repo_name(repo: &str) -> Result<(), String> {+ let mut chars = repo.chars();+ let first_ok = chars+ .next()+ .is_some_and(|c| c.is_ascii_alphanumeric() || c == '_');+ let rest_ok = chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'));+ if first_ok && rest_ok {+ return Ok(());+ }+ Err(format!(+ "repo name '{repo}' is not a plain directory name. It is used as a path under the \+ corpus directory and is then force-checked-out and cleaned, so a name containing \+ '/' or '..' would overwrite files outside the corpus. Allowed: letters, digits, \+ '.', '_' and '-', not starting with '.' or '-'."+ ))+}++/// Validate a pinned sha: full 40 lowercase hex.+///+/// A short sha is not fetchable from a remote (`git fetch --depth 1 origin+/// <short>` fails with "couldn't find remote ref"), so a manifest carrying+/// one would rebuild silently at the tip — the opposite of a pin. Fail+/// loudly, with the regeneration advice, instead.+pub fn valid_sha(repo: &str, sha: &str) -> Result<(), String> {+ let full_hex = sha.len() == 40 && sha.chars().all(|c| c.is_ascii_hexdigit());+ // The detector records what git prints; lowercase is the convention, but+ // rejecting uppercase would break manifests written by tools that+ // uppercase — accept either case, both are full shas.+ if full_hex {+ Ok(())+ } else {+ Err(format!(+ "repo '{repo}' has sha '{sha}', which is not a full 40-character sha. A short \+ sha is not fetchable from a remote, so this manifest cannot pin a rebuild. \+ Regenerate it with `xerj corpus add <name> <url>...` on a machine that has \+ the corpus."+ ))+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn unsafe_corpus_names_are_rejected_before_any_path_is_built() {+ for bad in ["", "/", "a/b", "*", "a*b", ".", "..", ".hidden"] {+ assert!(valid_corpus_name(bad).is_err(), "{bad:?} must be rejected");+ }+ for reserved in RESERVED_CORPUS_NAMES {+ assert!(+ valid_corpus_name(reserved).is_err(),+ "'{reserved}' is a subcommand noun"+ );+ }+ for good in ["kv", "xerj-search", "battle-terse", "rust_text", "c++"] {+ assert!(valid_corpus_name(good).is_ok(), "{good:?} is a fine name");+ }+ }++ #[test]+ fn unsafe_repo_names_are_rejected_with_the_path_escape_reason() {+ for bad in [+ "../escape",+ "a/b",+ ".hidden",+ "-flag",+ "",+ "repo name",+ "$(boom)",+ ] {+ let err = valid_repo_name(bad).unwrap_err();+ assert!(+ err.contains("force-checked-out"),+ "the message must say why: {err}"+ );+ }+ for good in ["valkey", "ClickHouse", "x_2", "a.b-c", "Sled"] {+ assert!(valid_repo_name(good).is_ok(), "{good:?}");+ }+ }++ #[test]+ fn short_shas_are_rejected_with_regen_advice() {+ let err = valid_sha("valkey", "e449d17").unwrap_err();+ assert!(+ err.contains("not a full 40-character sha")+ && err.contains("Regenerate it with `xerj corpus add"),+ "{err}"+ );+ let ok = "31081d9f05014003321333553bb3e657eb3da168";+ assert!(valid_sha("ClickHouse", ok).is_ok());+ assert!(valid_sha("ClickHouse", &ok.to_uppercase()).is_ok());+ assert!(valid_sha("x", &format!("{ok}1")).is_err(), "41 chars");+ assert!(valid_sha("x", "zzz").is_err());+ }+}diff --git a/engine/crates/xerj-common/src/xccode/render.rs b/engine/crates/xerj-common/src/xccode/render.rsnew file mode 100644index 000000000..d267ed5ff--- /dev/null+++ b/engine/crates/xerj-common/src/xccode/render.rs@@ -0,0 +1,426 @@+//! The ONE output renderer. `xerj code` prints its `text`; the+//! `xerj_code_search` MCP tool returns the same bytes as its payload — parity+//! pinned by test, because two renderers always drift.++use std::collections::HashMap;++use serde_json::Value;++use super::licence;+use super::passage::{+ best_window, commaus, locator_repo, provenance, py_len, symbol_passage, take_chars,+};++/// How to render the hit list.+pub struct RenderOpts<'a> {+ pub corpus: &'a str,+ pub query: &'a str,+ /// Max chars per passage; 0 = file-head mode (first 400 chars, labelled+ /// as the file head — never passed off as a matching passage).+ pub full: usize,+ pub no_symbol: bool,+ pub meatl: bool,+ /// Show `rrf {x:.4}` (native hybrid) instead of `score {x:.2}`. The+ /// per-leg `[bm25 #r, vec #r]` annotation is deliberately gone: the+ /// server-side fuser exposes no per-leg ranks, and the every-run arms+ /// note carries which arms ran.+ pub rrf_scores: bool,+ pub age_days: Option<i64>,+ /// MCP `licence_policy:"strict"`: restricted hits keep locator + licence+ /// + warning but lose the passage text. The CLI passes false (warn).+ pub strict_licence: bool,+}++/// Render the full result block: the optional arms-ran note line, one block+/// per hit, the footer. `note` is printed EVERY time it exists — a silently+/// BM25-only "hybrid" result must never read as hybrid.+pub fn render(+ hits: &[Value],+ licences: &HashMap<String, String>,+ opts: &RenderOpts,+ note: Option<&str>,+) -> String {+ let mut out = String::new();+ if let Some(n) = note {+ out.push_str(¬e_line(n, opts.meatl));+ out.push('\n');+ }+ for h in hits {+ out.push_str(&render_hit(h, licences, opts));+ }+ if !opts.meatl {+ out.push('\n');+ out.push_str(&format!("{} passages from '{}'", hits.len(), opts.corpus));+ if opts.age_days.is_some_and(|d| d > 0) {+ out.push_str(&format!(" (index {}d old)", opts.age_days.unwrap_or(0)));+ }+ out.push_str("\nCite file:line for anything you rely on.\n");+ }+ out+}++/// The no-match text. Explicit, because a silent miss makes the next agent+/// re-run the same dead query — this is the line that stops the loop.+pub fn no_match_text(corpus: &str, query: &str, meatl: bool) -> String {+ if meatl {+ format!("@no q=\"{query}\" why=no-match-in-corpus\n")+ } else {+ format!(+ "No passage in '{corpus}' matches: {query}\n\+ The corpus is likely wrong for this task — fall back to normal work \+ rather than forcing a bad match.\n"+ )+ }+}++fn note_line(note: &str, meatl: bool) -> String {+ if meatl {+ format!("@mode {note}")+ } else {+ format!("[{note}]")+ }+}++fn render_hit(h: &Value, licences: &HashMap<String, String>, opts: &RenderOpts) -> String {+ let src = h.get("_source").cloned().unwrap_or(Value::Null);+ let loc = provenance(&src);+ let score = h.get("_score").and_then(Value::as_f64).unwrap_or(0.0);+ let lic = licences+ .get(locator_repo(&loc))+ .cloned()+ .unwrap_or_default();+ let restricted = !lic.is_empty() && licence::is_restricted(&lic);++ if opts.meatl {+ let shown = if opts.rrf_scores {+ format!("rrf={score:.4}")+ } else {+ format!("score={score:.2}")+ };+ let why = if lic.is_empty() {+ String::new()+ } else {+ format!(" why={lic}")+ };+ return format!("@ok f={loc} {shown}{why}\n");+ }++ let shown = if opts.rrf_scores {+ format!("rrf {score:.4}")+ } else {+ format!("score {score:.2}")+ };+ let lic_part = if lic.is_empty() {+ String::new()+ } else {+ format!(", {lic}")+ };+ let mut out = format!("\n─── {loc} ({shown}{lic_part})\n");++ let body = src+ .get("body")+ .and_then(Value::as_str)+ .unwrap_or("")+ .to_string();++ if opts.full > 0 && !(restricted && opts.strict_licence) {+ // Prefer the matching DEFINITION over a byte window; fall back to the+ // window only when the record carries no usable symbols (a data+ // file, or a language whose extractor found nothing — issue #170).+ let sp = if opts.no_symbol {+ None+ } else {+ symbol_passage(&body, &src, opts.query, opts.full)+ };+ match sp {+ Some((text, label)) => {+ out.push_str(&format!(+ " [{label} — {} of {} chars]\n",+ commaus(py_len(&text)),+ commaus(py_len(&body))+ ));+ out.push_str(&text);+ out.push('\n');+ }+ None => {+ let (window, start, total) = best_window(&body, opts.query, opts.full);+ if total > py_len(&window) {+ out.push_str(&format!(+ " [no symbol match; showing {} of {} chars from offset {}, \+ window centred on the match]\n",+ commaus(py_len(&window)),+ commaus(total),+ commaus(start)+ ));+ }+ out.push_str(&window);+ out.push('\n');+ }+ }+ } else if opts.full > 0 {+ // strict licence policy: the code itself is the thing not to hand+ // over; provenance and the warning stay.+ out.push_str(" [passage withheld: restricted licence (licence_policy strict)]\n");+ } else {+ // Only reachable via `--full 0`. No highlight is ever requested+ // (issue #177 — it reorders hits), so this is the file head and is+ // labelled as such rather than passed off as a matching passage.+ let head = take_chars(&body, 400);+ if py_len(&body) > py_len(&head) {+ out.push_str(&format!(+ " [file head; {} of {} chars — pass --full N for the matching definition]\n",+ commaus(py_len(&head)),+ commaus(py_len(&body))+ ));+ }+ out.push_str(&format!(" {}\n", head.replace('\n', "\n ")));+ }++ if restricted {+ out.push_str(&licence::hit_warning_line(&lic));+ out.push('\n');+ }+ out+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ fn hit(loc_fields: Value, body: &str, symbols: Value, score: f64) -> Value {+ let mut src = loc_fields;+ src["body"] = json!(body);+ if !symbols.is_null() {+ src["symbols"] = symbols;+ }+ json!({ "_source": src, "_score": score })+ }++ fn apache_hit() -> Value {+ hit(+ json!({ "ax_path": "tantivy/src/reader.rs", "line": 30 }),+ "impl SegmentReader {\n pub fn rebuild(&self) {}\n}\n",+ json!([{ "name": "rebuild", "kind": "method", "line": 2 }]),+ 12.345,+ )+ }++ fn agpl_hit() -> Value {+ hit(+ json!({ "ax_path": "elasticsearch/server/src/main/Node.java", "line": 80 }),+ "class Node {\n void start() {}\n}\n",+ json!([{ "name": "start", "kind": "method", "line": 2 }]),+ 9.01,+ )+ }++ fn licences() -> HashMap<String, String> {+ HashMap::from([+ ("tantivy".to_string(), "Apache-2.0/MIT".to_string()),+ ("elasticsearch".to_string(), "AGPL".to_string()),+ ])+ }++ #[test]+ fn prose_hits_carry_loc_score_licence_passage_and_footer() {+ let hits = vec![apache_hit()];+ let text = render(+ &hits,+ &licences(),+ &RenderOpts {+ corpus: "xerj-search",+ query: "rebuild segment reader",+ full: 800,+ no_symbol: false,+ meatl: false,+ rrf_scores: false,+ age_days: Some(3),+ strict_licence: false,+ },+ None,+ );+ assert!(+ text.starts_with("\n─── tantivy/src/reader.rs:30 (score 12.35, Apache-2.0/MIT)\n"),+ "{text}"+ );+ assert!(text.contains(" [method rebuild @ line 2 — "), "{text}");+ assert!(+ text.contains("1 passages from 'xerj-search' (index 3d old)"),+ "{text}"+ );+ assert!(text.ends_with("Cite file:line for anything you rely on.\n"));+ // Compatible licence: no warning line.+ assert!(!text.contains("!!"), "{text}");+ }++ #[test]+ fn restricted_hits_carry_the_warning_under_the_passage() {+ let text = render(+ &[agpl_hit()],+ &licences(),+ &RenderOpts {+ corpus: "xerj-search",+ query: "start node",+ full: 800,+ no_symbol: false,+ meatl: false,+ rrf_scores: false,+ age_days: None,+ strict_licence: false,+ },+ None,+ );+ let passage_at = text.find("void start()").expect("passage present");+ let warn_at = text+ .find(" !! AGPL: adapt the APPROACH, do not copy the code")+ .expect("warning");+ assert!(warn_at > passage_at, "the warning sits UNDER the passage");+ assert!(text.contains("(score 9.01, AGPL)"), "{text}");+ }++ #[test]+ fn strict_licence_strips_the_passage_but_keeps_provenance_and_warning() {+ let text = render(+ &[agpl_hit()],+ &licences(),+ &RenderOpts {+ corpus: "xerj-search",+ query: "start node",+ full: 800,+ no_symbol: false,+ meatl: false,+ rrf_scores: false,+ age_days: None,+ strict_licence: true,+ },+ None,+ );+ assert!(+ !text.contains("void start()"),+ "no code handed over: {text}"+ );+ assert!(+ text.contains("─── elasticsearch/server/src/main/Node.java:80"),+ "{text}"+ );+ assert!(text.contains("!! AGPL"), "{text}");+ // Compatible corpora are untouched by strict mode.+ let ok = render(+ &[apache_hit()],+ &licences(),+ &RenderOpts {+ corpus: "xerj-search",+ query: "rebuild",+ full: 800,+ no_symbol: false,+ meatl: false,+ rrf_scores: false,+ age_days: None,+ strict_licence: true,+ },+ None,+ );+ assert!(ok.contains("pub fn rebuild"), "{ok}");+ }++ #[test]+ fn full_zero_is_the_labelled_file_head() {+ let text = render(+ &[apache_hit()],+ &licences(),+ &RenderOpts {+ corpus: "c",+ query: "rebuild",+ full: 0,+ no_symbol: false,+ meatl: false,+ rrf_scores: false,+ age_days: None,+ strict_licence: false,+ },+ None,+ );+ assert!(+ text.contains(+ "[file head; 58 of 58 chars — pass --full N for the matching definition]"+ ) || text.contains("impl SegmentReader {"),+ "{text}"+ );+ // head only, no definition chase+ assert!(!text.contains("@ line"), "{text}");+ }++ #[test]+ fn meatl_is_one_line_per_hit_with_licence_and_mode_notes() {+ let hits = vec![agpl_hit(), apache_hit()];+ let text = render(+ &hits,+ &licences(),+ &RenderOpts {+ corpus: "xerj-search",+ query: "start",+ full: 800,+ no_symbol: false,+ meatl: true,+ rrf_scores: false,+ age_days: Some(2),+ strict_licence: false,+ },+ Some("hybrid RRF(k=60) — BM25 over 9 index(es), vector over 3 of 9"),+ );+ assert!(+ text.starts_with(+ "@mode hybrid RRF(k=60) — BM25 over 9 index(es), vector over 3 of 9\n"+ ),+ "{text}"+ );+ assert!(+ text.contains("@ok f=elasticsearch/server/src/main/Node.java:80 score=9.01 why=AGPL\n"),+ "{text}"+ );+ assert!(+ text.contains("@ok f=tantivy/src/reader.rs:30 score=12.35 why=Apache-2.0/MIT\n"),+ "{text}"+ );+ assert!(+ !text.contains("passages from"),+ "no footer in meatl: {text}"+ );+ }++ #[test]+ fn rrf_scores_render_four_decimals_without_per_leg_ranks() {+ let text = render(+ &[agpl_hit()],+ &licences(),+ &RenderOpts {+ corpus: "c",+ query: "q",+ full: 800,+ no_symbol: false,+ meatl: false,+ rrf_scores: true,+ age_days: None,+ strict_licence: false,+ },+ None,+ );+ assert!(text.contains("(rrf 9.0100, AGPL)"), "{text}");+ assert!(!text.contains("[bm25 #"), "per-leg ranks are gone: {text}");+ }++ #[test]+ fn no_match_prose_and_meatl_shapes_are_verbatim() {+ assert_eq!(+ no_match_text("kv", "two-way substring", false),+ "No passage in 'kv' matches: two-way substring\n\+ The corpus is likely wrong for this task — fall back to normal work rather \+ than forcing a bad match.\n"+ );+ assert_eq!(+ no_match_text("kv", "xyzzy", true),+ "@no q=\"xyzzy\" why=no-match-in-corpus\n"+ );+ }+}diff --git a/engine/crates/xerj-common/src/xccode/state.rs b/engine/crates/xerj-common/src/xccode/state.rsnew file mode 100644index 000000000..30d9f6c2b--- /dev/null+++ b/engine/crates/xerj-common/src/xccode/state.rs@@ -0,0 +1,456 @@+//! The corpus state ledger: `{root}/state/<corpus>.json`.+//!+//! The ledger records that a corpus was indexed, against which URL, and —+//! since the #930 build-verify-swap — WHICH build was verified. Two prefixes+//! on purpose: `prefix` (`xc-<corpus>`, the whole namespace, unchanged since+//! the first release so anything that globs on it keeps working) and+//! `index_prefix` (`xc-<corpus>-b<stamp>`, the ONE verified build). Querying+//! the exact build keeps a half-built replacement — or a retired build whose+//! delete failed — out of the answers.+//!+//! The schema is FROZEN: a renamed field would silently orphan every existing+//! corpus. Legacy files (written before builds existed, no+//! `build`/`index_prefix`/`state_dir`) parse via hand-rolled tolerant reads+//! and select legacy mode in `xerj corpus index`.++use std::path::Path;++use chrono::{DateTime, Utc};+use serde_json::{json, Value};++use super::STALE_DAYS;++/// One parsed state file. Every field optional; unknown fields ignored.+#[derive(Debug, Clone, Default)]+pub struct CorpusState {+ pub corpus: Option<String>,+ pub indexed_at: Option<String>,+ pub prefix: Option<String>,+ pub url: Option<String>,+ /// int normally; a bool is tolerated as "finished" (older writers wrote+ /// the shell's idea of a boolean here).+ pub autoindex_exit: Option<Value>,+ pub salvaged: Option<bool>,+ pub build: Option<String>,+ pub index_prefix: Option<String>,+ pub state_dir: Option<String>,+}++impl CorpusState {+ fn from_value(v: &Value) -> CorpusState {+ let s = |k: &str| v.get(k).and_then(Value::as_str).map(str::to_string);+ CorpusState {+ corpus: s("corpus"),+ indexed_at: s("indexed_at"),+ prefix: s("prefix"),+ url: s("url"),+ autoindex_exit: v.get("autoindex_exit").cloned().filter(|x| !x.is_null()),+ salvaged: v.get("salvaged").and_then(Value::as_bool),+ build: s("build"),+ index_prefix: s("index_prefix"),+ state_dir: s("state_dir"),+ }+ }++ /// The corpus's own name for itself, falling back to the caller's.+ pub fn name(&self, fallback: &str) -> String {+ self.corpus.clone().unwrap_or_else(|| fallback.to_string())+ }+}++/// Read `{root}/state/{corpus}.json`. Missing → the actionable refusal that+/// names the command that fixes it.+pub fn load_state(root: &Path, corpus: &str) -> Result<CorpusState, String> {+ let path = root.join("state").join(format!("{corpus}.json"));+ let raw = std::fs::read_to_string(&path).map_err(|_| {+ format!("corpus '{corpus}' is not indexed — run `xerj corpus index {corpus}` first")+ })?;+ let v: Value = serde_json::from_str(&raw)+ .map_err(|e| format!("state file {} is not valid JSON: {e}", path.display()))?;+ Ok(CorpusState::from_value(&v))+}++/// The index prefix to query: the verified build when the ledger names one,+/// else the namespace, else the conventional `xc-<corpus>`.+pub fn query_prefix(st: &CorpusState) -> String {+ st.index_prefix+ .clone()+ .or_else(|| st.prefix.clone())+ .unwrap_or_else(|| format!("xc-{}", st.name("")))+}++/// Staleness: an index older than [`STALE_DAYS`] days is REFUSED, not served.+///+/// A missing or unparsable stamp disables the check (and the footer's age):+/// never refuse on an unreadable clock. `Ok(None)` = no age known.+///+/// `Err` carries the exact refusal text — it names the re-index command and+/// the one override the caller's surface accepts (`stale_hint`: "`--stale-ok`"+/// on the CLI, "`stale_ok:true`" on MCP). There is no env bypass: a wrapper+/// must not be able to silently de-fang the refusal.+pub fn check_fresh(+ st: &CorpusState,+ stale_ok: bool,+ stale_hint: &str,+) -> Result<Option<i64>, String> {+ let Some(stamp) = st.indexed_at.as_deref() else {+ return Ok(None);+ };+ let Some(dt) = parse_stamp(stamp) else {+ return Ok(None);+ };+ let age = Utc::now().signed_duration_since(dt).num_days();+ if age > STALE_DAYS && !stale_ok {+ let corpus = st.name("");+ return Err(format!(+ "index for '{corpus}' is {age} days old. Re-run `xerj corpus index {corpus} --fresh`, \+ or pass {stale_hint}."+ ));+ }+ Ok(Some(age))+}++/// The ledger's own word that this index came from a run that did not finish.+///+/// `autoindex_exit` 0 is clean, 3 is "completed with junk/refused datasets"+/// (both finished); a bool is tolerated as finished. Anything else, or+/// `salvaged: true`, means coverage is NOT verified — and a miss against a+/// half-built corpus must never read as "this code does not exist".+pub fn incomplete_coverage(st: &CorpusState) -> Option<String> {+ if exit_is_finished(st.autoindex_exit.as_ref()) && st.salvaged != Some(true) {+ return None;+ }+ let corpus = st.name("");+ let why = match (&st.autoindex_exit, st.salvaged == Some(true)) {+ (Some(v), true) => format!("autoindex exit {v}, kept unverified"),+ (None, true) => "no autoindex exit recorded, kept unverified".to_string(),+ (Some(v), false) => format!("autoindex exit {v}"),+ (None, false) => "no autoindex exit recorded".to_string(),+ };+ Some(format!(+ "WARNING: the index for '{corpus}' was NOT verified complete ({why}). A miss here \+ might mean 'not indexed yet', not 'does not exist'. \+ Re-run `xerj corpus index {corpus}` to resume or confirm it."+ ))+}++/// The DISTINCT not-loaded-here diagnosis (exit 3, not the no-match exit 1).+///+/// "0 live indices here" and "the corpus is loaded but nothing matched" are+/// different diagnoses with different fixes; collapsing them is the bug this+/// guard closes. The hint says where the corpus WAS indexed when the ledger+/// knows a different URL than the one being queried.+pub fn not_loaded_message(st: &CorpusState, prefix: &str, url: &str) -> String {+ let corpus = st.name("");+ let indexed_at = st.indexed_at.clone().unwrap_or_else(|| "?".to_string());+ let where_hint = match &st.url {+ Some(recorded) if recorded != url => {+ format!(" It was indexed against {recorded}.")+ }+ _ => " It was indexed against a different data dir or server.".to_string(),+ };+ format!(+ "corpus '{corpus}' is in state/ (indexed {indexed_at}) but has 0 live indices \+ ('{prefix}*') on {url}.{where_hint} \+ Re-run: xerj corpus index {corpus}, or set XERJ_URL to the node that has it. \+ (This is NOT a 'no match' — the corpus simply is not loaded on this server.)"+ )+}++/// Whether an `autoindex_exit` value counts as "the run finished".+fn exit_is_finished(rc: Option<&Value>) -> bool {+ match rc {+ None => true,+ Some(Value::Bool(_)) => true,+ Some(Value::Number(n)) => n.as_i64().map(|i| i == 0 || i == 3).unwrap_or(false),+ Some(_) => false,+ }+}++/// The state file's stamp format, written and read verbatim:+/// `%Y-%m-%dT%H:%M:%SZ` UTC (what `xc-index.sh` wrote; unchanged).+pub const STAMP_FORMAT: &str = "%Y-%m-%dT%H:%M:%SZ";++/// Parse a stamp in the ledger's exact format (also accepts general RFC3339).+fn parse_stamp(stamp: &str) -> Option<DateTime<Utc>> {+ if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(stamp, STAMP_FORMAT) {+ return Some(dt.and_utc());+ }+ DateTime::parse_from_rfc3339(stamp)+ .ok()+ .map(|dt| dt.with_timezone(&Utc))+}++/// Write the ledger ATOMICALLY (tmp + rename): a reader sees the old build or+/// the new one, never half. Key order and names are byte-identical to the+/// script's writer — a renamed field would silently orphan every corpus.+#[allow(clippy::too_many_arguments)]+pub fn write_state(+ root: &Path,+ corpus: &str,+ url: &str,+ rc: i64,+ salvaged: bool,+ build: Option<&str>,+ index_prefix: Option<&str>,+ state_dir: Option<&str>,+) -> std::io::Result<()> {+ let mut state = json!({+ "corpus": corpus,+ "indexed_at": Utc::now().format(STAMP_FORMAT).to_string(),+ "prefix": format!("xc-{corpus}"),+ "url": url,+ "autoindex_exit": rc,+ "salvaged": salvaged+ });+ if let (Some(b), Some(ip), Some(sd)) = (build, index_prefix, state_dir) {+ let obj = state.as_object_mut().unwrap();+ obj.insert("build".into(), json!(b));+ obj.insert("index_prefix".into(), json!(ip));+ obj.insert("state_dir".into(), json!(sd));+ }+ let dir = root.join("state");+ std::fs::create_dir_all(&dir)?;+ let path = dir.join(format!("{corpus}.json"));+ let tmp = dir.join(format!(".{corpus}.json.tmp"));+ // Compact separators, trailing newline — the script's exact bytes.+ std::fs::write(&tmp, format!("{state}\n"))?;+ std::fs::rename(&tmp, &path)+}++#[cfg(test)]+mod tests {+ use super::*;++ fn state_file(root: &Path, corpus: &str) -> std::path::PathBuf {+ root.join("state").join(format!("{corpus}.json"))+ }++ fn write(root: &Path, corpus: &str, body: &str) {+ let p = state_file(root, corpus);+ std::fs::create_dir_all(p.parent().unwrap()).unwrap();+ std::fs::write(p, body).unwrap();+ }++ #[test]+ fn missing_state_names_the_command_that_fixes_it() {+ let root = tempfile::tempdir().unwrap();+ let err = load_state(root.path(), "nope").unwrap_err();+ assert!(+ err.contains("corpus 'nope' is not indexed") && err.contains("xerj corpus index nope"),+ "must name the corpus and the fix command: {err}"+ );+ }++ #[test]+ fn legacy_state_parses_and_prefix_falls_back_in_order() {+ // A pre-#930 file: no build fields. Resolution must fall back+ // index_prefix -> prefix -> xc-{corpus}.+ let root = tempfile::tempdir().unwrap();+ write(+ root.path(),+ "old",+ r#"{"corpus":"old","indexed_at":"2026-01-02T03:04:05Z","prefix":"xc-old","url":"http://localhost:9200","autoindex_exit":0}"#,+ );+ let st = load_state(root.path(), "old").unwrap();+ assert_eq!(query_prefix(&st), "xc-old");++ let mut st2 = st.clone();+ st2.prefix = None;+ assert_eq!(query_prefix(&st2), "xc-old", "corpus name fallback");++ // A #930 file: the VERIFIED build wins over the namespace.+ write(+ root.path(),+ "new",+ r#"{"corpus":"new","prefix":"xc-new","index_prefix":"xc-new-b20260801","build":"b20260801","state_dir":"/tmp/s","autoindex_exit":0,"salvaged":false}"#,+ );+ let st3 = load_state(root.path(), "new").unwrap();+ assert_eq!(query_prefix(&st3), "xc-new-b20260801");+ }++ // ── staleness (fail-before: stub returns Ok(None), these fail) ─────────++ fn aged(root: &Path, corpus: &str, days_ago: i64) -> CorpusState {+ let stamp = (Utc::now() - chrono::Duration::days(days_ago))+ .format(STAMP_FORMAT)+ .to_string();+ write(+ root,+ corpus,+ &format!(r#"{{"corpus":"{corpus}","indexed_at":"{stamp}","prefix":"xc-{corpus}"}}"#),+ );+ load_state(root, corpus).unwrap()+ }++ #[test]+ fn an_index_older_than_30_days_is_refused_with_the_reindex_command() {+ let root = tempfile::tempdir().unwrap();+ let st = aged(root.path(), "kv", 40);+ let err = check_fresh(&st, false, "`--stale-ok`").unwrap_err();+ assert!(+ err.contains("index for 'kv' is 40 days old"),+ "exact refusal text: {err}"+ );+ assert!(+ err.contains("xerj corpus index kv --fresh"),+ "names the fix command: {err}"+ );+ assert!(+ err.ends_with("or pass `--stale-ok`."),+ "names the caller's override: {err}"+ );+ // MCP spelling of the same refusal.+ let err = check_fresh(&st, false, "stale_ok:true").unwrap_err();+ assert!(err.ends_with("or pass stale_ok:true."), "{err}");+ }++ #[test]+ fn a_29_day_old_index_is_served_and_reports_its_age() {+ let root = tempfile::tempdir().unwrap();+ let st = aged(root.path(), "kv", 29);+ assert_eq!(check_fresh(&st, false, "--stale-ok").unwrap(), Some(29));+ }++ #[test]+ fn stale_ok_is_the_only_override_and_missing_stamps_disable_the_check() {+ let root = tempfile::tempdir().unwrap();+ let st = aged(root.path(), "kv", 31);+ assert_eq!(check_fresh(&st, true, "--stale-ok").unwrap(), Some(31));++ let mut no_stamp = st.clone();+ no_stamp.indexed_at = None;+ assert_eq!(check_fresh(&no_stamp, false, "--stale-ok").unwrap(), None);++ let mut junk = st.clone();+ junk.indexed_at = Some("not-a-date".into());+ assert_eq!(+ check_fresh(&junk, false, "--stale-ok").unwrap(),+ None,+ "an unparsable clock never refuses"+ );+ }++ // ── incomplete coverage (fail-before: stub returns None) ───────────────++ #[test]+ fn an_unfinished_or_salvaged_run_warns_on_every_query() {+ let mut st = CorpusState {+ corpus: Some("kv".into()),+ autoindex_exit: Some(json!(1)),+ ..Default::default()+ };+ let w = incomplete_coverage(&st).unwrap();+ assert!(+ w.starts_with(+ "WARNING: the index for 'kv' was NOT verified complete (autoindex exit 1)"+ ),+ "{w}"+ );+ assert!(+ w.contains("Re-run `xerj corpus index kv` to resume or confirm it."),+ "{w}"+ );++ st.autoindex_exit = Some(json!(0));+ st.salvaged = Some(true);+ let w = incomplete_coverage(&st).unwrap();+ assert!(+ w.contains("(autoindex exit 0, kept unverified)"),+ "salvaged rides the same warning: {w}"+ );++ st.salvaged = Some(false);+ for clean in [None, Some(json!(0)), Some(json!(3)), Some(json!(true))] {+ st.autoindex_exit = clean.clone();+ assert!(+ incomplete_coverage(&st).is_none(),+ "exit {clean:?} is finished and must not warn"+ );+ }+ }++ // ── not-loaded-here (fail-before: stub returns empty text) ─────────────++ #[test]+ fn zero_live_indices_gets_the_distinct_not_loaded_diagnosis() {+ let st = CorpusState {+ corpus: Some("kv".into()),+ indexed_at: Some("2026-08-01T00:00:00Z".into()),+ prefix: Some("xc-kv".into()),+ url: Some("http://other-host:9200".into()),+ ..Default::default()+ };+ let msg = not_loaded_message(&st, "xc-kv-b1", "http://localhost:9200");+ assert!(+ msg.contains(+ "corpus 'kv' is in state/ (indexed 2026-08-01T00:00:00Z) but has 0 live \+ indices ('xc-kv-b1*') on http://localhost:9200."+ ),+ "{msg}"+ );+ assert!(+ msg.contains("It was indexed against http://other-host:9200."),+ "names the recorded url when it differs: {msg}"+ );+ assert!(+ msg.contains("Re-run: xerj corpus index kv, or set XERJ_URL to the node that has it."),+ "{msg}"+ );+ assert!(+ msg.contains(+ "(This is NOT a 'no match' — the corpus simply is not loaded on this server.)"+ ),+ "{msg}"+ );++ let same = CorpusState {+ url: Some("http://localhost:9200".into()),+ ..st.clone()+ };+ assert!(+ not_loaded_message(&same, "xc-kv", "http://localhost:9200")+ .contains("It was indexed against a different data dir or server."),+ "same-url variant names the data dir"+ );+ }++ #[test]+ fn write_state_is_atomic_and_schema_identical() {+ let root = tempfile::tempdir().unwrap();+ write_state(+ root.path(),+ "kv",+ "http://localhost:9200",+ 0,+ false,+ Some("b20260921"),+ Some("xc-kv-b20260921"),+ Some("/tmp/autoindex-state/kv/b20260921"),+ )+ .unwrap();+ let raw = std::fs::read_to_string(state_file(root.path(), "kv")).unwrap();+ assert!(+ raw.starts_with("{\"corpus\":\"kv\",\"indexed_at\":\""),+ "key order frozen: {raw}"+ );+ assert!(+ raw.contains("\"prefix\":\"xc-kv\"")+ && raw.contains("\"autoindex_exit\":0")+ && raw.contains("\"salvaged\":false")+ && raw.contains("\"build\":\"b20260921\"")+ && raw.contains("\"index_prefix\":\"xc-kv-b20260921\"")+ && raw.contains("\"state_dir\":\"/tmp/autoindex-state/kv/b20260921\""),+ "{raw}"+ );+ assert!(+ raw.ends_with("}\n"),+ "trailing newline like the script: {raw:?}"+ );+ // No tmp file left behind.+ assert!(!root.path().join("state/.kv.json.tmp").exists());+ // Round-trips through the tolerant reader.+ let st = load_state(root.path(), "kv").unwrap();+ assert_eq!(st.index_prefix.as_deref(), Some("xc-kv-b20260921"));+ }+}diff --git a/engine/crates/xerj-mcp/Cargo.toml b/engine/crates/xerj-mcp/Cargo.tomlindex 4da38292a..3bbc980ee 100644--- a/engine/crates/xerj-mcp/Cargo.toml+++ b/engine/crates/xerj-mcp/Cargo.toml@@ -4,7 +4,7 @@ version.workspace = trueedition.workspace = truelicense.workspace = trueauthors.workspace = true-description = "Model Context Protocol (MCP) stdio server exposing the 10 canonical XERJ agent operations (search, memory, second-brain graph) as thin proxies to an ES-compatible XERJ endpoint"+description = "Model Context Protocol (MCP) stdio server exposing the 11 canonical XERJ agent operations (search, memory, second-brain graph, reference-code) as thin proxies to an ES-compatible XERJ endpoint"# Library first: the `xerj mcp` subcommand on the main binary calls# `xerj_mcp::run`, so a user with the installed `xerj` binary already has thediff --git a/engine/crates/xerj-mcp/src/lib.rs b/engine/crates/xerj-mcp/src/lib.rsindex 88eb881ad..5cf81ef30 100644--- a/engine/crates/xerj-mcp/src/lib.rs+++ b/engine/crates/xerj-mcp/src/lib.rs@@ -9,12 +9,12 @@//!//! It speaks the MCP **stdio transport**: newline-delimited//! JSON-RPC 2.0 messages on stdin/stdout. It exposes XERJ to any MCP-capable-//! agent host (Claude Desktop, IDE agents, custom orchestrators) as ten+//! agent host (Claude Desktop, IDE agents, custom orchestrators) as eleven//! tools that map 1:1 onto XERJ's real, verified REST surface. Every tool is//! a *thin proxy*: it constructs exactly the request the running engine//! already accepts and forwards it to a configurable base URL.//!-//! ## The ten canonical agent operations+//! ## The eleven canonical agent operations//!//! | MCP tool | XERJ endpoint | Real capability |//! |------------------------|---------------------------------------|-----------------|@@ -102,9 +102,10 @@ USAGE:xerj mcp [OPTIONS] (or the standalone binary: xerj-mcp [OPTIONS])Speaks MCP over stdio (newline-delimited JSON-RPC 2.0 on stdin/stdout) and-proxies ten tools — xerj_search, xerj_semantic_search, xerj_vector_search,+proxies eleven tools — xerj_search, xerj_semantic_search, xerj_vector_search,xerj_hybrid_search, xerj_memory_store, xerj_memory_recall, xerj_brain_ego,-xerj_brain_link, xerj_brain_unlink, xerj_brain_overview — to a XERJ node that+xerj_brain_link, xerj_brain_unlink, xerj_brain_overview, xerj_code_search — to a+XERJ node thatis ALREADY RUNNING. This command does not start a node; start one first with`xerj --data-dir ./data`.@@ -826,6 +827,32 @@ pub fn tool_specs() -> Value {},"required": ["brain"]}+ },+ {+ "name": "xerj_code_search",+ "description": concat!(+ "Reference-coding retrieval over a corpus of peer projects: how did ",+ "real codebases solve this problem? Returns the matching definition ",+ "(not a byte window), the file:line to cite, and per-hit licence ",+ "warnings — AGPL/SSPL/Elastic/BUSL/GPL/LGPL/MPL sources are approach-only. ",+ "Refuses indices older than 30 days (override with stale_ok). ",+ "A no-match is NOT an error: it says the corpus is wrong for the task. ",+ "Corpora: `xerj corpus list`."),+ "inputSchema": {+ "type": "object",+ "properties": {+ "corpus": { "type": "string", "description": "Corpus name (`xerj corpus list`)." },+ "query": { "type": "string", "description": "What you need, in code terms (e.g. 'merge policy segment expiry')." },+ "k": { "type": "integer", "description": "Passages to return; clamped to 1..=50 (default 5)." },+ "mode": { "type": "string", "enum": ["bm25", "semantic", "hybrid"], "description": "Retrieval arm (default bm25 — measured best)." },+ "lang": { "type": "string", "description": "Filter to one language field (e.g. rust, go)." },+ "full": { "type": "integer", "description": "Max chars per passage (default 800; 0 = file head only)." },+ "no_symbol": { "type": "boolean", "description": "Window selection instead of the matching definition." },+ "stale_ok": { "type": "boolean", "description": "Override the 30-day staleness refusal." },+ "licence_policy": { "type": "string", "enum": ["warn", "strict"], "description": "strict strips passage text from restricted-licence hits, keeping locator + warning (default warn)." }+ },+ "required": ["corpus", "query"]+ }}])}@@ -858,6 +885,7 @@ async fn call_tool(ctx: &Ctx, msg: &Value) -> Value {"xerj_brain_link" => build_brain_link(&args),"xerj_brain_unlink" => build_brain_unlink(&args),"xerj_brain_overview" => build_brain_overview(&args),+ "xerj_code_search" => return run_code_search(ctx, &args).await,other => return tool_text(format!("unknown tool: {other}"), true),};@@ -1320,6 +1348,173 @@ fn build_brain_overview(args: &Value) -> Result<BuiltRequest, String> {))}+// ── xerj_code_search: the shared reference-coding pipeline ──────────────────++/// Synchronous [`XcHttp`] over a fresh reqwest client. This crate is+/// deliberately async-only (no `blocking` feature), so each call runs on a+/// private current-thread runtime inside the `spawn_blocking` below — no+/// query logic lives here, only transport.+struct McpXc {+ base_url: String,+ auth: Option<String>,+}++impl McpXc {+ fn request(&self, method: &str, path: &str, body: Option<&Value>) -> Result<Value, String> {+ let rt = tokio::runtime::Builder::new_current_thread()+ .enable_all()+ .build()+ .map_err(|e| format!("runtime: {e}"))?;+ let url = format!("{}{}", self.base_url, path);+ let auth = self.auth.clone();+ let method = method.to_string();+ let body = body.cloned();+ rt.block_on(async move {+ let client = reqwest::Client::new();+ let m = reqwest::Method::from_bytes(method.as_bytes())+ .map_err(|_| format!("not an HTTP method: {method}"))?;+ let mut req = client.request(m, &url);+ if let Some(h) = auth.as_deref() {+ req = req.header("Authorization", h);+ }+ if let Some(b) = &body {+ req = req.json(b);+ }+ let resp = req+ .send()+ .await+ .map_err(|e| format!("no response from {url}: {e}"))?;+ // Surface the status WITH the body: the tri-state callers (404 =+ // zero, not error) classify it themselves.+ let status = resp.status().as_u16();+ let text = resp.text().await.map_err(|e| format!("read {url}: {e}"))?;+ let v: Value = serde_json::from_str(&text).unwrap_or(Value::String(text));+ match status {+ 200..=299 => Ok(v),+ 404 => Err("__404__".to_string()),+ other => Err(format!("HTTP {other}: {v}")),+ }+ })+ }+}++impl xerj_common::xccode::XcHttp for McpXc {+ fn get_mapping(&self, path: &str) -> Result<Value, String> {+ self.request("GET", path, None)+ }+ fn cat_indices_json(&self, pattern: &str) -> Result<Vec<String>, String> {+ let v = match self.request(+ "GET",+ &format!("/_cat/indices/{pattern}?format=json&h=index"),+ None,+ ) {+ Ok(v) => v,+ // A 404 on a wildcard means "no such indices" -> none, not an error.+ Err(e) if e.contains("__404__") => return Ok(Vec::new()),+ Err(e) => return Err(e),+ };+ v.as_array()+ .map(|rows| {+ rows.iter()+ .filter_map(|r| r.get("index").and_then(Value::as_str))+ .map(str::to_string)+ .collect()+ })+ .ok_or_else(|| "non-array _cat reply".to_string())+ }+ fn search(&self, index: &str, body: &Value) -> Result<Value, String> {+ self.request("POST", &format!("/{index}/_search"), Some(body))+ }+}++/// `xerj_code_search` — the SAME pipeline `xerj code` runs, from the SAME+/// renderer; only the surface differs. Warnings ride the TOP of the tool text+/// (MCP has no stderr channel, so warnings are content), and the exit-code+/// triangle maps onto `isError`: staleness/not-loaded/transport are errors, a+/// no-match is NOT.+async fn run_code_search(ctx: &Ctx, args: &Value) -> Value {+ let corpus = match args.get("corpus").and_then(Value::as_str) {+ Some(c) if !c.is_empty() => c.to_string(),+ _ => return tool_text("xerj_code_search: `corpus` is required", true),+ };+ let query = match args.get("query").and_then(Value::as_str) {+ Some(q) if !q.is_empty() => q.to_string(),+ _ => return tool_text("xerj_code_search: `query` is required", true),+ };+ let mut p = xerj_common::xccode::CodeParams::new(&corpus, &query);+ if let Some(k) = args.get("k") {+ match k.as_u64().filter(|n| (1..=50).contains(n)) {+ Some(n) => p.k = n as usize,+ None => return tool_text("xerj_code_search: `k` must be an integer 1..=50", true),+ }+ }+ if let Some(m) = args.get("mode").and_then(Value::as_str) {+ match xerj_common::xccode::Mode::parse(m) {+ Some(mode) => p.mode = mode,+ None => return tool_text(format!("xerj_code_search: unknown mode '{m}'"), true),+ }+ }+ if let Some(l) = args.get("lang").and_then(Value::as_str) {+ p.lang = Some(l.to_string());+ }+ match args.get("full").and_then(Value::as_u64) {+ Some(n) => p.full = n as usize,+ None => {+ if args.get("full").is_some() {+ return tool_text(+ "xerj_code_search: `full` must be a non-negative integer",+ true,+ );+ }+ }+ }+ p.no_symbol = args+ .get("no_symbol")+ .and_then(Value::as_bool)+ .unwrap_or(false);+ p.stale_ok = args+ .get("stale_ok")+ .and_then(Value::as_bool)+ .unwrap_or(false);+ p.strict_licence = matches!(+ args.get("licence_policy").and_then(Value::as_str),+ Some("strict")+ );++ let base_url = ctx.base_url.clone();+ let auth = ctx.auth.clone();+ let res = tokio::task::spawn_blocking(move || {+ let http = McpXc { base_url, auth };+ let root = code_root();+ xerj_common::xccode::run_code_query(&root, &http, &http.base_url, &p, "stale_ok:true")+ })+ .await;++ let out = match res {+ Ok(out) => out,+ Err(e) => return tool_text(format!("xerj_code_search: join error: {e}"), true),+ };+ let mut text = String::new();+ for w in &out.warnings {+ text.push_str(w);+ text.push('\n');+ }+ text.push_str(&out.text);+ tool_text(text, out.is_error)+}++/// `~/.xerj-code` unless `XERJ_CODE_HOME` says otherwise — the SAME root the+/// CLI uses, so both surfaces see the same corpora.+fn code_root() -> std::path::PathBuf {+ if let Ok(home) = std::env::var("XERJ_CODE_HOME") {+ if !home.is_empty() {+ return std::path::PathBuf::from(home);+ }+ }+ let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());+ std::path::Path::new(&home).join(".xerj-code")+}+// ── Engine transport ─────────────────────────────────────────────────────────/// Send one request to the configured XERJ base URL and wrap the response as@@ -1810,7 +2005,7 @@ mod tests {}#[test]- fn tools_list_has_all_ten() {+ fn tools_list_has_all_eleven() {let specs = tool_specs();let names: Vec<&str> = specs.as_array()@@ -1818,7 +2013,7 @@ mod tests {.iter().map(|t| t["name"].as_str().unwrap()).collect();- assert_eq!(names.len(), 10);+ assert_eq!(names.len(), 11);for n in ["xerj_search","xerj_semantic_search",@@ -1830,6 +2025,9 @@ mod tests {"xerj_brain_link","xerj_brain_unlink","xerj_brain_overview",+ // #977: reference-coding retrieval, served by the same pipeline+ // as `xerj code` (LAST in the list, by design).+ "xerj_code_search",] {assert!(names.contains(&n), "missing tool {n}");}diff --git a/engine/crates/xerj-server/src/main.rs b/engine/crates/xerj-server/src/main.rsindex 887a7c2b6..bdaddab27 100644--- a/engine/crates/xerj-server/src/main.rs+++ b/engine/crates/xerj-server/src/main.rs@@ -205,6 +205,10 @@ fn help_text(feedback: bool) -> String {flagship path for most agents (see xerj\n\autoindex --help)\n\xerj autoindex map print the discovered data map\n\+ xerj code <corpus> \"<query>\" reference-coding retrieval over a corpus\n\+ of peer projects (see xerj code --help)\n\+ xerj corpus add|index|list the corpus lifecycle behind `xerj code`\n\+ (see xerj corpus --help)\n\xerj index [OPTIONS] direct NDJSON → engine ingest (see xerj\n\index --help)\n\xerj brain <folder> index + browse in one command (see xerj\n\@@ -281,16 +285,20 @@ fn help_text(feedback: bool) -> String {query client, no wrapper scripts (see xerj search --help)\n\xerj def \"<symbol>\" go-to-definition: where is this symbol defined, and\n\what is its signature (see xerj def --help)\n\+ xerj code <corpus> \"<q>\" reference-coding retrieval: how did peer projects\n\+ solve this (see xerj code --help)\n\+ xerj corpus add|index|list clone + index + list the reference corpora that\n\+ `xerj code` searches (see xerj corpus --help)\n\xerj init wire XERJ into the coding agents in this project:\n\MCP + skill files, one command (see xerj init --help)\n\xerj gain what this node did for you, counted from the audit\n\log — searches, hit rate, latency (xerj gain --help)\n\xerj brain <folder> one command: index a folder into a running, browsable\n\second brain in your browser (see xerj brain --help)\n\- xerj mcp [opts] Model Context Protocol stdio server: exposes 10 tools\n\- (search, semantic, vector, hybrid, memory, second-brain)\n\- to any MCP client. Proxies to a node you already started\n\- — set XERJ_URL or --url (see xerj mcp --help)\n\+ xerj mcp [opts] Model Context Protocol stdio server: exposes 11 tools\n\+ (search, semantic, vector, hybrid, memory, second-brain,\n\+ code-search) to any MCP client. Proxies to a node you\n\+ already started — set XERJ_URL or --url (see xerj mcp --help)\n\xerj feedback [opts] draft the agent field report XERJ asks every agent to\n\file, auto-filling version/OS/what-was-indexed; --open-pr\n\files it, --dry-run just prints (see xerj feedback --help)\n\@@ -2005,6 +2013,26 @@ async fn async_main() -> Result<()> {.unwrap_or(1);std::process::exit(code);}+ if matches!(argv1.as_deref(), Some("code")) {+ // Reference-coding retrieval (issue #977, previously xc.py): blocking+ // ES-compat client + local state ledger, synchronous — off the+ // runtime like `def`.+ let args: Vec<String> = std::env::args().skip(2).collect();+ let code = tokio::task::spawn_blocking(move || xerj_autoindex::xc::run_code_cli(&args))+ .await+ .unwrap_or(1);+ std::process::exit(code);+ }+ if matches!(argv1.as_deref(), Some("corpus")) {+ // Reference-coding corpus lifecycle (issue #977, previously+ // xc-corpus.sh/xc-index.sh): git + autoindex + ES-compat client, all+ // synchronous — off the runtime like `autoindex`.+ let args: Vec<String> = std::env::args().skip(2).collect();+ let code = tokio::task::spawn_blocking(move || xerj_autoindex::xc::run_corpus_cli(&args))+ .await+ .unwrap_or(1);+ std::process::exit(code);+ }// Start profiling before config loading, TLS, engine replay, and router// construction so delay=0 is a genuine initialization profile.diff --git a/landing/docs/agents/schemas/mcp-tools.json b/landing/docs/agents/schemas/mcp-tools.jsonindex 841234fc6..016cdf6de 100644--- a/landing/docs/agents/schemas/mcp-tools.json+++ b/landing/docs/agents/schemas/mcp-tools.json@@ -469,6 +469,64 @@"brain"]}+ },+ {+ "name": "xerj_code_search",+ "description": "Reference-coding retrieval over a corpus of peer projects: how did real codebases solve this problem? Returns the matching definition (not a byte window), the file:line to cite, and per-hit licence warnings — AGPL/SSPL/Elastic/BUSL/GPL/LGPL/MPL sources are approach-only. Refuses indices older than 30 days (override with stale_ok). A no-match is NOT an error: it says the corpus is wrong for the task. Corpora: `xerj corpus list`.",+ "inputSchema": {+ "type": "object",+ "properties": {+ "corpus": {+ "type": "string",+ "description": "Corpus name (`xerj corpus list`)."+ },+ "query": {+ "type": "string",+ "description": "What you need, in code terms (e.g. 'merge policy segment expiry')."+ },+ "k": {+ "type": "integer",+ "description": "Passages to return; clamped to 1..=50 (default 5)."+ },+ "mode": {+ "type": "string",+ "enum": [+ "bm25",+ "semantic",+ "hybrid"+ ],+ "description": "Retrieval arm (default bm25 — measured best)."+ },+ "lang": {+ "type": "string",+ "description": "Filter to one language field (e.g. rust, go)."+ },+ "full": {+ "type": "integer",+ "description": "Max chars per passage (default 800; 0 = file head only)."+ },+ "no_symbol": {+ "type": "boolean",+ "description": "Window selection instead of the matching definition."+ },+ "stale_ok": {+ "type": "boolean",+ "description": "Override the 30-day staleness refusal."+ },+ "licence_policy": {+ "type": "string",+ "enum": [+ "warn",+ "strict"+ ],+ "description": "strict strips passage text from restricted-licence hits, keeping locator + warning (default warn)."+ }+ },+ "required": [+ "corpus",+ "query"+ ]+ }}]}diff --git a/tools/xerj-code/README.md b/tools/xerj-code/README.mdindex b86792b3f..453056fd4 100644--- a/tools/xerj-code/README.md+++ b/tools/xerj-code/README.md@@ -5,32 +5,36 @@ lap costs **output** tokens, the expensive kind. This toolkit replaces laps witha lookup: clone the repositories that already contain a correct implementation,index them with XERJ, and retrieve the passage before writing.-These are the three commands the case study and the website print. Until now-they lived only in a working copy and were not shipped, so nobody outside the-project could run them ([#319](https://github.com/xerj-org/xerj/issues/319)).+Since [#977](https://github.com/xerj-org/xerj/issues/977) the whole loop ships+**inside the `xerj` binary** as the `xerj corpus` and `xerj code` subcommands —+no scripts, no `python3`. (Before that they were wrapper scripts in this+directory; before [#319](https://github.com/xerj-org/xerj/issues/319) they were+not shipped at all.)```sh-scripts/xc-corpus.sh xerj-storage https://github.com/spacejam/sled … # clone the peers, once-scripts/xc-index.sh xerj-storage # xerj autoindex; re-run to update in place-scripts/xc-index.sh xerj-storage --fresh # rebuild beside the old index, verify, then swap-scripts/xc.py xerj-storage "how does sled fsync its WAL segment on rotation?"+xerj corpus add xerj-storage https://github.com/spacejam/sled … # clone the peers, once+xerj corpus index xerj-storage # xerj autoindex; re-run to update in place+xerj corpus index xerj-storage --fresh # rebuild beside the old index, verify, then swap+xerj code xerj-storage "how does sled fsync its WAL segment on rotation?"```Or rebuild a corpus someone else already defined and vetted:```sh-scripts/xc-corpus.sh --from hub/xerj-storage.json && scripts/xc-index.sh xerj-storage+xerj corpus add --from hub/xerj-storage.json && xerj corpus index xerj-storage```## What you need- The `xerj` binary — a release build, or `curl -fsSL https://xerj.org/get | sh`.- `xc-index.sh` finds it via `XERJ_BIN`, defaulting to `xerj` on `PATH`.-- A running XERJ instance (`XERJ_URL`, default `http://localhost:9200`):- `xerj --data-dir ~/.xerj-code/data --insecure`.-- `git`, `python3`, `curl`.+- A running XERJ instance (`--url` or `$XERJ_URL`, default+ `http://localhost:9200`): `xerj --data-dir ~/.xerj-code/data --insecure`.+- `git` (for `xerj corpus add`).-Clones land in `~/.xerj-code/corpora/`, overridable with `XERJ_CODE_HOME`.+Everything lives under `~/.xerj-code/` — `corpora/` (clones + `corpus.json`),+`state/` (the ledger), `autoindex-state/` (per-build journals), `data/` (the+server dir) — overridable with `XERJ_CODE_HOME`. All of it **persists**: never+put it under `/tmp`, or the corpora silently retrieve nothing after a reboot.## Sharing a corpus: definitions, not indexes@@ -45,7 +49,7 @@ corpus anywhere:]}```-`xc-corpus.sh` writes one after every build, and `--from` reads one back.+`xerj corpus add` writes one after every build, and `--from` reads one back.The SHA is the full 40 characters because that is what a remote will serve:`git fetch --depth 1 origin e449d17` fails with *couldn't find remote ref*,while the same fetch with the full SHA succeeds — so a pinned rebuild is one@@ -55,15 +59,17 @@ before this change) is rejected rather than silently rebuilt at the tip.`--from` is exact: an existing clone is **moved** to the recorded SHA, and localedits or untracked files inside it are discarded. Same manifest in, same bytesout — which is what makes a shared prompt or a shared measurement comparable-across two machines.+across two machines. A `review` block in the input manifest (see+[`hub/README.md`](hub/README.md)) is preserved for every repo that lands at its+recorded SHA.Pre-built *indexes* are a different question (on-disk format version, embedderidentity, redistribution of the indexed source) and are not offered here.## Licences are recorded, and reviewed-`xc-corpus.sh` classifies each repo from the licence file it actually ships, and-warns when the result is copyleft or source-available. The detection is+`xerj corpus add` classifies each repo from the licence file it actually ships,+and warns when the result is copyleft or source-available. The detection istext-matching heuristics and **has been wrong**, in both directions:- Elasticsearch's triple licence (AGPL-3.0 / SSPL-1.0 / Elastic-2.0) was@@ -75,7 +81,8 @@ text-matching heuristics and **has been wrong**, in both directions:So the manifests in [`hub/`](hub/) carry a `review` block a human filled in —SPDX expression, and whether the repo is safe to adapt from or approach-only.-See [`hub/README.md`](hub/README.md).+See [`hub/README.md`](hub/README.md). `xerj corpus list` surfaces each corpus's+`review.use` values.**Retrieved code is evidence, not authority.** It shows how *that* projectsolved it under *its* constraints. Cite `file:line`, and say plainly when you@@ -91,21 +98,29 @@ carry the measured numbers, including the cases where this loses.## Passage windows-When no matching symbol is available, or with `--no-symbol`, `xc.py` selects a-window of source around query terms, capped at 800 characters by default.-It aligns the window to whole lines only when doing so preserves+When no matching symbol is available, or with `--no-symbol`, `xerj code`+selects a window of source around query terms, capped at 800 characters by+default. It aligns the window to whole lines only when doing so preservesthe selected window's term score; a partial line is preferable to dropping thematch. Window offsets refer to the original source, including when Unicodelowercasing changes its length. `--full N` changes the character limit, and`--full 0` keeps the explicit file-head mode.-## Hybrid retrieval fallback--With `--mode hybrid`, the optional vector arm falls back to the already-retrieved BM25 passages if its mapping lookup or search has a transport error:-connection failures, read timeouts, and interrupted HTTP responses. Prose and-MEATL output label the fallback as `BM25 only`; `--json` keeps its existing hits-format. A failed primary BM25 search still exits with an error. In standalone+## Hybrid retrieval, fused server-side++With `--mode hybrid`, `xerj code` sends **one native top-level `hybrid` query**+(`{"fusion":{"method":"rrf","k":60}}`) — the same fusion the engine serves over+the wire, no client-side rank merging. Before it fires, a BM25 size-1 preflight+decides honesty: no lexical match is reported as a miss (exit 1), because with+the lexical embedder vector nearest-neighbours are not evidence of a match.+The mapping is read first and the vector arm is aimed only at indices whose+`body` is `semantic_text` — a semantic leg against plain-text indices 400s the+whole request — and the fused query targets that capable set when it is smaller+than the corpus. Every hybrid run opens with an arms-ran note naming what+actually ran and which lexical-only indices were excluded; per-hit per-arm+ranks are gone (the server-side fuser does not expose them). If no capable+mapping exists, or the fused request fails, the answer is plain BM25 labelled+`BM25 only — …`, never a silently-BM25 "hybrid". In standalone`--mode semantic`, mapping and search HTTP/transport failures exit `2`, ratherthan reporting no match; there are no BM25 results to fall back to.@@ -114,14 +129,28 @@ than reporting no match; there are no BM25 results to fall back to.Pass `--json` to return the search result as JSON, including when no passagesmatch. Check both stdout and the exit status: matching results exit `0`, whilean empty `hits.hits` array exits `1`. A corpus with no live indices still exits-`3` with a diagnostic on stderr; it is not an empty search result.+`3` with a diagnostic on stderr; it is not an empty search result. Exit `2` is+usage, an unreachable node, or the 30-day staleness refusal.++`--meatl` prints one line per hit instead of prose:+`@ok f=<file>:<line> score=<12.34>[ why=<licence>]` (hybrid scores render as+`rrf=<0.1234>`), `@no q="<query>" why=no-match-in-corpus` for a miss, and+`@mode <arms-ran note>` for the hybrid/semantic note line.++Agents without a shell get the same pipeline as the eleventh MCP tool,+`xerj_code_search` (`xerj mcp`) — byte-identical text, with refusals mapped to+`isError: true`, a no-match mapped to `isError: false`, and an optional+`licence_policy: "strict"` that strips passage text from restricted-licence+hits.## Tests+The contracts live where the code lives, gated by scoped cargo tests (run from+`engine/`, with `--profile ci-test`):+```sh-tools/xerj-code/tests/test_xc_corpus.sh # offline; local git fixtures over file://-tools/xerj-code/tests/test_xc_index_fresh.py # offline; fake node + fake xerj: the --fresh build-verify-swap contract (#930)-python3 tools/xerj-code/tests/test_state_ledger.py # offline; xc.py's "in state/ but not loaded here" guard, and its --json/mocked-HTTP cases-python3 tools/xerj-code/tests/test_passage_window.py # offline passage extraction regressions-python3 tools/xerj-code/tests/test_hybrid_fallback.py # offline; simulated HTTP failures+cargo test --profile ci-test -p xerj-common xccode # staleness, licences, exit triangle, hybrid shape, passages, ledger+cargo test --profile ci-test -p xerj-autoindex xc_ # corpus lifecycle, path gate, usage+cargo test --profile ci-test -p xerj-mcp # tool schema presence + isError mapping+cargo test --profile ci-test -p xerj-common xccode::manifest # hub manifests pass the untrusted-input gate```diff --git a/tools/xerj-code/SKILL.md b/tools/xerj-code/SKILL.mdindex e943e10ab..d72f6daf4 100644--- a/tools/xerj-code/SKILL.md+++ b/tools/xerj-code/SKILL.md@@ -1,6 +1,6 @@---name: xerj-code-description: Reference-coding with XERJ. Clone the libraries that already solved your problem, index them locally, and retrieve the exact implementation before writing code — so the agent reads passages instead of re-deriving algorithms across retry loops. Use when starting a task in an unfamiliar API, porting an algorithm, or when an agent has already looped twice on the same error.+description: Reference-coding with XERJ. Clone the libraries that already solved your problem, index them locally, and retrieve the exact implementation before writing code — so the agent reads passages instead of re-deriving algorithms across retry loops. Use when starting a task in an unfamiliar API, porting an algorithm, or when you have already looped twice on the same error.---# XERJ.code — reference coding@@ -39,12 +39,19 @@ the arithmetic and for the conditions under which this trade **loses**.> saves. The native-vs-xerj gap grows with corpus size (grep pulls the whole tree> into context; retrieval pulls one passage).+Since [#977](https://github.com/xerj-org/xerj/issues/977) the whole loop is+**inside the `xerj` binary** — `xerj corpus add` / `xerj corpus index` /+`xerj code` — plus the `xerj_code_search` MCP tool for agents without a shell.+The old wrapper scripts (`xc-corpus.sh`, `xc-index.sh`, `xc.py`) are gone; your+existing `~/.xerj-code` corpora and indexes work unchanged (see+[Migration](#migration-from-the-wrapper-scripts-977) below).+## Standing corpora for this repository (MANDATORY since 2026-08-06)In the xerj repo, retrieval-before-writing is **required** for non-trivialengine work, not optional. Each corpus below has a pinned, licence-reviewed-definition in [`hub/`](hub/) — `xc-corpus.sh --from hub/<name>.json` rebuilds it-at the same commits anyone else is using:+definition in [`hub/`](hub/) — `xerj corpus add --from hub/<name>.json` rebuilds+it at the same commits anyone else is using:| corpus | projects | use it for ||---|---|---|@@ -64,49 +71,50 @@ bucket a repo is in; `hub/README.md` explains the three.### Operational traps, both hit in practice- **Nothing under `/tmp`.** Clones live in `~/.xerj-code/corpora/`, the index in- `~/.xerj-code/data`. A `/tmp` data dir is lost on reboot and the whole corpus- silently retrieves nothing.-- **`xc-index.sh <corpus> --fresh` is the rebuild, and it never costs you a- working index.** It builds a replacement *beside* the existing one — under+ `~/.xerj-code/data` (override the root with `XERJ_CODE_HOME`). A `/tmp` data+ dir is lost on reboot and the whole corpus silently retrieves nothing.+- **`xerj corpus index <corpus> --fresh` is the rebuild, and it never costs you+ a working index.** It builds a replacement *beside* the existing one — under`xc-<corpus>-b<stamp>-*`, with an autoindex `--state-dir` of its own in`~/.xerj-code/autoindex-state/<corpus>/` — verifies it (autoindex exited `0`or `3` **and** `_count > 0`), switches `state/<corpus>.json` to it by atomicrename, and only then deletes the old indices, by exact name. A build thatfails or comes back empty is removed and the old index, the old state fileand the old state directory stay exactly as they were. Use it after the data- dir was wiped or moved, when `xc.py` says the index is older than 30 days, or- when a plain re-run says the state directory "cannot become generation- authority". It is **not** `xerj autoindex --fresh`, which the script never- forwards: that flag only discards autoindex's resume journal and is refused- outright once a corpus generation has committed — which is why `--fresh` used- to fail on every corpus that had been indexed before+ dir was wiped or moved, when `xerj code` says the index is older than 30+ days, or when a plain re-run says the state directory "cannot become+ generation authority". It is **not** `xerj autoindex --fresh`, which the+ command never forwards: that flag only discards autoindex's resume journal+ and is refused outright once a corpus generation has committed — which is why+ `--fresh` used to fail on every corpus that had been indexed before([#930](https://github.com/xerj-org/xerj/issues/930)).-- **A record count the node does not answer is never read as zero.** The- script asks up to 6 times (`XC_COUNT_TRIES`, `XC_COUNT_PAUSE`). If the node- still cannot count the existing index, it is presumed to be a working one and- no failed build is kept over it; if it cannot count the new build, nothing is- deleted and nothing is switched. Only a number — or a 404, no index matches —- authorises a delete or a swap.-- **An interrupted FIRST build is kept, and `xc.py` says so.** When a build+- **A record count the node does not answer is never read as zero.** The count+ is a tri-state: a number, a 404 (no index matches — genuinely zero), or+ *Unknown* (timeout, 5xx, unparseable reply). *Unknown* authorises no delete+ and no swap: if the node cannot count the existing index, it is presumed to+ be a working one and no failed build is kept over it; if it cannot count the+ new build, nothing is deleted and nothing is switched. Only a number — or a+ 404 — authorises a delete or a swap.+- **An interrupted FIRST build is kept, and `xerj code` says so.** When a buildfails after writing records and there is no working index to fall back to,- the script keeps it rather than leave no corpus at all, and records+ the command keeps it rather than leave no corpus at all, and records`salvaged: true` plus the real `autoindex_exit` in the state file. Such a- build can be partial, so `xc.py` warns on stderr with every query that+ build can be partial, so `xerj code` warns on stderr with every query thatcoverage is INCOMPLETE — **a miss is then not evidence that the code is- absent** — and `xc.py --list` marks the corpus. A plain `xc-index.sh <corpus>`- resumes it (same prefix, same state directory) and clears the mark when it- finishes.-- **A plain `xc-index.sh <corpus>` updates in place.** It re-runs autoindex- against the recorded build's prefix and state directory, so additions,- edits, deletions and renames reconcile incrementally.+ absent** — and `xerj corpus list` marks the corpus. A plain+ `xerj corpus index <corpus>` resumes it (same prefix, same state directory)+ and clears the mark when it finishes.+- **A plain `xerj corpus index <corpus>` updates in place.** It re-runs+ autoindex against the recorded build's prefix and state directory, so+ additions, edits, deletions and renames reconcile incrementally.- **The state file has two prefixes on purpose.** `prefix` is always`xc-<corpus>` — the whole namespace, so anything that globs `xc-<corpus>*`keeps working across rebuilds. `index_prefix` is the one verified build, and- it is what `xc.py` queries, so a half-built replacement never leaks into+ it is what `xerj code` queries, so a half-built replacement never leaks intoanswers during a rebuild.- **During a rebuild both builds exist**, so the node briefly holds the corpustwice. Budget disk for it on a large corpus.-- Always verify: `curl -s "$URL/xc-<corpus>*/_count"` must be > 0. The script+- Always verify: `curl -s "$URL/xc-<corpus>*/_count"` must be > 0. The commanddoes this itself and says so; do it again if you are scripting around it.## When this is worth it@@ -126,12 +134,17 @@ a fixed setup cost; a task you would finish in two tool calls will not repay it.## The loop```-xc-corpus.sh <name> <git-url>... # clone reference repos (once per domain)-xc-corpus.sh --from <manifest> # ...or rebuild a corpus someone else defined-xc-index.sh <name> # index them with xerj autoindex (once per corpus)-xc.py <name> "<what you need>" # retrieve before writing (every task)+xerj corpus add <name> <git-url>... # clone reference repos (once per domain)+xerj corpus add --from <manifest> # ...or rebuild a corpus someone else defined+xerj corpus index <name> # index them with xerj autoindex (once per corpus)+xerj code <name> "<what you need>" # retrieve before writing (every task)```+Status at any time: `xerj corpus list` shows every corpus in the ledger, its+index prefix, whether it is **loaded on this node** (`— loaded — N index(es)` /+`— NOT loaded here (0 indices) — stale/other-server`), and any INCOMPLETE+marks.+### 1. Build a corpusGroup repositories by *problem domain*, not by language. A corpus for "async@@ -140,7 +153,7 @@ tree-sitter. Keep corpora small and sharp — a corpus that contains everythingretrieves like a search engine with no query.```sh-scripts/xc-corpus.sh async-rust \+xerj corpus add async-rust \https://github.com/tokio-rs/tokio \https://github.com/hyperium/hyper```@@ -151,7 +164,7 @@ licences, a few hundred bytes, no source. That file *is* the shareable corpusdefinition: hand it to someone else and```sh-scripts/xc-corpus.sh --from their-corpus.json+xerj corpus add --from their-corpus.json```rebuilds the same commits on their machine (an existing clone is moved to the@@ -159,26 +172,33 @@ recorded SHA, so both trees match). Vetted definitions for the corpora thisproject uses live in [`hub/`](hub/):```sh-scripts/xc-corpus.sh --from hub/xerj-storage.json && scripts/xc-index.sh xerj-storage+xerj corpus add --from hub/xerj-storage.json && xerj corpus index xerj-storage```+Corpus names and repo names are validated before anything touches the+filesystem — a name with `/`, `*`, a leading `.`, or a reserved word is+rejected at parse time, because the pinned-clone checkout runs `git checkout+--force` inside that path.+### 2. Index it```sh-scripts/xc-index.sh async-rust+xerj corpus index async-rust```-This runs `xerj autoindex` against the local XERJ instance. **Exit code 3 means+This runs `xerj autoindex` in-process against the local XERJ instance+(`--url` / `$XERJ_URL`, default `http://localhost:9200`). **Exit code 3 means"completed with junk files" and is not a failure** — some files in any realrepository are unparseable. Treat 0 and 3 as success; anything else is real.+The node must be reachable; nothing is built offline.### 3. Retrieve before writing```sh-scripts/xc.py async-rust "graceful shutdown with a broadcast channel"+xerj code async-rust "graceful shutdown with a broadcast channel"```-`xc.py` returns the **matching definition**, not a byte window:+`xerj code` returns the **matching definition**, not a byte window:```─── valkey/src/networking.c (score 12.68, BSD)@@ -194,8 +214,24 @@ ranked `networking.c` and then returned its licence banner, because `addReplyNullives at line 1460. Read the named definition, cite it, and if the top hits areirrelevant say so and fall back to normal work rather than forcing them in.-`--full N` caps each passage at N chars. `--no-symbol` falls back to a raw window-(only useful for data files with no symbols at all).+`--full N` caps each passage at N chars (`--full 0` prints the file head and+says how to get the matching definition instead). `--no-symbol` falls back to a+raw window (only useful for data files with no symbols at all).++### Exit codes++`xerj code` distinguishes *no match* from *broken* from *not loaded* — script+around it:++| exit | meaning |+|---|---|+| `0` | hits (the passages are on stdout) |+| `1` | **no match** — including `--json` with an empty `hits.hits`; the fall-back prose tells you to fall back to normal work, not to retry |+| `2` | usage error, unreachable node, transport failure, 30-day staleness refusal, standalone-semantic failure |+| `3` | corpus is in `state/` but has **0 live indices on this node** — "This is NOT a 'no match' — the corpus simply is not loaded on this server." Re-index, or point `XERJ_URL` at the node that holds it |++This is deliberately different from sibling `xerj search`, which exits `0` on an+empty result — different tool, different contract.### Retrieval modes@@ -207,7 +243,7 @@ queries:| | top-1 | top-3| top-1 | top-3| top-1 | top-3 || **bm25** | 3/6 | 6/6 | **6/6** | 6/6 | **9/12** |**12/12**|| hybrid | **5/6** | 6/6 | 2/6 | 4/6 | 7/12 | 10/12 |-| semantic | 4/6 | 4/6 | 2/6 | 3/6 | 6/12 | 7/12 |+| semantic | 4/6 | 4/6 | 2/6 | 3/6 | 6/12 | 7/12 |top-3 is the operative metric — the agent reads *k* passages, not one — and BM25is perfect on it while never being the worst arm on either corpus. It is also@@ -221,22 +257,51 @@ broad `semantic_text` coverage *and* you specifically care about top-1 — andmeasure it before trusting it.```sh-scripts/xc.py rust-text "lazy DFA cache eviction" # bm25 (default)-scripts/xc.py rust-text "lazy DFA cache eviction" --mode hybrid # + vector, RRF-fused-scripts/xc.py rust-text "lazy DFA cache eviction" --mode semantic # vector only+xerj code rust-text "lazy DFA cache eviction" # bm25 (default)+xerj code rust-text "lazy DFA cache eviction" --mode hybrid # + vector, RRF-fused+xerj code rust-text "lazy DFA cache eviction" --mode semantic # vector only```-A hybrid answer opens with a line naming the arms that actually ran. **The vector-arm only works where `body` is mapped as `semantic_text`**, and a `semantic` query-against an index where it is not does not degrade — it fails the whole search with-a 400 and takes every other index in the wildcard with it. `xc.py` reads the-mapping first and aims the vector arm only at capable indices, so a corpus with no-`semantic_text` says `BM25 only — ...` rather than pretending.--**`xc.py` never requests `highlight`.** On this engine a highlight block changes-`_score` and reorders hits (issue #177): identical query, top-1 **6/6** without it-and **1/6** with it. Since passages now come from `symbols[]`, the highlighter-bought nothing and cost ranking.+The table above was measured with the script-era client-side fusion. Since #977+hybrid is **fused server-side**: one native top-level `hybrid` query with+`{"fusion":{"method":"rrf","k":60}}`, no client-side rank merging — so per-hit+per-arm ranks are gone (the server does not expose them) and every hybrid run+opens with an arms-ran note instead, e.g.+`[hybrid RRF(k=60) — BM25 over 9 index(es), vector over 3 of 9]`. On a corpus+where only some indices are semantic-capable, the fused query is aimed at the+capable set only and the note names the excluded lexical-only indices — a+semantic leg fired at a wildcard covering plain-text indices 400s the whole+request.++A hybrid answer opens with a line naming the arms that actually ran, and says+`BM25 only — ...` rather than pretending when the vector arm could not run (no+`semantic_text` mapping for `body`, or the fused request failed). **The vector+arm only works where `body` is mapped as `semantic_text`**, and a `semantic`+query against an index where it is not does not degrade — it fails the whole+search with a 400 and takes every other index in the wildcard with it. `xerj+code` reads the mapping first and aims the vector arm only at capable indices.+Hybrid also runs a BM25 size-1 preflight: if the lexical arm finds nothing, the+answer is an honest miss (exit 1) — with the lexical embedder, vector+nearest-neighbours are not evidence of a match.++**`xerj code` never requests `highlight`.** On this engine a highlight block+changes `_score` and reorders hits (issue #177): identical query, top-1 **6/6**+without it and **1/6** with it. Since passages now come from `symbols[]`, the+highlighter bought nothing and cost ranking.++## No shell? The MCP tool++Not every agent can run commands. The same pipeline is the eleventh MCP tool,+`xerj_code_search` (see `xerj mcp`; registration snippets per client live in the+llms docs, not here). Its text output is byte-identical to `xerj code`'s prose —+same hits, same `!!` licence warnings, same footer — with the exit triangle+mapped onto MCP's boolean: refusals (30-day staleness, corpus not in the ledger,+corpus not loaded on this server, transport failure) are `isError: true` with+the remediation in the text, while **a no-match is `isError: false`** — a miss+is guidance, not a tool failure. Warnings ride the successful text payload (MCP+has no stderr). `licence_policy: "strict"` additionally strips the passage text+from restricted-licence hits, keeping locator + licence + the approach-only+warning.## Rules that keep this honest@@ -244,15 +309,18 @@ bought nothing and cost ranking.project solved the problem under *its* constraints. Cite `file:line` when yourely on it, and say plainly when you are adapting rather than copying.-**Check the licence before copying.** `xc-corpus.sh` records each repository's-licence in `corpus.json`. Copying a GPL implementation into a permissively-licensed project is a real problem, not a technicality. Adapt the approach and-write your own code when the licences are incompatible.+**Check the licence before copying.** `xerj corpus add` records each+repository's licence in `corpus.json`, and every hit from a restricted licence+(AGPL, SSPL, Elastic, BUSL, GPL family, MPL, unknown) carries the warning line+`!! <licence>: adapt the APPROACH, do not copy the code` directly under its+passage. Copying a GPL implementation into a permissively licensed project is a+real problem, not a technicality. Adapt the approach and write your own code+when the licences are incompatible.**A stale index is worse than none.** It returns code that no longer exists and-sends the agent down a dead path with false confidence. `xc.py` refuses to+sends the agent down a dead path with false confidence. `xerj code` refuses toanswer from an index older than 30 days unless you pass `--stale-ok`; re-run-`xc-index.sh` instead.+`xerj corpus index <corpus> --fresh` instead.**Never index the working repository into a shared corpus.** Reference corporaare for other people's code. Mixing your own in makes retrieval return your own@@ -260,11 +328,22 @@ mistakes as precedent.## MEATL-For agent-to-agent and agent-to-tool exchanges, use the notation in `MEATL.md` —-a compact, checkable format that cuts output tokens on the messages no human-reads. It is explicitly **not** for user-facing text: prose to a person stays-prose. A summary compressed into arrow chains costs the reader more than it-saves the budget.+For agent-to-agent and agent-to-tool exchanges, `xerj code --meatl` emits one+machine-readable line per hit — a compact, checkable format that cuts output+tokens on the messages no human reads. It is explicitly **not** for user-facing+text: prose to a person stays prose. A summary compressed into arrow chains+costs the reader more than it saves the budget. The grammar:++```+@ok f=<file>:<line> score=<12.34>[ why=<licence>] # one per hit+@ok f=<file>:<line> rrf=<0.1234>[ why=<licence>] # native-hybrid scores+@no q="<query>" why=no-match-in-corpus # a miss (exit 1)+@mode <arms-ran note> # hybrid/semantic note line+```++`f` is the provenance locator `path:line` exactly as the prose block prints it;+`why` is the licence recorded in `corpus.json` for that hit's repo (absent when+unknown). A MEATL miss keeps exit 1 and its no-match record.## Measuring it@@ -276,12 +355,14 @@ expensive kind, `data/results-*.json` for the runs behind each figure, andThe measurement harness itself (`csrun.py`, the purpose-built referencelibraries, the hidden-test task specs) is **not** shipped in this repository —-only the retrieval tooling in this directory is. What that harness does, if you-want to build the equivalent: run three arms of the *same* agent — `bare`-(memory only), `native` (it greps the corpus tree itself), `xerj` (the retrieved-passage is injected) — over tasks whose verdict is objective, i.e. the generated-code compiles and passes a hidden test the model never sees. Report medians, not-means: one flailing trial can be 5× another.+the retrieval loop it drove now lives in the binary, and the SWE-bench-shaped+harness beside this skill (`swebench/gen_predictions.py`) drives `xerj code`+the same way. What that harness does, if you want to build the equivalent: run+three arms of the *same* agent — `bare` (memory only), `native` (it greps the+corpus tree itself), `xerj` (the retrieved passage is injected) — over tasks+whose verdict is objective, i.e. the generated code compiles and passes a+hidden test the model never sees. Report medians, not means: one flailing+trial can be 5× another.Two rules that decide whether a result means anything:@@ -294,13 +375,11 @@ Two rules that decide whether a result means anything:honest test bed is code that was never in a training set — your own privatecode is the realistic case.-## After the session: file the field report+## After the session: `xerj feedback`-Retrieval is only half the loop. The other half is telling the maintainers what-using XERJ was actually like — the baseline contribution asked of every agent-that uses it (`user-feedback/16-agent-field-reports/README.md`,-https://xerj.org/llms.txt). One command drafts it and fills in the facts-(version, OS, what was indexed) for you:+If you want to tell the maintainers what using XERJ was actually like, one+command drafts the report and fills in the facts it can observe (version, OS,+what was indexed) for you:```sh# opens the PR (branch + commit of ONLY the report + gh pr create):@@ -312,6 +391,27 @@ xerj feedback --dry-run --used-for "reference coding" --verdict "…"```It only ever auto-fills facts it can observe and leaves every opinion as a-placeholder for you to fill — never an invented verdict. A pull request that adds-only a field report is exempt from the CLA gate, so this costs a signature-nothing. `xerj feedback --help` has the full contract.+placeholder for you to fill — never an invented verdict. A pull request that+adds only a field report is exempt from the CLA gate. `xerj feedback --help`+has the full contract. This is offered, not asked: the automatic nudge that+used to print after queries is gone (2026-09-18 directive — no obligation+language, and never ask an agent for a pull request), and no marker file is+written either way.++## Migration from the wrapper scripts (#977)++The capabilities moved into the binary; nothing about your data moved:++| before (#977) | since #977 |+|---|---|+| `xc-corpus.sh <name> <git-url>...` / `xc-corpus.sh --from <m>.json` | `xerj corpus add <name> <git-url>...` / `xerj corpus add --from <m>.json` |+| `xc-index.sh <name>` / `xc-index.sh <name> --fresh` | `xerj corpus index <name>` / `xerj corpus index <name> --fresh` |+| `xc.py <name> "<query>"` | `xerj code <name> "<query>"` |+| `xc.py --list` | `xerj corpus list` |++Your existing `~/.xerj-code` corpora, state files and indexes work unchanged —+same layout (`corpora/`, `state/`, `autoindex-state/`, `data/`), same+`corpus.json` schema, same `xc-<corpus>` index namespaces, same exit-code+triangle. `python3` is no longer required; `git` still is (for `xerj corpus+add`). One deliberate change: hybrid fusion is server-side now, so per-hit+per-arm rank annotations are gone and the arms-ran note carries that duty.diff --git a/tools/xerj-code/hub/README.md b/tools/xerj-code/hub/README.mdindex a918829fa..b8cd1de2e 100644--- a/tools/xerj-code/hub/README.md+++ b/tools/xerj-code/hub/README.md@@ -4,8 +4,8 @@ Each file here defines a reference corpus by **domain**, pinned to exactcommits. Rebuild one anywhere:```sh-tools/xerj-code/scripts/xc-corpus.sh --from tools/xerj-code/hub/xerj-storage.json-tools/xerj-code/scripts/xc-index.sh xerj-storage+xerj corpus add --from tools/xerj-code/hub/xerj-storage.json+xerj corpus index xerj-storage```| corpus | projects | use it for | approx. checkout |@@ -48,13 +48,15 @@ pasting ES source would make that claim false.## Contributing a corpus-1. Build it locally: `xc-corpus.sh <name> <git-url>...`+1. Build it locally: `xerj corpus add <name> <git-url>...`2. Copy the generated `~/.xerj-code/corpora/<name>/corpus.json` to`hub/<name>.json` — the filename must match the `corpus` field.3. Open each repo's licence file yourself and fill in a `review` block perentry. Do not copy the detector's answer without looking; it has been wrongin both directions (see [`../README.md`](../README.md)).-4. Check it: `python3 tools/xerj-code/tests/validate_manifest.py --hub hub/<name>.json`+4. Check it: `cd engine && cargo test --profile ci-test -p xerj-common xccode::manifest`+ (the same untrusted-input gate `xerj corpus add --from` enforces; CI runs+ it over every file in `hub/`)5. Open a PR. Say what the corpus is *for* — a domain a reviewer can judge, nota pile of repositories.@@ -62,5 +64,5 @@ pasting ES source would make that claim false.The SHAs are deliberately frozen: a shared pin is what makes two people'sretrieval results comparable. To move a corpus forward, rebuild without `--from`-(`xc-corpus.sh <name> <url>...` in a clean `XERJ_CODE_HOME`), re-review any+(`xerj corpus add <name> <url>...` in a clean `XERJ_CODE_HOME`), re-review anylicence that changed, and open a PR with the new manifest.diff --git a/tools/xerj-code/scripts/xc-corpus.sh b/tools/xerj-code/scripts/xc-corpus.shdeleted file mode 100755index ed82fac64..000000000--- a/tools/xerj-code/scripts/xc-corpus.sh+++ /dev/null@@ -1,365 +0,0 @@-#!/usr/bin/env bash-# Clone reference repositories into a named corpus.-#-# Two ways in:-#-# xc-corpus.sh <name> <git-url>... build a new corpus from URLs, and write-# a manifest that describes it-# xc-corpus.sh --from <manifest> rebuild the corpus that manifest-# describes, at the exact commits it pins-#-# The second form is what makes a corpus shareable. `corpus.json` is a few-# hundred bytes of URLs, SHAs and licences — no source, so no redistribution-# question — and the same manifest on two machines produces the same bytes on-# disk, which is what makes a shared prompt or a shared measurement comparable.-#-# Shallow clones only — history is dead weight for retrieval, and a full clone of-# a large project can be 10x the checkout. Licence is recorded per repo because-# copying from an incompatible one is a real problem, not a formality.-set -euo pipefail--ROOT="${XERJ_CODE_HOME:-$HOME/.xerj-code}"-CORPORA="$ROOT/corpora"--usage() {- cat >&2 <<'EOF'-usage: xc-corpus.sh <corpus-name> <git-url> [git-url...]- xc-corpus.sh --from <manifest.json> [--as <corpus-name>]--Groups repositories by PROBLEM DOMAIN, not by language. A corpus that contains-everything retrieves like a search engine with no query — keep them sharp.-- xc-corpus.sh async-rust https://github.com/tokio-rs/tokio \- https://github.com/hyperium/hyper--Rebuild a corpus someone else defined, pinned to the same commits:-- xc-corpus.sh --from hub/xerj-storage.json && xc-index.sh xerj-storage----from is exact: each repo is fetched at the manifest's SHA, and an existing-clone is MOVED to that SHA (local edits and untracked files in it are-discarded). Vetted manifests live in this toolkit's hub/ directory.-EOF- exit 2-}--# find the licence without guessing: read the file the project actually ships.-# Dual-licensed crates (very common in Rust) ship LICENSE-MIT + LICENSE-APACHE-# and no plain LICENSE, so collect every candidate rather than taking the first.-detect_licence() {- local repo="$1" f found=()- for f in "$repo"/LICENSE* "$repo"/LICENCE* "$repo"/COPYING*; do- [ -f "$f" ] || continue- # LICENSE-3rdparty.csv (quickwit) is an inventory of DEPENDENCY licences,- # not this project's licence. Classifying it produced a spurious "UNKNOWN"- # arm on an otherwise plain Apache-2.0 repo.- case "$(basename "$f" | tr '[:upper:]' '[:lower:]')" in- *3rdparty*|*third-party*|*thirdparty*) continue ;;- esac- found+=("$(classify_one "$f")")- done- if [ ${#found[@]} -eq 0 ]; then echo "NONE-FOUND"; return; fi- # de-duplicate, join with "/" — "Apache-2.0/MIT" is the honest answer for a- # dual-licensed project; collapsing it to one licence would be a false record.- printf '%s\n' "${found[@]}" | sort -u | paste -sd/ --}--# Classify a single licence file by its text. Order matters: check the most-# RESTRICTIVE phrases first, and keep "bsd" last because Apache and MIT texts-# can both mention BSD in passing.-#-# The restrictive-first ordering is not stylistic. Elasticsearch's LICENSE.txt-# is a triple licence (AGPL-3.0 / SSPL-1.0 / Elastic-2.0) whose text contains-# the phrase «an "Apache License 2.0" compatible license». With Apache checked-# first, the repo was recorded as "Apache-2.0" — the most permissive possible-# reading of the most restrictive licence in the corpus, on the one repo where-# being wrong matters most. A misclassification here is a legal problem, so-# when in doubt this must over-report restriction, never under-report it.-#-# Read the TITLE first, and only then the body. A licence file names itself in-# its opening lines, while its body may cite other licences: MPL-2.0 defines-# "Secondary License" as «the GNU General Public License, Version 2.0» inside-# its own text, so a body-only scan with restrictive-first ordering read-# sonic's plain MPL-2.0 file as GPL.-#-# Two lines, not one, because titles wrap ("Apache License" / "Version 2.0,-# January 2004"). Elasticsearch's triple licence wraps mid-name across exactly-# those two lines and still resolves to AGPL, so the safe direction is-# preserved where it matters most. When the title says nothing recognisable-# (a "# License" heading, a bare copyright line) this falls back to the body-# scan, which is the previous behaviour.-classify_one() {- local title out- # `|| true`: grep exits 1 on an empty licence file, and pipefail would- # otherwise take the whole script down with it.- title="$(grep -av '^[[:space:]]*$' "$1" 2>/dev/null | head -n 2 || true)"- out="$(classify_text "$title")"- [ "$out" = "UNKNOWN" ] && out="$(classify_text "$(head -c 4000 "$1")")"- echo "$out"-}--classify_text() {- local body- body="$(printf '%s' "$1" | tr '[:upper:]' '[:lower:]' | tr '\n' ' ')"- case "$body" in- *"affero general public license"*) echo "AGPL" ;;- *"server side public license"*) echo "SSPL" ;;- *"elastic license"*) echo "Elastic" ;;- *"business source license"*) echo "BUSL" ;;- *"gnu lesser general"*) echo "LGPL" ;;- *"gnu general public license"*) echo "GPL" ;;- *"mozilla public license"*) echo "MPL-2.0" ;;- *"apache license"*) echo "Apache-2.0" ;;- *"mit license"*|*"permission is hereby granted, free of charge"*)- echo "MIT" ;;- *"redistribution and use in source and binary forms"*)- echo "BSD" ;;- *) echo "UNKNOWN" ;;- esac-}--# Copyleft and source-available licences are read-the-approach only. Warn on-# every one of them, not just GPL — the corpora deliberately include AGPL/SSPL-# (Elasticsearch) and BUSL (Meilisearch EE) sources.-warn_licence() {- case "$1" in- *AGPL*|*SSPL*|*Elastic*|*BUSL*|*GPL*|*LGPL*|*UNKNOWN*|*NONE-FOUND*)- echo " ^ $1: adapt the APPROACH, do not copy the code" >&2 ;;- esac-}--# Read a manifest into "repo<TAB>url<TAB>sha<TAB>licence" lines. python3 is-# already required by xc.py, so this adds no new dependency — and a real JSON-# parser beats a regex on a file that carries licence data.-read_manifest() {- python3 - "$1" <<'PY'-import json, re, sys-path = sys.argv[1]--# A manifest is UNTRUSTED INPUT. `--from` is documented as "rebuild a corpus-# someone else defined", so the file arrives from a hub, a chat message or a-# pull request, and every field in it is attacker-controlled. `repo` becomes a-# filesystem path (`$dest/$repo_name`) that the caller then runs `checkout-# --force` and `clean -fd` inside, so a name like "../../../work/repo" walks-# out of ~/.xerj-code and destroys uncommitted work in an unrelated checkout.-# The corpus name has been screened since the first version of this script;-# the per-repo name comes from the same untrusted file and needs the same gate.-REPO_NAME = re.compile(r"[A-Za-z0-9_][A-Za-z0-9._-]*\Z")-try:- with open(path) as fh:- m = json.load(fh)-except FileNotFoundError:- sys.exit(f"xc-corpus: no such manifest: {path}")-except json.JSONDecodeError as e:- sys.exit(f"xc-corpus: {path} is not valid JSON: {e}")--repos = m.get("repos")-if not isinstance(repos, list) or not repos:- sys.exit(f"xc-corpus: {path} has no 'repos' array")--for r in repos:- name = r.get("repo") or ""- url, sha = r.get("url") or "", r.get("sha") or ""- if not name or not url:- sys.exit(f"xc-corpus: {path}: an entry is missing 'repo' or 'url'")- if not REPO_NAME.match(name):- sys.exit(- f"xc-corpus: {path}: repo name {name!r} is not a plain directory "- "name. It is used as a path under the corpus directory and is then "- "force-checked-out and cleaned, so a name containing '/' or '..' "- "would overwrite files outside the corpus. Allowed: letters, "- "digits, '.', '_' and '-', not starting with '.' or '-'."- )- # A short sha cannot be fetched from a remote — `git fetch --depth 1 origin- # e449d17` fails with "couldn't find remote ref". Manifests written before- # full SHAs were recorded would otherwise rebuild silently at the tip,- # which is the opposite of a pin. Fail loudly instead.- if not re.fullmatch(r"[0-9a-f]{40}", sha):- sys.exit(- f"xc-corpus: {path}: repo '{name}' has sha '{sha}', which is not a "- "full 40-character sha. A short sha is not fetchable from a remote, "- "so this manifest cannot pin a rebuild. Regenerate it with "- "`xc-corpus.sh <name> <url>...` on a machine that has the corpus."- )- print(f"{name}\t{url}\t{sha}\t{r.get('licence') or 'UNKNOWN'}")--print(m.get("corpus") or "", end="", file=sys.stderr)-PY-}--# Put `target` on exactly `sha`, fetching only what that needs.-#-# Fetch-by-full-SHA at depth 1 is cheap and is what github.com serves; the-# progressively deeper fallbacks cover remotes that refuse an arbitrary-SHA-# want (uploadpack.allowAnySHA1InWant off) or a commit that is not reachable-# from the default tip.-checkout_at_sha() {- local target="$1" url="$2" sha="$3"-- if [ ! -d "$target/.git" ]; then- mkdir -p "$target"- git -C "$target" init -q- git -C "$target" remote add origin "$url"- else- git -C "$target" remote set-url origin "$url" 2>/dev/null \- || git -C "$target" remote add origin "$url"- fi-- if ! git -C "$target" cat-file -e "$sha^{commit}" 2>/dev/null; then- git -C "$target" fetch --depth 1 --quiet origin "$sha" 2>/dev/null \- || git -C "$target" fetch --quiet origin "$sha" 2>/dev/null \- || git -C "$target" fetch --quiet --tags origin 2>/dev/null \- || true- fi-- if ! git -C "$target" cat-file -e "$sha^{commit}" 2>/dev/null; then- echo " [FAIL] $(basename "$target") — remote has no commit $sha" >&2- return 1- fi-- # --force discards tracked edits; clean removes files left over from a- # different commit. "Same manifest in, same bytes out" has to mean it.- git -C "$target" checkout --quiet --force --detach "$sha"- git -C "$target" clean -qfd-}--# ----------------------------------------------------------------------------# argument parsing-# ----------------------------------------------------------------------------manifest_in=""-name=""--if [ "${1:-}" = "--from" ]; then- shift- [ $# -ge 1 ] || usage- manifest_in="$1"; shift- while [ $# -gt 0 ]; do- case "$1" in- --as) shift; [ $# -ge 1 ] || usage; name="$1"; shift ;;- *) usage ;;- esac- done-else- [ $# -ge 2 ] || usage- name="$1"; shift-fi--entries=()-# Repos that were asked for and did not land. A partial corpus is not the-# corpus the caller asked for, and the documented idiom is-# `xc-corpus.sh --from hub/<name>.json && xc-index.sh <name>` — so a rebuild-# that dropped a repository must not exit 0 and let the chain continue as if-# "same manifest in, same bytes out" had held.-skipped=()--if [ -n "$manifest_in" ]; then- # stderr of read_manifest carries the manifest's own corpus name; on failure- # it carries the error, so keep both and let the exit status decide.- meta_err="$(mktemp)"; trap 'rm -f "$meta_err"' EXIT- if ! rows="$(read_manifest "$manifest_in" 2>"$meta_err")"; then- cat "$meta_err" >&2- exit 2- fi- [ -n "$name" ] || name="$(cat "$meta_err")"- [ -n "$name" ] || { echo "xc-corpus: manifest has no 'corpus' name; pass --as <name>" >&2; exit 2; }-fi--case "$name" in- */*|.*|"") echo "xc-corpus: bad corpus name '$name'" >&2; exit 2 ;;-esac--dest="$CORPORA/$name"-mkdir -p "$dest"-manifest="$dest/corpus.json"--# ----------------------------------------------------------------------------# fetch-# ----------------------------------------------------------------------------record() {- local repo_name="$1" url="$2" target="$3" declared="${4:-}"- local lic sha bytes files- lic="$(detect_licence "$target")"- sha="$(git -C "$target" rev-parse HEAD 2>/dev/null || echo unknown)"- bytes="$(du -sb "$target" 2>/dev/null | cut -f1 || echo 0)"- files="$(find "$target" -type f -not -path '*/.git/*' 2>/dev/null | wc -l)"- echo " licence=$lic sha=${sha:0:12} files=$files"- warn_licence "$lic"- # The detector is text-matching heuristics and has been wrong before. When a- # manifest disagrees with the checkout, say so rather than overwrite quietly.- if [ -n "$declared" ] && [ "$declared" != "$lic" ]; then- echo " ! manifest says licence=$declared, checkout reads $lic — verify before copying" >&2- fi- entries+=("{\"repo\":\"$repo_name\",\"url\":\"$url\",\"licence\":\"$lic\",\"sha\":\"$sha\",\"files\":$files,\"bytes\":$bytes}")-}--if [ -n "$manifest_in" ]; then- echo "rebuilding corpus '$name' from $manifest_in"- while IFS=$'\t' read -r repo_name url sha declared; do- [ -n "$repo_name" ] || continue- # read_manifest already rejects these, loudly and with a better message.- # Repeated here because the next few lines force-checkout and `clean -fd`- # whatever path this builds: the one destructive step in the toolkit should- # not depend on a validator two functions away staying correct.- case "$repo_name" in- */*|.*|-*) echo " [FAIL] refusing unsafe repo name '$repo_name'" >&2- skipped+=("$repo_name"); continue ;;- esac- target="$dest/$repo_name"- if [ -d "$target/.git" ] && [ "$(git -C "$target" rev-parse HEAD 2>/dev/null)" = "$sha" ]; then- echo " [ok] $repo_name already at ${sha:0:12}"- else- echo " [pin] $repo_name -> ${sha:0:12}"- checkout_at_sha "$target" "$url" "$sha" || { skipped+=("$repo_name"); continue; }- fi- record "$repo_name" "$url" "$target" "$declared"- done <<< "$rows"-else- for url in "$@"; do- repo_name="$(basename "$url" .git)"- target="$dest/$repo_name"-- if [ -d "$target/.git" ]; then- echo " [skip] $repo_name already cloned"- else- echo " [clone] $repo_name"- if ! git clone --depth 1 --quiet "$url" "$target"; then- echo " [FAIL] $repo_name — could not clone; continuing" >&2- skipped+=("$repo_name")- continue- fi- fi- record "$repo_name" "$url" "$target"- done-fi--if [ ${#entries[@]} -eq 0 ]; then- echo "xc-corpus: nothing cloned" >&2- exit 1-fi--# The manifest is regenerated from what is actually on disk — never copied-# through from the input — so it always describes this checkout.-{- printf '{"corpus":"%s","cloned_at":"%s","repos":[\n' \- "$name" "$(date -u +%Y-%m-%dT%H:%M:%SZ)"- printf ' %s' "${entries[0]}"- for e in "${entries[@]:1}"; do printf ',\n %s' "$e"; done- printf '\n]}\n'-} > "$manifest"--echo-echo "corpus '$name': ${#entries[@]} repos at $dest"-echo "share it: $manifest (rebuild with xc-corpus.sh --from <that file>)"--# The manifest above is still written — it honestly describes what is on disk,-# which is what you want when diagnosing a partial run. The exit code is what-# stops `&& xc-index.sh` from indexing a corpus that is missing repositories-# and calling it the shared one.-if [ ${#skipped[@]} -gt 0 ]; then- echo >&2- echo "xc-corpus: ${#skipped[@]} of $(( ${#entries[@]} + ${#skipped[@]} )) repos did not land: ${skipped[*]}" >&2- echo "xc-corpus: this corpus is INCOMPLETE — it is not the one the manifest describes." >&2- exit 1-fi--echo "next: xc-index.sh $name"diff --git a/tools/xerj-code/scripts/xc-index.sh b/tools/xerj-code/scripts/xc-index.shdeleted file mode 100755index 96ab4404b..000000000--- a/tools/xerj-code/scripts/xc-index.sh+++ /dev/null@@ -1,437 +0,0 @@-#!/usr/bin/env bash-# Index a corpus into the local XERJ instance.-#-# xc-index.sh <corpus> index, or update in place what an earlier run built-# xc-index.sh <corpus> --fresh rebuild from scratch: build a replacement BESIDE the-# existing index, verify it, and only then retire the old one-set -euo pipefail--ROOT="${XERJ_CODE_HOME:-$HOME/.xerj-code}"-CORPORA="$ROOT/corpora"-URL="${XERJ_URL:-http://localhost:9200}"-XERJ_BIN="${XERJ_BIN:-xerj}"-# One autoindex --state-dir per build, owned by this script. See "WHAT --fresh-# MEANS" below for why the state directory is never left to autoindex's default.-STATE_ROOT="$ROOT/autoindex-state"--usage() { echo "usage: xc-index.sh <corpus-name> [--fresh]" >&2; exit 2; }--[ $# -ge 1 ] || usage-name="$1"; shift--# Reject what we do not understand rather than dropping it. The previous form-# was `[ "${1:-}" = "--fresh" ] && fresh="--fresh"`, which silently ignored a-# mistyped or extra flag: `xc-index.sh <corpus> --frsh` ran an INCREMENTAL-# index and exited 0.-fresh=false-while [ $# -gt 0 ]; do- case "$1" in- --fresh) fresh=true; shift ;;- *) echo "xc-index: unknown argument '$1'" >&2; usage ;;- esac-done--dir="$CORPORA/$name"-[ -d "$dir" ] || { echo "xc-index: no corpus '$name' — run xc-corpus.sh first" >&2; exit 2; }--command -v "$XERJ_BIN" >/dev/null 2>&1 || {- echo "xc-index: '$XERJ_BIN' not on PATH. Set XERJ_BIN to the binary path." >&2; exit 2; }--command -v python3 >/dev/null 2>&1 || {- echo "xc-index: python3 is required (xc.py needs it too)." >&2; exit 2; }--# An auth-enabled node needs the key on every request this script makes itself,-# not only on the ones autoindex makes (autoindex reads XERJ_API_KEY on its own).-auth=()-[ -n "${XERJ_API_KEY:-}" ] && auth=(-H "Authorization: ApiKey $XERJ_API_KEY")--# `${auth[@]+…}`, not a bare "${auth[@]}": under `set -u`, bash 3.2 — still what-# macOS ships as /bin/bash — treats expanding an EMPTY array as an unbound-# variable and exits, so every call would fail on a node without auth.-http() { curl -fsS -m 30 ${auth[@]+"${auth[@]}"} "$@"; }--http -m 5 "$URL/_cluster/health" >/dev/null 2>&1 || {- echo "xc-index: no XERJ at $URL. Start it, or set XERJ_URL." >&2; exit 2; }--# ----------------------------------------------------------------------------# WHAT --fresh MEANS (issue #930)-#-# This flag used to be forwarded to `xerj autoindex --fresh`, which is a-# different thing: it discards autoindex's resume journal and never touches the-# records already on the server, and it is REFUSED outright once a durable-# corpus generation exists. So `xc-index.sh <corpus> --fresh` failed for every-# corpus that had been indexed before — with "cannot become generation-# authority" for a state directory written before the generation format, and-# with "--fresh cannot discard committed corpus generation N" for one written-# since. autoindex's own advice in both messages is the same: build into a NEW-# --state-dir and a NEW --prefix, validate, then switch readers. A wrapper that-# owns the whole `xc-<corpus>` namespace can do exactly that, so it does:-#-# 1. build the replacement under xc-<corpus>-b<stamp>-* with a state dir-# of its own — nothing an earlier run left can be adopted or refuse;-# 2. verify it: autoindex exited 0 or 3 AND _count > 0;-# 3. switch readers by rewriting state/<corpus>.json (atomic rename);-# 4. retire the old indices, by exact name, plus their catalog documents and-# their state directory — only now, never before step 2 passed.-#-# A failed build removes only what it created and leaves the old index, the old-# state file and the old state directory exactly as they were.-#-# The state file keeps "prefix": "xc-<corpus>" on purpose. `xc-<corpus>*`-# matches every build's indices, so any reader that globs on it keeps working-# across a rebuild. `index_prefix` is the exact build, and xc.py prefers it, so-# during the (deliberate) overlap between step 1 and step 4 it does not see the-# half-built replacement beside the index it is still serving.-# -----------------------------------------------------------------------------state_file="$ROOT/state/$name.json"--# Read one string field of the state file; empty when absent or unreadable.-state_get() {- [ -f "$state_file" ] || return 0- python3 - "$state_file" "$1" <<'PY' 2>/dev/null || true-import json, sys-try:- value = json.load(open(sys.argv[1])).get(sys.argv[2], "")-except Exception:- value = ""-print(value if isinstance(value, str) else "")-PY-}--# Every index under `xc-<corpus>-` that belongs to THIS corpus. The bare glob is-# not enough: `xc-battle-*` also matches the sibling corpus `battle-terse`, and-# retiring a sibling's indices is not a mistake this script gets to make. An-# index is a sibling's when it sits under `xc-<other>-` for a longer corpus name-# that extends this one — known from corpora/ and from state/.-# The filter is passed with -c, NOT as a heredoc on `python3 -`: a heredoc IS the-# process's stdin, so it would replace the pipe carrying the index list — the-# filter would read nothing, and curl would die writing into a closed pipe-# (exit 23), which `pipefail` + `set -e` turn into a silent exit of this script.-CORPUS_INDICES_PY='-import json, os, sys-name, corpora, state = sys.argv[1], sys.argv[2], sys.argv[3]-siblings = set()-for folder, strip in ((corpora, ""), (state, ".json")):- try:- for entry in os.listdir(folder):- other = entry[: -len(strip)] if strip and entry.endswith(strip) else entry- if other != name and other.startswith(name + "-"):- siblings.add("xc-%s-" % other)- except OSError:- pass-try:- rows = json.load(sys.stdin)-except Exception:- rows = []-for row in rows if isinstance(rows, list) else []:- index = row.get("index", "") if isinstance(row, dict) else ""- if index.startswith("xc-%s-" % name) and not any(index.startswith(s) for s in siblings):- print(index)-'-corpus_indices() {- # A wildcard that matches nothing may answer 404; that is "no indices", not a- # failure. Any other error also lists nothing, which errs toward keeping an- # index (nothing is retired that was not listed), never toward deleting one.- { http "$URL/_cat/indices/xc-$name-*?format=json&h=index" 2>/dev/null || true; } \- | python3 -c "$CORPUS_INDICES_PY" "$name" "$CORPORA" "$ROOT/state"-}--# Records under one exact index prefix, asked ONCE. Three answers, and the-# difference between the last two is the whole point:-# a number the node counted them-# 0 the node answered 404 — the wildcard matches no index, so no records-# (nothing) the node DID NOT SAY: timeout, 5xx, connection refused, junk-# "Did not say" used to be folded into 0 by every caller, and 0 is what-# authorises the two destructive steps below. One 503 on one request was enough-# to (a) read a working 500-record index as "nothing to fall back to", keep a-# FAILED build over it and retire it, and (b) read a finished build as "empty"-# and delete it with its resume state. A node under memory pressure — the node-# a long build produces — answers exactly like that.-count_once() {- local reply code- # No -f: the status is read, not inferred. `|| return 0`: under `pipefail` +- # `set -e` a failure inside `x="$(count_once …)"` would end the script at the- # assignment instead of reporting "did not say".- reply="$(curl -sS -m 30 ${auth[@]+"${auth[@]}"} -w '\n%{http_code}' "$URL/$1-*/_count" 2>/dev/null)" || return 0- code="${reply##*$'\n'}"- case "$code" in- 200) printf '%s\n' "${reply%$'\n'*}" \- | sed -n 's/.*"count"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p' | head -n 1 || true ;;- 404) echo 0 ;;- esac-}--# The same, asked patiently: a busy node gets several chances before "did not-# say" is believed. Still prints nothing when it never answered — callers must-# treat that as UNKNOWN, never as zero.-COUNT_TRIES="${XC_COUNT_TRIES:-6}"-COUNT_PAUSE="${XC_COUNT_PAUSE:-5}"-count_under() {- local attempt=1 value=""- while :; do- value="$(count_once "$1")"- if [ -n "$value" ]; then printf '%s\n' "$value"; return 0; fi- [ "$attempt" -lt "$COUNT_TRIES" ] || return 0- attempt=$((attempt + 1))- sleep "$COUNT_PAUSE"- done-}--delete_indices() { # names on stdin, one per line; exact names only, never a wildcard- local failed=0 index- while IFS= read -r index; do- [ -n "$index" ] || continue- http -X DELETE "$URL/$index" >/dev/null 2>&1 || { failed=$((failed+1)); echo "xc-index: could not delete $index" >&2; }- done- return "$failed"-}--# The catalog is one global index shared by every corpus on the node, so its-# documents are removed by EXACT scope value: `corpus_scope` is a keyword, and a-# `term` on a legacy analyzed `prefix` cannot equal a hyphenated value at all —-# it under-deletes there, it never reaches a sibling corpus.-delete_catalog_scope() {- http -X POST "$URL/autoindex-catalog/_delete_by_query?refresh=true" \- -H 'Content-Type: application/json' \- -d "{\"query\":{\"bool\":{\"minimum_should_match\":1,\"should\":[{\"term\":{\"corpus_scope\":\"$1\"}},{\"term\":{\"prefix\":\"$1\"}}]}}}" \- >/dev/null 2>&1 || echo "xc-index: could not clean autoindex-catalog for '$1' (harmless; \`xerj autoindex map\` may list retired datasets)" >&2-}--write_state() { # rc salvaged build index_prefix state_dir- mkdir -p "$ROOT/state"- local tmp="$state_file.tmp.$$"- python3 - "$tmp" "$name" "$URL" "$1" "$2" "$3" "$4" "$5" <<'PY'-import json, sys, datetime-path, corpus, url, rc, salvaged, build, index_prefix, state_dir = sys.argv[1:9]-state = {- "corpus": corpus,- "indexed_at": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),- "prefix": "xc-%s" % corpus,- "url": url,- "autoindex_exit": int(rc),- "salvaged": salvaged == "true",-}-if build:- state.update({"build": build, "index_prefix": index_prefix, "state_dir": state_dir})-with open(path, "w") as handle:- json.dump(state, handle, separators=(",", ":"))- handle.write("\n")-PY- mv -f "$tmp" "$state_file" # rename is atomic: a reader sees the old build or the new, never half-}--report() { # rc docs- case "$1" in- 0) echo "indexed cleanly" ;;- 3) echo "indexed (exit 3: some files skipped as junk — normal for real repos)" ;;- esac- echo "corpus '$name' searchable: $2 records"- echo "next: xc.py $name \"<what you need>\""-}--old_build="$(state_get build)"-old_index_prefix="$(state_get index_prefix)"-old_state_dir="$(state_get state_dir)"-old_url="$(state_get url)"--# ── Which run is this? ──────────────────────────────────────────────────────-mode=legacy-if $fresh; then- mode=build-elif [ -n "$old_build" ] && [ -n "$old_index_prefix" ] && [ -d "$old_state_dir" ] && [ "$old_url" = "$URL" ]; then- live="$(count_under "$old_index_prefix")"- if [ -n "$live" ] && [ "$live" -gt 0 ] 2>/dev/null; then- mode=update- else- # The ledger names a build this node does not hold (data-dir swap, another- # port). There is nothing to update and nothing to lose, so build.- echo "xc-index: state/ records build $old_build but $URL holds no records for it — building it here"- mode=build- fi-elif [ ! -f "$state_file" ] && [ -z "$(corpus_indices)" ]; then- mode=build # first index of this corpus: same path as --fresh, nothing to retire-fi--echo "indexing corpus '$name' from $dir"--# --no-graph: reference code needs ranked passages, not a relationship map. The-# graph detectors cost real time on a large tree and nothing here consumes edges.-run_autoindex() { # prefix [state-dir]- local args=("$dir" --url "$URL" --prefix "$1" --no-graph)- [ -n "${2:-}" ] && args+=(--state-dir "$2")- set +e- "$XERJ_BIN" autoindex "${args[@]}"- rc=$?- set -e-}--case "$mode" in-# ── build: first index, or --fresh ──────────────────────────────────────────-build)- # Listed BEFORE the build so "old" can never include what this run creates.- old_indices="$(corpus_indices)"- # The build id has one-second resolution, and everything below keys on it: a- # second --fresh inside the same second would reuse the prefix of the build it- # is replacing, write into its indices, and then RETIRE them as "old". So the- # id must be new — not the recorded build, not a state directory that exists,- # not a prefix any live index already sits under.- build="b$(date -u +%Y%m%d%H%M%S)"- while [ "$build" = "$old_build" ] || [ -e "$STATE_ROOT/$name/$build" ] \- || printf '%s\n' "$old_indices" | grep -q "^xc-$name-$build-"; do- sleep 1- build="b$(date -u +%Y%m%d%H%M%S)"- done- new_prefix="xc-$name-$build"- new_state="$STATE_ROOT/$name/$build"- # Is there a working index to protect? When the node cannot count it, the- # answer is YES: presuming "none" is what lets a failed build be kept over it- # and the old indices be retired.- has_working_index=false- if [ -n "$old_indices" ]; then- old_docs="$(count_under "${old_index_prefix:-xc-$name}")"- if [ -z "$old_docs" ]; then- has_working_index=true; old_docs="an unknown number of"- echo "xc-index: the node did not answer a record count for the existing index; treating it as" >&2- echo "xc-index: a WORKING index — a failed build will not be kept over it." >&2- elif [ "$old_docs" -gt 0 ] 2>/dev/null; then- has_working_index=true- fi- echo "xc-index: --fresh — building $new_prefix-* beside the existing index ($old_docs records);"- echo "xc-index: the existing index stays live until the replacement has been verified"- fi- mkdir -p "$new_state"- run_autoindex "$new_prefix" "$new_state"-- docs="$(count_under "$new_prefix")"- if [ -z "$docs" ]; then- # UNKNOWN is not EMPTY. The cleanup below deletes this build's indices and- # its resume state, so it may only run on a count the node actually gave.- echo "xc-index: the node did not answer a record count for build $build ($COUNT_TRIES attempts;" >&2- echo "xc-index: autoindex exit $rc). It cannot be verified, so NOTHING was deleted and NOTHING" >&2- echo "xc-index: was switched: its indices ($new_prefix-*) and its state directory are kept." >&2- if $has_working_index; then- echo "xc-index: the existing index was NOT touched and is still what xc.py serves." >&2- echo "xc-index: When the node answers again, re-run with --fresh; the unverified build is" >&2- echo "xc-index: retired by the next build that verifies." >&2- else- # Nothing to protect and nothing else to serve: record it for what it is,- # so xc.py warns on every query and a plain re-run resumes or confirms it.- write_state "$rc" true "$build" "$new_prefix" "$new_state"- echo "xc-index: There is no other index for '$name', so this build is recorded as UNVERIFIED" >&2- echo "xc-index: (xc.py will say so). Re-run xc-index.sh $name to resume or confirm it." >&2- fi- [ "$rc" -ne 0 ] && [ "$rc" -ne 3 ] && exit "$rc"- exit 1- fi- salvaged=false- verified=false- case $rc in- 0|3) [ "$docs" -gt 0 ] 2>/dev/null && verified=true ;;- *)- # autoindex can abort in finalisation AFTER every document was written- # (#367), leaving a complete, queryable index behind. That is worth- # keeping when the alternative is no corpus at all — and NOT worth- # swapping a verified, working index out for.- if [ "$docs" -gt 0 ] 2>/dev/null && ! $has_working_index; then- verified=true; salvaged=true- echo "xc-index: WARNING — autoindex exited $rc, but this build wrote $docs records and" >&2- echo "xc-index: there is no working index to fall back to. Recording it as indexed with" >&2- echo "xc-index: autoindex_exit=$rc; coverage is not guaranteed — please report the error above." >&2- fi- ;;- esac-- if ! $verified; then- echo "xc-index: build $build did not verify (autoindex exit $rc, $docs records)." >&2- # Remove only what THIS run created; everything that existed before stays.- comm -13 <(printf '%s\n' "$old_indices" | sort) <(corpus_indices | sort) \- | grep "^$new_prefix-" | delete_indices || true- delete_catalog_scope "$new_prefix"- rm -rf "$new_state"- if [ -n "$old_indices" ]; then- echo "xc-index: the existing index was NOT touched and is still what xc.py serves." >&2- fi- [ "$rc" -ne 0 ] && [ "$rc" -ne 3 ] && exit "$rc"- exit 1- fi-- # Verified. Switch readers first, retire second: a crash between the two- # leaves a duplicate, never a gap.- write_state "$rc" "$salvaged" "$build" "$new_prefix" "$new_state"- if [ -n "$old_indices" ]; then- # Belt and braces for the invariant above: whatever else is true, an index- # of the build that was just verified is never on the retire list.- old_indices="$(printf '%s\n' "$old_indices" | grep -v "^$new_prefix-" || true)"- fi- if [ -n "$old_indices" ]; then- echo "xc-index: replacement verified ($docs records) — retiring $(printf '%s\n' "$old_indices" | wc -l | tr -d ' ') old indices"- if ! printf '%s\n' "$old_indices" | delete_indices; then- echo "xc-index: WARNING — some old indices could not be deleted. The corpus is healthy and" >&2- echo "xc-index: xc.py reads only $new_prefix-*; delete the leftovers by name when the node allows." >&2- fi- delete_catalog_scope "${old_index_prefix:-xc-$name}"- fi- # Earlier builds' state directories are dead weight once their indices are gone.- if [ -d "$STATE_ROOT/$name" ]; then- find "$STATE_ROOT/$name" -mindepth 1 -maxdepth 1 -type d ! -name "$build" -exec rm -rf {} +- fi- report "$rc" "$docs"- ;;--# ── update: reconcile the recorded build in place ───────────────────────────-update)- run_autoindex "$old_index_prefix" "$old_state_dir"- case $rc in- 0|3) ;;- *)- echo "xc-index: updating build $old_build failed with exit $rc. The index is unchanged." >&2- echo "xc-index: re-run with --fresh to build a replacement beside it (the existing index" >&2- echo "xc-index: stays live until the replacement verifies)." >&2- exit "$rc"- ;;- esac- docs="$(count_under "$old_index_prefix")"; [ -n "$docs" ] || docs="?"- write_state "$rc" false "$old_build" "$old_index_prefix" "$old_state_dir"- report "$rc" "$docs"- ;;--# ── legacy: a corpus indexed before builds existed, updated the way it was ──-legacy)- # Recorded before the run so a failure can tell "this run wrote records" apart- # from "an earlier run's records are still lying around". Salvaging the latter- # would date stale data to now, which SKILL.md calls worse than no index.- docs_before="$(count_under "xc-$name")"- before_known=true- [ -n "$docs_before" ] || { before_known=false; docs_before=0; }- run_autoindex "xc-$name"- docs=""- salvaged=false- case $rc in- 0|3) ;;- *)- docs="$(count_under "xc-$name")"- # Without a count from BEFORE the run, "more records than before" cannot be- # shown, and salvaging would date an earlier run's records to now.- if $before_known && [ -n "$docs" ] && [ "$docs" -gt "$docs_before" ] 2>/dev/null; then- salvaged=true- echo "xc-index: WARNING — autoindex exited $rc, but this run wrote records" >&2- echo "xc-index: ($docs_before -> $docs). The corpus is queryable and is being" >&2- echo "xc-index: recorded as indexed, with autoindex_exit=$rc in its state file." >&2- echo "xc-index: Coverage is not guaranteed — please report the error above." >&2- else- echo "xc-index: autoindex failed with exit $rc and wrote no new records." >&2- echo "xc-index: If the error above says the state directory cannot become generation" >&2- echo "xc-index: authority, or that --fresh is refused, run: xc-index.sh $name --fresh" >&2- echo "xc-index: It builds a replacement beside the existing index and retires the old one" >&2- echo "xc-index: only after the new one verifies." >&2- exit "$rc"- fi- ;;- esac- [ -n "$docs" ] || docs="$(count_under "xc-$name")"- [ -n "$docs" ] || docs="?"- write_state "$rc" "$salvaged" "" "" ""- report "$rc" "$docs"- ;;-esacdiff --git a/tools/xerj-code/scripts/xc.py b/tools/xerj-code/scripts/xc.pydeleted file mode 100755index 87366c178..000000000--- a/tools/xerj-code/scripts/xc.py+++ /dev/null@@ -1,814 +0,0 @@-#!/usr/bin/env python3-"""Retrieve reference passages from an indexed corpus.--This is the tool the agent calls before writing code. It returns ranked passages-with file:line provenance, and it refuses to answer from a stale index rather-than handing back code that no longer exists.-"""-import argparse-import http.client-import json-import os-import re-import sys-import urllib.error-import urllib.request-from datetime import datetime, timedelta, timezone--ROOT = os.environ.get("XERJ_CODE_HOME", os.path.expanduser("~/.xerj-code"))-URL = os.environ.get("XERJ_URL", "http://localhost:9200")-STALE_DAYS = 30--# Reciprocal Rank Fusion constant (Cormack, Clarke & Buettcher, SIGIR 2009).-# k=60 is the paper's value and the universal default. It is NOT tuned here.-RRF_K = 60--# Licences you must not copy from, as substrings of what the manifest records.-# This MUST stay in step with `warn_licence()` in xc-corpus.sh: that one fires-# once at clone time, this one fires at the moment an agent is actually looking-# at the code and deciding whether to lift it, which is the one that counts.-#-# Warning on only ("GPL", "LGPL") — an exact match, as this did — was silent on-# every restricted repo the hub deliberately ships: elasticsearch (AGPL/SSPL/-# Elastic), meilisearch's Enterprise Edition parts (BUSL), and, once the-# detector was corrected to read MPL-2.0 rather than GPL, sonic as well. Fixing-# the detector must not quietly cost a repo its warning.-RESTRICTED = ("AGPL", "SSPL", "Elastic", "BUSL", "GPL", "LGPL", "MPL",- "UNKNOWN", "NONE-FOUND")---def die(msg, code=2):- print(f"xc: {msg}", file=sys.stderr)- sys.exit(code)---def field_report_nudge():- """One line, on STDERR, at most once a day: file the field report.-- The reference-coding loop had no path back to the maintainers — an agent- retrieved, wrote code, and left, and the folder that asks for a short field- report stayed empty. This is that missing path, surfaced where the agent- already is. It is deliberately unobtrusive: it writes only to stderr, so it- can NEVER corrupt the retrieval passages a caller parses on stdout; it fires- at most once per day per machine via a marker under ROOT, so a session's many- queries do not turn it into spam; and it is silenced entirely by- XERJ_CODE_NO_NUDGE. A cache we cannot write is a reason to stay quiet, not to- nag every query.- """- if os.environ.get("XERJ_CODE_NO_NUDGE"):- return- try:- marker = os.path.join(ROOT, f".field-report-nudge-{datetime.now():%Y%m%d}")- if os.path.exists(marker):- return- os.makedirs(ROOT, exist_ok=True)- open(marker, "w").close()- except OSError:- return- print(- "xc: wrapping up? `xerj feedback --open-pr` files the one short field "- "report XERJ asks every agent for (or --dry-run if sandboxed); it "- "auto-fills the facts and a field-report-only PR skips the CLA gate. "- "Silence with XERJ_CODE_NO_NUDGE=1.",- file=sys.stderr,- )---def load_state(corpus):- path = os.path.join(ROOT, "state", f"{corpus}.json")- if not os.path.exists(path):- die(f"corpus '{corpus}' is not indexed — run xc-index.sh {corpus}")- with open(path) as fh:- return json.load(fh)---def query_prefix(state):- """The index prefix to query for this corpus.-- `xc-index.sh --fresh` builds a replacement BESIDE the index it replaces and- retires the old one only after the new one verifies (#930), so for the- length of a rebuild two builds of one corpus exist under `xc-<corpus>-*`.- The state file therefore records two things: `prefix` (`xc-<corpus>`, the- whole namespace, unchanged since the first release so anything that globs on- it keeps working) and `index_prefix` (`xc-<corpus>-b<stamp>`, the ONE build- that was verified). Querying the exact build is what keeps a half-built- replacement — or a retired build whose delete failed — out of the answers.- A state file written before builds existed has no `index_prefix`.- """- return state.get("index_prefix") or state.get("prefix") or f"xc-{state.get('corpus', '')}"---def live_index_count(prefix):- """How many indices under `prefix*` actually exist on the target server.-- `state/<corpus>.json` records that a corpus was once indexed, and against- which url. It is NOT proof the corpus is loaded on the server THIS process- is querying: the state entry survives a data-dir swap, a server restart onto- an empty dir, or an XERJ_URL pointed at a different node. When that happens- the prefix resolves to zero indices and every query returns "no match" —- indistinguishable from a genuinely bad query, which is the exact failure- reference-coding exists to prevent (an agent concludes "no reference" and- starts guessing). So the count is checked explicitly.-- Returns an int on success (0 meaning "in state/ but not loaded here"), or- None when the server is unreachable/unparseable — in which case the caller- must NOT claim "0 live indices": the ordinary search path will report the- transport failure honestly instead.- """- req = urllib.request.Request(f"{URL}/_cat/indices/{prefix}*?format=json&h=index")- try:- with urllib.request.urlopen(req, timeout=30) as resp:- data = json.load(resp)- except urllib.error.HTTPError as e:- # A 404 on a wildcard means "no such indices" -> 0 loaded. Any other- # HTTP status is an ambiguous server condition, not a clean zero.- return 0 if e.code == 404 else None- except (urllib.error.URLError, ValueError):- return None- if not isinstance(data, list):- return None- return len(data)---def require_loaded(state):- """Fail with a DISTINCT, actionable message when the corpus is not loaded.-- Kept deliberately separate from the empty-result path in main(): "0 live- indices here" and "the corpus is loaded but nothing matched your query" are- different diagnoses with different fixes, and collapsing them is the bug this- guard closes.- """- prefix = query_prefix(state)- count = live_index_count(prefix)- if count is None:- return # server unreachable/ambiguous — let the search path report it.- if count == 0:- name = state.get("corpus", "?")- stamp = state.get("indexed_at", "?")- against = state.get("url")- hint = (f" It was indexed against {against}." if against and against != URL- else " It was indexed against a different data dir or server.")- die(f"corpus '{name}' is in state/ (indexed {stamp}) but has 0 live "- f"indices ('{prefix}*') on {URL}.{hint} Re-run xc-index.sh {name}, "- f"or set XERJ_URL to the node that has it. (This is NOT a 'no "- f"match' — the corpus simply is not loaded on this server.)", code=3)---def incomplete_coverage(state):- """The ledger's own word that this index came from a run that did not finish.-- xc-index.sh keeps a build whose autoindex run exited non-zero when the only- alternative is no corpus at all, and records `salvaged: true` and the exit- code in the state file with the words "coverage is not guaranteed". Nothing- ever read them back, so the one party who needed to know — whoever is- querying — saw a normal index: a miss against a half-built corpus read- exactly like "this code does not exist", which is the false confidence the- staleness check exists to prevent. Exit 0 is clean and 3 is completed with- junk or refused datasets; anything else did not finish. `salvaged` is also- set for a build whose record count the node never answered, whatever its- exit code, so the wording covers both: not verified complete.-- Returns the warning line, or None when the ledger records a finished run.- """- rc = state.get("autoindex_exit")- finished = rc in (None, 0, 3) or isinstance(rc, bool)- if finished and not state.get("salvaged"):- return None- name = state.get("corpus", "?")- how = f"autoindex exit {rc}" + (", kept unverified" if state.get("salvaged") else "")- return (f"WARNING: the index for '{name}' was NOT verified complete ({how}). "- f"Coverage may be INCOMPLETE: a miss here is not evidence that the "- f"code is absent. Re-run xc-index.sh {name} to resume or confirm it.")---def check_fresh(state, stale_ok):- """A stale index returns code that no longer exists, with false confidence."""- stamp = state.get("indexed_at")- if not stamp:- return None- when = datetime.strptime(stamp, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc)- age = datetime.now(timezone.utc) - when- if age > timedelta(days=STALE_DAYS) and not stale_ok:- die(f"index for '{state['corpus']}' is {age.days} days old. "- f"Re-run xc-index.sh {state['corpus']} --fresh, or pass --stale-ok.")- return age.days---# These exact fields and these exact (flat) weights were measured, not chosen.-# Swept 7 variants over 6 ground-truth queries on a 324-file Rust corpus:-#-# body, defs, title (flat) top1 3/6 top3 6/6 <- this-# title^3 defs body top1 3/6 top3 6/6-# defs^2 body top1 3/6 top3 4/6-# defs^3 title^2 body top1 2/6 top3 5/6-# body alone top1 2/6 top3 3/6-# title^2 body top1 1/6 top3 2/6-#-# Boosting `defs` looks obviously right and measures worse: `defs` is a flat-# blob of every symbol name in the file, so a boost favours whichever file-# defines the most symbols — usually a test module, not the implementation.-# top3 is the metric that matters here; the agent reads k passages, not one.-#-# Two fields are deliberately absent:-# `symbols.name` — `symbols` is an array of objects with no searchable `.name`-# subpath. Including it makes the whole multi_match return ZERO hits with no-# error at all. It took an Aho-Corasick query from 0 hits to 3 correct-# source files just to remove it. A silent zero is the worst failure shape-# available, so it is called out here rather than left to be rediscovered.-# `"*"` — a bare wildcard flattens every score to the same value (measured:-# every hit scored exactly 2.0), destroying the ranking entirely.-# `defs_expanded^0.5` — a low-weight RECALL field (present only on indexes built-# by the enrichment server): per-symbol signatures + identifier sub-words-# (`per_tick` -> `per tick`). It is boosted BELOW 1.0 on purpose, so it adds hits-# a behavioural query would otherwise miss WITHOUT overriding the precise name-# match in `defs`. The boost is measured, not chosen: see-# measure/SERVER_UPLIFT_SCORECARD.md.-#-# It is NOT safe to send unconditionally — see resolve_fields().-FIELDS = ["body", "defs", "title", "defs_expanded^0.5"]--_FIELDS_CACHE = {}---def resolve_fields(prefix):- """Drop query fields that no index under `prefix` actually maps.-- This engine does NOT ignore an unmapped field in `multi_match` the way ES- does — including one silently collapses a MULTI-TOKEN query to ZERO hits.- Measured 2026-08-06, one index, exact totals (`relation: eq`):-- query "log merge policy segment size buckets"- fields=["body"] -> 673 hits- fields=["body","defs"] -> 673 hits- fields=["body","defs","title"] -> 673 hits- fields=["body","defs","title","defs_expanded"] -> 0 hits-- `defs_expanded` was mapped in exactly 0 of the corpus's 219 indices, so- every multi-word query returned "no passage matches". Mapped fields of any- type (keyword, numeric) are harmless; only unmapped ones zero the query,- and only when the query has more than one token.-- The old comment here asserted the opposite — "a no-op there, multi_match- ignores a missing field" — which was never true on this engine. Until the- engine is fixed, resolve the field list against the real mapping first.-- Full reproducer and the separate memtable/segment divergence it uncovered:- measure/MULTIMATCH_DEFECT.md.- """- if prefix in _FIELDS_CACHE:- return _FIELDS_CACHE[prefix]- present = None- try:- req = urllib.request.Request(f"{URL}/{prefix}*/_mapping")- with urllib.request.urlopen(req, timeout=60) as resp:- present = set()- for _idx, m in json.load(resp).items():- present |= set(m.get("mappings", {}).get("properties", {}).keys())- except Exception:- present = None # mapping unreadable: send the list unchanged rather- # than silently narrowing it on a transport hiccup.- if present is None:- out = list(FIELDS)- else:- out = [f for f in FIELDS if f.split("^", 1)[0] in present]- out = out or ["body"] # never send an empty field list- _FIELDS_CACHE[prefix] = out- return out---def post(path, body, fatal=True):- """POST a search body; fatal=False returns HTTP/transport errors as data.-- The non-fatal path exists for the vector arm of hybrid retrieval: a corpus- where no index supports `semantic` must degrade to BM25, not abort.- """- req = urllib.request.Request(- f"{URL}/{path}",- data=json.dumps(body).encode(),- headers={"Content-Type": "application/json"},- )- try:- with urllib.request.urlopen(req, timeout=60) as resp:- return json.load(resp)- except urllib.error.HTTPError as e:- if not fatal:- # The status already means fallback. Reading an optional error- # body can itself time out or fail on an interrupted response.- e.close()- return {"_xc_error": f"{e.code}: {e.reason}"}- try:- msg = e.read()[:200].decode(errors="replace")- except (OSError, http.client.HTTPException) as read_error:- msg = f"{e.reason}; error response could not be read: {read_error}"- finally:- e.close()- die(f"search failed ({e.code}): {msg}")- except (OSError, http.client.HTTPException) as e:- # URLError is an OSError; response reads can also raise socket or- # HTTP errors directly, without urllib wrapping them.- msg = f"cannot reach XERJ at {URL}: {getattr(e, 'reason', str(e))}"- if not fatal:- return {"_xc_error": msg}- die(msg)---def bm25_query(query, lang, fields=None):- must = [{"multi_match": {"query": query, "fields": fields or FIELDS}}]- if lang:- must.append({"match": {"language": lang}})- return {"bool": {"must": must}}---def search(prefix, query, k, lang, highlight=False):- """BM25 search.-- `highlight` defaults OFF because on this engine a highlight block CHANGES- THE RANKING (issue #177). Measured on a 6-query labelled set over a- valkey+memcached corpus: identical query, top-1 6/6 without highlight and- 1/6 with it, every score shifted (12.68 -> 20.43) and the result sets- disjoint. Since `--full` now returns the matching definition from- `symbols[]`, the highlighter is not needed for the passage anyway — so the- cost of requesting it is pure ranking damage.- """- body = {"size": k, "query": bm25_query(query, lang, resolve_fields(prefix))}- if highlight:- body["highlight"] = {- "fields": {"*": {"fragment_size": 320, "number_of_fragments": 2}},- }- return post(f"{prefix}*/_search", body)---def semantic_indices(prefix, field="body", fatal=False):- """Indices under `prefix*` whose `field` is mapped as semantic_text.-- A `semantic` query against an index where the field is plain `text` does not- return fewer hits — it fails the WHOLE search with a 400, taking every other- index in the wildcard down with it. Measured on this corpus: 3 of 9- `xc-rust-text-*` indices carry semantic_text; querying the wildcard errors- outright. So the capable set is discovered from the mapping, and the vector- arm is aimed only at those indices.-- Returns (capable, total). An unreachable or unparseable mapping yields an- empty capable set, which degrades to BM25 rather than failing. Standalone- semantic retrieval uses fatal=True because it has no BM25 result to keep.- """- req = urllib.request.Request(f"{URL}/{prefix}*/_mapping")- try:- with urllib.request.urlopen(req, timeout=30) as resp:- mapping = json.load(resp)- except (OSError, http.client.HTTPException, ValueError) as e:- if isinstance(e, urllib.error.HTTPError):- e.close()- if fatal:- die(f"semantic mapping lookup failed at {URL}: {e}")- return [], 0- if not isinstance(mapping, dict):- return [], 0- capable = [- name for name, m in sorted(mapping.items())- if (m.get("mappings", {}).get("properties", {})- .get(field, {}).get("type") == "semantic_text")- ]- return capable, len(mapping)---def semantic_search(indices, query, k, lang, field="body", fatal=False):- """Vector search; errors are optional only when BM25 fallback is allowed."""- if not indices:- return []- q = {"semantic": {"field": field, "query": query}}- if lang:- q = {"bool": {"must": [q, {"match": {"language": lang}}]}}- res = post(f"{','.join(indices)}/_search", {"size": k, "query": q}, fatal=fatal)- if "_xc_error" in res:- return []- return res.get("hits", {}).get("hits", [])---def rrf(lists, size, k=RRF_K):- """Reciprocal Rank Fusion: score(d) = sum over lists of 1/(k + rank(d)).-- Ranks are 1-based. A document missing from a list contributes nothing —- that is the whole point of RRF: it needs only the orderings, so it never has- to reconcile a BM25 score of 13.0 with a cosine-ish score of 0.81, which are- not on the same scale and cannot be added.-- Ties are broken by BM25 rank — it is the arm the FIELDS sweep was measured- on and the one hybrid falls back to. Without a stated rule the order would- depend on dict iteration and the measurement would not reproduce. Exact ties- are not hypothetical: on "two-way substring search algorithm" the top two- documents both score 0.032522 (ranks 1,2 and 2,1), and this rule decides- which one the agent reads first. It was fixed before the scoring run, not- after — a tie-break picked once its effect on the score is known is not a- measurement.- """- fused = {}- for li, hits in enumerate(lists):- for rank, h in enumerate(hits, start=1):- key = (h.get("_index"), h.get("_id"))- slot = fused.setdefault(key, {"hit": h, "rrf": 0.0, "ranks": {}})- slot["rrf"] += 1.0 / (k + rank)- slot["ranks"][li] = rank- # Keep the BM25 copy of the document: it carries the highlights.- if li == 0:- slot["hit"] = h- out = []- for slot in sorted(fused.values(),- key=lambda s: (-s["rrf"], s["ranks"].get(0, 10**6))):- h = dict(slot["hit"])- h["_score"] = slot["rrf"]- h["_rrf_ranks"] = slot["ranks"]- out.append(h)- return out[:size]---def hybrid_search(prefix, query, k, lang, depth=None):- """BM25 + vector, fused by RRF.-- `depth` is how many candidates each arm contributes before fusion. Fusing- only the k the caller asked for would mean a document ranked k+1 by BM25 and- 1 by the vector arm could never surface, which is precisely the case fusion- exists to catch.-- Returns (hits, note). `note` is never None: the caller must be able to say- which arms actually ran, because a silently BM25-only "hybrid" result would- be indistinguishable from a working one.- """- depth = depth or max(4 * k, 20)- bm = search(prefix, query, depth, lang).get("hits", {}).get("hits", [])- if not bm:- # BM25 finding nothing is the corpus's only honest "no". The vector arm- # cannot supply one: the built-in embedder is LEXICAL, and it returns- # its nearest neighbours for any input whatsoever. Measured: the query- # "xyzzy plugh frobnicate quuxbaz" returns 0 BM25 hits and 3 confident- # vector hits. Passing those through would convert an explicit miss into- # three irrelevant files at exit 0 — the exact silent failure the- # no-match branch below exists to prevent.- return [], ("no lexical match in this corpus — vector nearest-neighbours "- "are not evidence of a match, so this is reported as a miss")- capable, total = semantic_indices(prefix)- if not capable:- return bm[:k], (f"BM25 only — no usable semantic_text mapping for `body` "- f"could be discovered under '{prefix}*'")- sem = semantic_search(capable, query, depth, lang)- if not sem:- return bm[:k], (f"BM25 only — vector search failed or returned no hits from the "- f"{len(capable)} semantic_text index(es)")- note = (f"hybrid RRF(k={RRF_K}) — BM25 over {total} index(es), vector over "- f"{len(capable)} of {total}")- return rrf([bm, sem], k), note---def symbol_spans(src):- """[(name, kind, start_line, end_line)] from the record's own `symbols`.-- A definition runs until the next definition starts, which is a coarse but- honest bound: it never claims a range the index did not report, and it is- exactly right for the common case of top-level functions laid out in order.- """- syms = src.get("symbols") or []- if not isinstance(syms, list):- return []- got = sorted(- ((s.get("name"), s.get("kind"), int(s["line"]))- for s in syms- if isinstance(s, dict) and s.get("name") and isinstance(s.get("line"), int)),- key=lambda t: t[2],- )- out = []- for i, (name, kind, line) in enumerate(got):- end = got[i + 1][2] - 1 if i + 1 < len(got) else None- out.append((name, kind, line, end))- return out---def symbol_passage(body, src, query, width):- """Return the DEFINITION that best matches the query, not a byte window.-- This is the difference between "search found the file" and "the agent got- the code". Measured on a real valkey corpus: a query about null replies- ranks networking.c correctly, but `addReplyNull` is at line 1460 — roughly- 40 KB in — so any head- or window-based slice of a 200 KB file is a coin- flip on whether the answer is inside it. The record already carries- {name, kind, line} for all 278 definitions in that file; using them turns a- guess into a lookup.-- Returns (text, label) or None when the record has no usable symbols.- """- spans = symbol_spans(src)- if not spans:- return None- lines = body.splitlines()- if not lines:- return None- terms = [t.lower() for t in re.findall(r"[A-Za-z_][A-Za-z0-9_]{2,}", query)]- if not terms:- return None-- best = None- for name, kind, start, end in spans:- lo = max(0, start - 1)- hi = min(len(lines), end if end else len(lines))- if hi <= lo:- continue- text = "\n".join(lines[lo:hi])- low = text.lower()- # Name match is the strongest signal an agent can act on: a query- # mentioning `addReplyNull` should return addReplyNull, not whichever- # unrelated span happens to repeat a common word most often.- nm = (name or "").lower()- score = sum(low.count(t) for t in terms)- score += 25 * sum(1 for t in terms if t in nm)- if score <= 0:- continue- if best is None or score > best[0]:- best = (score, name, kind, start, text)- if best is None:- return None- _, name, kind, start, text = best- if len(text) > width:- text = text[:width] + f"\n ... [{kind} {name} truncated at {width} chars]"- return text, f"{kind} {name} @ line {start}"---def best_window(body, query, width):- """The densest sampled `width`-char slice, snapped to lines when safe.-- Taking the HEAD of the file instead is the single worst bug this tool had.- Measured on a real valkey+memcached corpus: retrieval ranked the correct- files (`memcached/proto_text.c` #1 for a memcached protocol query), then- handed back 21,461 chars containing ZERO occurrences of `$-1`, `addReply`,- `STORED` or `CRLF` — the entire reason to retrieve those files. `addReplyNull`- lives at networking.c:1261, thousands of chars past a head-truncation, so the- model received licence banners and #include lines and nothing else.-- A file-level record means retrieval can only tell you WHICH file. Choosing- the passage is this function's job, and skipping it makes the whole reference- block worthless while still looking substantial.-- Returns (window, start_offset, total_len).- """- total = len(body)- if total <= width:- return body, 0, total- terms = [t.lower() for t in re.findall(r"[A-Za-z_][A-Za-z0-9_]{2,}", query)]- if not terms:- return body[:width], 0, total- # Score every candidate start on a coarse stride: dense term hits win. The- # stride keeps this linear-ish on multi-hundred-KB sources.- stride = max(1, width // 8)- best_start, best_score = 0, -1- for start in range(0, total - width + stride, stride):- # Slice before lowercasing: Unicode lowercase can expand a character,- # so offsets in a lowercased copy need not be offsets in the source.- chunk = body[start:start + width].lower()- score = sum(chunk.count(t) for t in terms)- if score > best_score:- best_start, best_score = start, score- if best_score <= 0:- return body[:width], 0, total- # Prefer complete lines, but never discard query evidence just to align- # them. The final partial line may hold the match, or the previous newline- # may be far away in a source line longer than the requested width.- nl = body.rfind("\n", 0, best_start)- start = nl + 1 if nl != -1 else best_start- end = body.rfind("\n", start, start + width)- end = end if end > start else min(total, start + width)- snapped = body[start:end].lower()- if sum(snapped.count(t) for t in terms) < best_score:- return body[best_start:best_start + width], best_start, total- return body[start:end], start, total---def provenance(src):- """file:line, or the best locator the record actually carries.-- Never invent a line number — a fabricated citation is worse than none,- because it survives review by looking checkable.- """- path = (src.get("ax_path") or src.get("ax_file")- or src.get("path") or src.get("file") or "?")- line = src.get("line") or src.get("start_line") or src.get("lineno")- return f"{path}:{line}" if line else path---def list_corpora():- """Show every state/ entry and whether it is actually loaded HERE.-- The whole point: freshness in state/ does not imply the corpus is queryable- on this server. This prints the live index count per corpus so an agent can- see the real, loadable corpus set without hitting _cat/indices by hand — and- without mistaking an over-advertised ledger for the truth.- """- state_dir = os.path.join(ROOT, "state")- if not os.path.isdir(state_dir):- die(f"no state directory at {state_dir} — nothing indexed yet")- entries = sorted(f[:-5] for f in os.listdir(state_dir) if f.endswith(".json"))- if not entries:- die(f"no corpora in {state_dir} — run xc-index.sh <corpus>")- print(f"corpora in state/ (queried against {URL}):")- loaded = 0- for name in entries:- try:- with open(os.path.join(state_dir, f"{name}.json")) as fh:- st = json.load(fh)- except (OSError, ValueError):- print(f" {name:<18} !! unreadable state file")- continue- st.setdefault("corpus", name)- prefix = query_prefix(st)- stamp = (st.get("indexed_at") or "?")[:10]- count = live_index_count(prefix)- if count is None:- status = "server unreachable/ambiguous"- elif count == 0:- status = "NOT loaded here (0 indices) — stale/other-server"- else:- loaded += 1- status = f"loaded — {count} index(es)"- if incomplete_coverage(st):- status += (f" — INCOMPLETE (autoindex exit "- f"{st.get('autoindex_exit')}); re-run xc-index.sh {name}")- print(f" {name:<18} {stamp} {prefix:<18} {status}")- print(f"\n{loaded} of {len(entries)} corpora are actually loaded on {URL}.")---def main():- ap = argparse.ArgumentParser(description="retrieve reference passages")- ap.add_argument("corpus", nargs="?")- ap.add_argument("query", nargs="?")- ap.add_argument("-k", type=int, default=5, help="max passages (default 5)")- ap.add_argument("--lang", help="restrict to a file extension, e.g. rs")- ap.add_argument("--stale-ok", action="store_true", help="answer from an old index anyway")- ap.add_argument("--meatl", action="store_true", help="emit MEATL instead of prose")- ap.add_argument("--json", action="store_true", help="emit raw JSON")- # Reference coding needs the actual implementation, not a keyword-in-context- # snippet. A 320-char highlight tells the agent a file is relevant; it does- # not tell it how the algorithm works.- # Defaulted, not opt-in. This used to be None, which meant the documented- # invocation `xc.py <corpus> "<query>"` skipped the symbol path entirely and- # fell through to a branch that prints body[:400] — the licence header, on- # every Apache/BSD/MIT file in every corpus (issue #368). Retrieving the- # definition IS the feature; capping its length is the knob.- ap.add_argument("--full", type=int, metavar="CHARS", default=800,- help="cap each passage at CHARS of real source (default 800; "- "0 prints only the file head)")- ap.add_argument("--no-symbol", action="store_true",- help="use a raw byte window instead of the matching definition")- # Default is BM25, decided on TWO corpora after an earlier default (hybrid)- # was chosen on one and turned out to be corpus-specific.- #- # rust-text kv-oss (C) combined- # mode top1 top3 top1 top3 top1 top3- # bm25 3/6 6/6 6/6 6/6 9/12 12/12 <- this- # hybrid 5/6 6/6 2/6 4/6 7/12 10/12- # semantic 4/6 4/6 2/6 3/6 6/12 7/12- #- # The adoption rule, fixed before the numbers were in: top-3 is the operative- # metric, because the agent reads k passages rather than one. BM25 is perfect- # on it (12/12) and is never the worst arm on either corpus. Hybrid's only- # win is top-1 on rust-text; on the C corpus it loses badly, because the- # vector arm can reach just 5 of 407 indices there (issue #173), so RRF- # fuses a good ranking with one that cannot see 98.8% of the corpus.- #- # BM25 is also ~5x faster: no vector round trip and no mapping lookup.- # Use --mode hybrid when a corpus has broad semantic_text coverage AND you- # care about top-1 specifically; measure before trusting it.- ap.add_argument("--mode", choices=("bm25", "semantic", "hybrid"), default="bm25",- help="retrieval arm (default bm25 — best top-3 on both corpora)")- ap.add_argument("--hybrid", action="store_const", const="hybrid", dest="mode",- help="shorthand for --mode hybrid (lexical + vector, RRF-fused)")- ap.add_argument("--list", action="store_true",- help="list state/ corpora and whether each is loaded HERE, "- "then exit (no corpus/query needed)")- args = ap.parse_args()-- if args.list:- list_corpora()- return- if not args.corpus or not args.query:- ap.error("the following arguments are required: corpus, query "- "(or pass --list)")-- state = load_state(args.corpus)- age = check_fresh(state, args.stale_ok)- # A corpus can be in state/ yet have zero live indices on THIS server (it- # was indexed against another data dir / node). Catch that here with a- # distinct, actionable error — never let it fall through to the generic- # "no passage matches" path, which reads as a bad query and sends the agent- # off to guess. This is the fix for the state-ledger trust trap.- require_loaded(state)- # Every time, like the mode note below: an incomplete index that answers- # silently is indistinguishable from a complete one. stderr, so `--json`- # output stays parseable.- warning = incomplete_coverage(state)- if warning:- print(warning, file=sys.stderr)-- note = None- if args.mode == "hybrid":- hits, note = hybrid_search(query_prefix(state), args.query, args.k, args.lang)- res = {"hits": {"hits": hits}}- elif args.mode == "semantic":- capable, total = semantic_indices(query_prefix(state), fatal=True)- hits = semantic_search(capable, args.query, args.k, args.lang, fatal=True)- res = {"hits": {"hits": hits}}- note = (f"vector only over {len(capable)} of {total} index(es)" if capable- else f"no index under '{query_prefix(state)}*' maps `body` as semantic_text")- else:- res = search(query_prefix(state), args.query, args.k, args.lang)- hits = res.get("hits", {}).get("hits", [])-- # Say which arms ran, every time. A hybrid call that silently fell back to- # BM25 must not read like a hybrid result.- if note and not args.json:- print(f'@mode {note}' if args.meatl else f"[{note}]")-- if args.json:- # Empty results must remain machine-readable without turning a miss- # into a successful retrieval (the exit-code contract is unchanged).- print(json.dumps(res, indent=1))- if not hits:- sys.exit(1)- return-- if not hits:- # Say so explicitly. A silent miss makes the next agent re-run the same- # dead query; this is the line that stops the loop.- print(f'@no q="{args.query}" why=no-match-in-corpus' if args.meatl- else f"No passage in '{args.corpus}' matches: {args.query}\n"- f"The corpus is likely wrong for this task — fall back to "- f"normal work rather than forcing a bad match.")- sys.exit(1)-- licences = {}- man = os.path.join(ROOT, "corpora", args.corpus, "corpus.json")- if os.path.exists(man):- with open(man) as fh:- licences = {r["repo"]: r["licence"] for r in json.load(fh)["repos"]}-- for h in hits:- src = h.get("_source", {})- loc = provenance(src)- score = h.get("_score") or 0.0- repo = loc.split("/")[0] if "/" in loc else ""- lic = licences.get(repo, "")-- # An RRF score lives around 0.03 and two decimals would print every hit- # as "0.03". Show the arms that produced it instead — that is the part- # a reader can act on.- ranks = h.get("_rrf_ranks")- if ranks:- arms = ", ".join(f"{('bm25', 'vec')[li]} #{r}"- for li, r in sorted(ranks.items()))- shown = f"rrf {score:.4f} [{arms}]"- else:- shown = f"score {score:.2f}"-- if args.meatl:- print(f'@ok f={loc} {shown.replace(" ", "=", 1)}'- + (f' why={lic}' if lic else ""))- continue-- print(f"\n─── {loc} ({shown}{', ' + lic if lic else ''})")- if args.full:- body = str(src.get("body") or "")- # Prefer the matching DEFINITION over a byte window. Fall back to the- # window only when the record carries no usable symbols (a data file,- # or a language whose extractor found nothing — see issue #170).- sp = None if args.no_symbol else symbol_passage(body, src, args.query, args.full)- if sp:- text, label = sp- print(f" [{label} — {len(text):,} of {len(body):,} chars]")- print(text)- else:- window, start, total = best_window(body, args.query, args.full)- if total > len(window):- print(f" [no symbol match; showing {len(window):,} of {total:,} "- f"chars from offset {start:,}, window centred on the match]")- print(window)- else:- # Only reachable via `--full 0`. `highlight` is never requested- # (issue #177 — it reorders hits), so this is the file head and is- # labelled as such rather than passed off as a matching passage.- body = str(src.get("body") or "")- head = body[:400]- if len(body) > len(head):- print(f" [file head; {len(head):,} of {len(body):,} chars — "- f"pass --full N for the matching definition]")- print(" " + head.replace("\n", "\n "))- if lic and any(r in lic for r in RESTRICTED):- print(f" !! {lic}: adapt the APPROACH, do not copy the code")-- if not args.meatl:- print(f"\n{len(hits)} passages from '{args.corpus}'"- + (f" (index {age}d old)" if age else ""))- print("Cite file:line for anything you rely on.")-- # Stderr-only, once a day: the loop back to the maintainers. Kept out of the- # retrieval output on stdout on purpose (see field_report_nudge).- field_report_nudge()---if __name__ == "__main__":- main()diff --git a/tools/xerj-code/swebench/gen_predictions.py b/tools/xerj-code/swebench/gen_predictions.pyindex 21b0d232f..b42e4df53 100644--- a/tools/xerj-code/swebench/gen_predictions.py+++ b/tools/xerj-code/swebench/gen_predictions.py@@ -26,7 +26,6 @@ import argparse, json, os, subprocess, tempfile, shutil, sys, time, pathlibXERJ_URL = os.environ.get("XERJ_URL", "http://localhost:9200")XERJ_BIN = os.environ.get("XERJ_BIN", "xerj")-XC = os.path.join(os.path.dirname(__file__), "..", "scripts", "xc.py")def sh(cmd, cwd=None, timeout=None, env=None):@@ -49,8 +48,10 @@ def retrieve_context(repo_dir, instance_id, problem, k=6, chars=8000):return None, f"index-failed:{idx.returncode}:{idx.stderr[:160]}"# first ~3 lines of the issue make the best lexical query on the default embedderquery = " ".join(problem.split("\n")[:3])[:300]- r = sh(["python3", XC, prefix, query, "--k", str(k), "--chars", str(chars),- "--full"], env={"XERJ_URL": XERJ_URL})+ # `xerj code` (issue #977): same retrieval the xc.py wrapper used to do.+ # exit 1 == no match == no context injected; only 0 carries passages.+ r = sh([XERJ_BIN, "code", prefix, query, "-k", str(k),+ "--full", str(chars)], env={"XERJ_URL": XERJ_URL})if r.returncode != 0:return None, f"retrieve-failed:{r.returncode}:{r.stderr[:160]}"return r.stdout, Nonediff --git a/tools/xerj-code/tests/test_hybrid_fallback.py b/tools/xerj-code/tests/test_hybrid_fallback.pydeleted file mode 100644index 25d8ac396..000000000--- a/tools/xerj-code/tests/test_hybrid_fallback.py+++ /dev/null@@ -1,259 +0,0 @@-#!/usr/bin/env python3-"""Offline regressions for optional transport failures in hybrid retrieval."""-import contextlib-import http.client-import importlib.util-import io-import json-from pathlib import Path-import sys-import tempfile-import unittest-from unittest.mock import patch-import urllib.error---XC_PATH = Path(__file__).resolve().parents[1] / "scripts" / "xc.py"-PREFIX = "xc-fixture"-INDEX = PREFIX + "-1"---def hit(name, score):- return {"_index": INDEX, "_id": name, "_score": score,- "_source": {"path": f"fixture/{name}.rs",- "body": f"fn parse_{name}() {{}}"}}---BM25_HITS = [hit("alpha", 9.0), hit("beta", 7.0), hit("gamma", 5.0)]-VECTOR_HITS = [hit("beta", 0.9), hit("delta", 0.8)]--# A connection can fail while opening a request or while reading its body.-# These are concrete urllib/http.client failures, without network or timing.-FAILURES = (- ("url", lambda: urllib.error.URLError("fixture connection refused"), False),- ("timeout", lambda: TimeoutError("fixture read timed out"), True),- ("reset", lambda: ConnectionResetError("fixture connection reset"), True),- ("disconnect", lambda: http.client.RemoteDisconnected("fixture disconnect"), False),- ("incomplete", lambda: http.client.IncompleteRead(b'{"hits":', 10), True),-)---class BrokenResponse(io.BytesIO):- def __init__(self, failure):- super().__init__()- self.failure = failure-- def read(self, *args):- raise self.failure()---class Transport:- """Serve real request shapes; optionally fail one retrieval stage."""-- def __init__(self, stage=None, failure=None, during_read=False, bm25=None,- semantic_only=False, vector=None, capable=True):- self.stage = stage- self.failure = failure- self.during_read = during_read- self.bm25 = BM25_HITS if bm25 is None else bm25- self.vector = VECTOR_HITS if vector is None else vector- self.semantic_only = semantic_only- self.capable = capable- self.calls = []- self.mapping_calls = 0-- def __call__(self, req, timeout=None):- url = req.full_url- if "/_cat/indices/" in url:- stage, payload = "loaded", [{"index": INDEX}]- elif url.endswith("/_mapping"):- self.mapping_calls += 1- stage = "fields" if self.mapping_calls == 1 and not self.semantic_only else "mapping"- payload = {INDEX: {"mappings": {"properties": {- "body": {"type": "semantic_text" if self.capable else "text"},- "defs": {"type": "text"}, "title": {"type": "text"},- }}}}- elif url.endswith("/_search"):- body = json.loads(req.data)- stage = "vector" if "semantic" in body["query"] else "bm25"- payload = {"hits": {"hits": self.vector if stage == "vector" else self.bm25}}- else:- raise AssertionError(f"unexpected request: {url}")- self.calls.append(stage)- if stage == self.stage:- if self.during_read:- return BrokenResponse(self.failure)- raise self.failure()- return io.BytesIO(json.dumps(payload).encode())---class HybridFallbackTests(unittest.TestCase):- def setUp(self):- spec = importlib.util.spec_from_file_location("xc_hybrid_under_test", XC_PATH)- self.xc = importlib.util.module_from_spec(spec)- spec.loader.exec_module(self.xc)- self.home = tempfile.TemporaryDirectory(prefix="xc-hybrid-test-")- self.addCleanup(self.home.cleanup)-- def run_main(self, transport, flags=(), mode="hybrid"):- out, err = io.StringIO(), io.StringIO()- argv = ["xc.py", "fixture", "parse", "-k", "2", "--mode", mode, *flags]- state = {"corpus": "fixture", "prefix": PREFIX}- # Every patched process-global value is restored, including urllib and- # argv. A fresh field cache also keeps repeated subtests independent.- with patch.object(self.xc, "ROOT", self.home.name), \- patch.object(self.xc, "URL", "http://fixture.invalid"), \- patch.object(self.xc, "_FIELDS_CACHE", {}), \- patch.object(self.xc, "load_state", return_value=state), \- patch.object(self.xc, "field_report_nudge"), \- patch.object(self.xc.urllib.request, "urlopen", side_effect=transport), \- patch.object(sys, "argv", argv), \- contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):- code = 0- try:- self.xc.main()- except SystemExit as exc:- code = exc.code- return code, out.getvalue(), err.getvalue()-- def assert_fallback(self, transport, flags):- code, out, err = self.run_main(transport, flags)- self.assertEqual(code, 0, err)- self.assertEqual(err, "")- if "--json" in flags:- self.assertEqual(json.loads(out), {"hits": {"hits": BM25_HITS[:2]}})- else:- self.assertIn("BM25 only", out)- self.assertNotIn("hybrid RRF", out)- self.assertNotIn("no index under", out)- self.assertLess(out.index("fixture/alpha.rs"), out.index("fixture/beta.rs"))- self.assertNotIn("fixture/gamma.rs", out)- self.assertNotIn("fixture/delta.rs", out)- if "--meatl" in flags:- self.assertTrue(out.startswith("@mode BM25 only"))- self.assertEqual(out.count("@ok "), 2)-- def test_optional_transport_failures_keep_bm25_in_each_output_mode(self):- for stage in ("mapping", "vector"):- for name, failure, during_read in FAILURES:- for flags in ((), ("--json",), ("--meatl",)):- with self.subTest(stage=stage, failure=name, flags=flags):- transport = Transport(stage, failure, during_read)- self.assert_fallback(transport, flags)- self.assertEqual(transport.calls.count("bm25"), 1)- self.assertEqual(transport.calls.count("vector"), int(stage == "vector"))-- def test_optional_http_errors_still_fall_back(self):- for stage in ("mapping", "vector"):- with self.subTest(stage=stage):- def failure():- error = urllib.error.HTTPError(- "http://fixture.invalid", 503, "fixture unavailable", {}, io.BytesIO(b"offline"))- self.addCleanup(error.close)- return error- self.assert_fallback(Transport(stage, failure), ("--json",))-- def test_optional_http_error_with_unreadable_body_still_falls_back(self):- for name, read_failure, _ in (FAILURES[1], FAILURES[4]):- with self.subTest(failure=name):- def failure():- error = urllib.error.HTTPError(- "http://fixture.invalid", 503, "fixture unavailable", {},- BrokenResponse(read_failure))- self.addCleanup(error.close)- return error- self.assert_fallback(Transport("vector", failure), ("--json",))-- def test_primary_http_error_with_unreadable_body_is_still_fatal(self):- for mode in ("bm25", "hybrid", "semantic"):- for name, read_failure, _ in (FAILURES[1], FAILURES[4]):- with self.subTest(mode=mode, failure=name):- def failure():- error = urllib.error.HTTPError(- "http://fixture.invalid", 503, "fixture unavailable", {},- BrokenResponse(read_failure))- self.addCleanup(error.close)- return error- stage = "vector" if mode == "semantic" else "bm25"- transport = Transport(stage, failure, semantic_only=mode == "semantic")- code, out, err = self.run_main(transport, ("--json",), mode)- self.assertEqual((code, out), (2, ""))- self.assertIn("search failed (503)", err)-- def test_primary_transport_failures_are_fatal_without_results(self):- for mode in ("bm25", "hybrid"):- for name, failure, during_read in FAILURES:- with self.subTest(mode=mode, failure=name):- transport = Transport("bm25", failure, during_read)- code, out, err = self.run_main(transport, ("--json",), mode)- self.assertEqual(code, 2)- self.assertEqual(out, "")- self.assertIn("cannot reach XERJ", err)- self.assertNotIn("No passage", err)- self.assertNotIn("vector", transport.calls)-- def test_successful_hybrid_fuses_ranks_and_caps_results(self):- transport = Transport()- code, out, err = self.run_main(transport, ("--json",))- self.assertEqual((code, err), (0, ""))- hits = json.loads(out)["hits"]["hits"]- self.assertEqual([h["_id"] for h in hits], ["beta", "alpha"])- self.assertAlmostEqual(hits[0]["_score"], 1 / 62 + 1 / 61)- self.assertEqual(hits[0]["_rrf_ranks"], {"0": 2, "1": 1})- self.assertEqual(hits[0]["_source"], BM25_HITS[1]["_source"])- self.assertEqual(transport.calls, ["loaded", "fields", "bm25", "mapping", "vector"])-- def test_empty_bm25_never_attempts_optional_retrieval(self):- transport = Transport(bm25=[])- code, out, err = self.run_main(transport)- self.assertEqual((code, err), (1, ""))- self.assertIn("No passage", out)- self.assertEqual(transport.calls, ["loaded", "fields", "bm25"])-- def assert_semantic_failure(self, transport, flags):- code, out, err = self.run_main(transport, flags, mode="semantic")- self.assertEqual(code, 2, (out, err))- self.assertEqual(out, "")- self.assertIn("xc:", err)- self.assertNotIn("No passage", err)- self.assertNotIn("bm25", transport.calls)-- def test_standalone_semantic_transport_failures_are_fatal(self):- for stage in ("mapping", "vector"):- for name, failure, during_read in FAILURES:- for flags in ((), ("--json",)):- with self.subTest(stage=stage, failure=name, flags=flags):- transport = Transport(stage, failure, during_read, semantic_only=True)- self.assert_semantic_failure(transport, flags)-- def test_standalone_semantic_http_errors_are_fatal(self):- for stage in ("mapping", "vector"):- for flags in ((), ("--json",)):- with self.subTest(stage=stage, flags=flags):- def failure():- error = urllib.error.HTTPError(- "http://fixture.invalid", 503, "fixture unavailable", {}, io.BytesIO(b"offline"))- self.addCleanup(error.close)- return error- self.assert_semantic_failure(Transport(stage, failure, semantic_only=True), flags)-- def test_successful_standalone_semantic_preserves_vector_hits(self):- transport = Transport(semantic_only=True)- code, out, err = self.run_main(transport, ("--json",), mode="semantic")- self.assertEqual((code, err), (0, ""))- self.assertEqual(json.loads(out), {"hits": {"hits": VECTOR_HITS}})- self.assertEqual(transport.calls, ["loaded", "mapping", "vector"])-- def test_standalone_semantic_genuine_misses_keep_exit_one(self):- for capable in (False, True):- with self.subTest(capable=capable):- transport = Transport(semantic_only=True, capable=capable, vector=[])- code, out, err = self.run_main(transport, mode="semantic")- self.assertEqual((code, err), (1, ""))- self.assertIn("No passage", out)- expected = ["loaded", "mapping"] + (["vector"] if capable else [])- self.assertEqual(transport.calls, expected)---if __name__ == "__main__":- unittest.main()diff --git a/tools/xerj-code/tests/test_passage_window.py b/tools/xerj-code/tests/test_passage_window.pydeleted file mode 100644index 2a1c482e3..000000000--- a/tools/xerj-code/tests/test_passage_window.py+++ /dev/null@@ -1,137 +0,0 @@-#!/usr/bin/env python3-"""Offline regressions for preserving query evidence in xc.py excerpts."""-import importlib.util-import io-import json-import os-from pathlib import Path-import sys-import tempfile-import unittest-from contextlib import redirect_stderr, redirect_stdout-from unittest.mock import patch---XC_PATH = Path(__file__).resolve().parents[1] / "scripts" / "xc.py"-SPEC = importlib.util.spec_from_file_location("xc_passage_under_test", XC_PATH)-xc = importlib.util.module_from_spec(SPEC)-SPEC.loader.exec_module(xc)---def tail_match_body():- # The only match fits in the first 800 characters, but its newline does not.- return ("padding 123456789012\n" * 37- + "needle(); more_source_text_here();\n"- + "// trailing text\n" * 30)---class PassageWindowTests(unittest.TestCase):- def window(self, body, query="needle", width=800):- text, start, total = xc.best_window(body, query, width)- self.assertEqual(total, len(body))- self.assertGreaterEqual(start, 0)- self.assertLessEqual(len(text), width)- self.assertEqual(text, body[start:start + len(text)])- return text, start-- def test_end_snap_keeps_the_matching_partial_line(self):- text, _ = self.window(tail_match_body())- self.assertIn("needle", text)-- def test_start_snap_does_not_jump_back_over_a_long_line(self):- body = "// header\n" + "x" * 1500 + "needle" + "x" * 500- text, _ = self.window(body)- self.assertIn("needle", text)-- def test_alignment_preserves_all_selected_query_occurrences(self):- body = ("needle\n" + "padding 123456789012\n" * 36- + "padding abcde\nneedle(); more_source_text_here();\n"- + "// trailing text\n" * 30)- self.assertEqual(body[:800].count("needle"), 2)- text, _ = self.window(body)- self.assertEqual(text.count("needle"), 2)-- def test_lowercase_expansion_keeps_source_offsets(self):- # U+0130 lowercases to two code points; source offsets must not shift.- body = "\u0130" * 900 + "needle" + "x" * 1500- text, _ = self.window(body)- self.assertIn("needle", text)-- def test_readable_line_boundaries_when_the_match_is_preserved(self):- body = "// padding line\n" * 70 + "needle();\n" + "// tail\n" * 100- text, start = self.window(body)- self.assertIn("needle", text)- self.assertTrue(start == 0 or body[start - 1] == "\n")- self.assertTrue(start + len(text) == len(body)- or body[start + len(text)] == "\n")-- def test_equal_scores_keep_the_first_candidate(self):- body = "needle" + "x" * 1600 + "needle" + "x" * 1000- text, start = self.window(body)- self.assertEqual(start, 0)- self.assertEqual(text, body[:800])-- def test_empty_and_short_bodies_are_returned_unchanged(self):- for body in ("", "needle();\n", "x" * 800):- with self.subTest(length=len(body)):- self.assertEqual(self.window(body), (body, 0))-- def test_no_terms_and_no_matches_keep_the_head_fallback(self):- body = "// plain source\n" * 100- for query in ("", "$-1", "needle"):- with self.subTest(query=query):- self.assertEqual(self.window(body, query), (body[:800], 0))-- def test_custom_width_preserves_a_match_within_the_budget(self):- body = "padding\n" * 3 + "needle(); more_source();\n" + "tail\n" * 30- text, _ = self.window(body, width=32)- self.assertIn("needle", text)-- def test_cli_emits_the_matching_source_with_and_without_symbols(self):- body = tail_match_body()- # Exercise the real argument parsing, HTTP request handling, and output- # formatter without a live XERJ or changes to the user's corpus state.- with tempfile.TemporaryDirectory(prefix="xc-passage-test-") as home:- state = Path(home) / "state"- state.mkdir()- (state / "fixture.json").write_text(json.dumps({- "corpus": "fixture", "prefix": "xc-fixture",- }), encoding="utf-8")- for extra in ([], ["--no-symbol"]):- with self.subTest(extra=extra):- source = {"path": "acme/source.txt", "body": body}- if extra:- source["symbols"] = [- {"name": "needle", "kind": "fn", "line": 38},- ]-- def urlopen(req, timeout=None):- if "/_cat/indices/" in req.full_url:- payload = [{"index": "xc-fixture-1"}]- elif req.full_url.endswith("/_mapping"):- payload = {"xc-fixture-1": {"mappings": {- "properties": {"body": {"type": "text"}},- }}}- elif req.full_url.endswith("/_search"):- payload = {"hits": {"hits": [{- "_source": source, "_score": 1.0,- }]}}- else:- self.fail(f"unexpected request: {req.full_url}")- return io.BytesIO(json.dumps(payload).encode())-- out, err = io.StringIO(), io.StringIO()- with (patch.object(xc, "ROOT", home),- patch.dict(xc._FIELDS_CACHE, {}, clear=True),- patch.dict(os.environ, {"XERJ_CODE_NO_NUDGE": "1"}),- patch.object(xc.urllib.request, "urlopen", urlopen),- patch.object(sys, "argv", ["xc.py", "fixture", "needle"] + extra),- redirect_stdout(out), redirect_stderr(err)):- xc.main()- self.assertIn("needle", out.getvalue())- self.assertIn("1 passages from 'fixture'", out.getvalue())- self.assertEqual(err.getvalue(), "")---if __name__ == "__main__":- unittest.main()diff --git a/tools/xerj-code/tests/test_state_ledger.py b/tools/xerj-code/tests/test_state_ledger.pydeleted file mode 100755index 845e9bc95..000000000--- a/tools/xerj-code/tests/test_state_ledger.py+++ /dev/null@@ -1,303 +0,0 @@-#!/usr/bin/env python3-"""Regression tests for the state-ledger guard in xc.py.--The bug (dogfood 2026-08-18): a corpus can be listed in `state/` while having-ZERO live indices on the server xc.py is querying — it was indexed against a-different data dir / node. Before this guard, querying such a corpus returned-the SAME "No passage matches — corpus is likely wrong, fall back" message as a-genuinely bad query, so an agent concluded "no reference exists" and started-guessing: the exact failure reference-coding exists to prevent.--These tests pin the three outcomes, distinguishing them by exit code AND by-message, with the HTTP layer (urllib) mocked so no live server is needed:-- 1. in state/ but 0 live indices -> exit 3, DISTINCT "not loaded here" error- 2. loaded, query matches nothing -> exit 1, ordinary "No passage ... matches"- 3. loaded, query matches -> exit 0, normal answer with provenance--Offline by design: XERJ_CODE_HOME points at a throwaway dir and urlopen is-replaced, so nothing touches the network or the real ~/.xerj-code.-"""-import importlib.util-import io-import json-import os-import sys-import tempfile-import urllib.error-from contextlib import redirect_stderr, redirect_stdout-from datetime import datetime, timezone--HERE = os.path.dirname(os.path.abspath(__file__))-XC_PATH = os.path.join(HERE, "..", "scripts", "xc.py")--PREFIX = "xc-fixture"-CORPUS = "fixture"-# Every URL the mocked urlopen was asked for, so a test can assert on WHICH-# indices a query addressed, not only on what came back.-SEEN_URLS = []---class FakeResp:- """Minimal context-manager response json.load() can read."""- def __init__(self, payload):- self._data = json.dumps(payload).encode()-- def read(self, *a):- return self._data-- def __enter__(self):- return self-- def __exit__(self, *a):- return False---def make_urlopen(indices, search_hits):- """A urlopen stand-in dispatching on the request URL.-- `indices` is the list _cat/indices returns (its length is the live count).- `search_hits` is the hits array _search returns.- """- def fake_urlopen(req, timeout=None):- url = req.full_url if hasattr(req, "full_url") else str(req)- SEEN_URLS.append(url)- if "/_cat/indices/" in url:- return FakeResp(indices)- if "/_mapping" in url:- # One index, mapping `body`+`defs`+`title` so resolve_fields keeps- # the multi-field query and semantic_indices finds no semantic_text.- return FakeResp({- f"{PREFIX}-1": {"mappings": {"properties": {- "body": {"type": "text"},- "defs": {"type": "text"},- "title": {"type": "text"},- }}}- })- if "/_search" in url:- return FakeResp({"hits": {"total": {"value": len(search_hits)},- "hits": search_hits}})- raise urllib.error.URLError(f"unexpected url in test: {url}")- return fake_urlopen---def load_xc():- """Import xc.py fresh so module-level ROOT/URL pick up the test env."""- for m in [k for k in sys.modules if k == "xc_under_test"]:- del sys.modules[m]- spec = importlib.util.spec_from_file_location("xc_under_test", XC_PATH)- mod = importlib.util.module_from_spec(spec)- spec.loader.exec_module(mod)- return mod---def write_state(home):- os.makedirs(os.path.join(home, "state"), exist_ok=True)- os.makedirs(os.path.join(home, "corpora", CORPUS), exist_ok=True)- now = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")- with open(os.path.join(home, "state", f"{CORPUS}.json"), "w") as fh:- json.dump({"corpus": CORPUS, "indexed_at": now, "prefix": PREFIX,- "url": "http://localhost:9999"}, fh)- with open(os.path.join(home, "corpora", CORPUS, "corpus.json"), "w") as fh:- json.dump({"repos": [{"repo": "acme", "licence": "MIT"}]}, fh)---def run_query(mod, indices, search_hits, argv):- """Run xc.main() with urlopen mocked; return (exit_code, stdout, stderr)."""- mod.urllib.request.urlopen = make_urlopen(indices, search_hits)- out, err = io.StringIO(), io.StringIO()- code = 0- saved = sys.argv- sys.argv = ["xc.py"] + argv- try:- with redirect_stdout(out), redirect_stderr(err):- mod.main()- except SystemExit as e:- code = e.code if isinstance(e.code, int) else 1- finally:- sys.argv = saved- return code, out.getvalue(), err.getvalue()---def main():- passed = failed = 0-- def check(name, cond, detail=""):- nonlocal passed, failed- if cond:- passed += 1- print(f" ok — {name}")- else:- failed += 1- print(f" FAIL — {name} {detail}")-- home = tempfile.mkdtemp(prefix="xc-ledger-test-")- os.environ["XERJ_CODE_HOME"] = home- os.environ["XERJ_URL"] = "http://localhost:9200"- write_state(home)- mod = load_xc()-- HIT = [{"_index": f"{PREFIX}-1", "_id": "d1", "_score": 12.3,- "_source": {"body": "fn parse_two_way() { /* the algorithm */ }",- "path": "acme/src/lib.rs", "line": 42,- "symbols": [{"name": "parse_two_way", "kind": "fn",- "line": 1}]}}]-- # Case 1: in state/ but ZERO live indices -> distinct "not loaded here".- code, out, err = run_query(mod, indices=[], search_hits=[],- argv=[CORPUS, "two way string search"])- blob = out + err- check("case1 exit code is 3 (distinct, not 1)", code == 3, f"got {code}")- check("case1 message says 0 live indices", "0 live" in blob, repr(blob))- check("case1 message is explicitly NOT a no-match",- "NOT a 'no match'" in blob, repr(blob))- check("case1 does NOT emit the ordinary no-match line",- "No passage in" not in blob, repr(blob))- check("case1 is actionable (re-run xc-index.sh)",- "xc-index.sh" in blob, repr(blob))-- # Case 2: loaded (1 index) but the query matches nothing -> ordinary miss.- code, out, err = run_query(mod, indices=[{"index": f"{PREFIX}-1"}],- search_hits=[],- argv=[CORPUS, "nonexistent xyzzy plugh"])- blob = out + err- check("case2 exit code is 1 (ordinary empty-result)", code == 1, f"got {code}")- check("case2 uses the no-match wording", "No passage in" in blob, repr(blob))- check("case2 does NOT claim the corpus is unloaded",- "0 live" not in blob and "not loaded" not in blob, repr(blob))-- # Case 3: loaded and the query matches -> normal answer with provenance.- code, out, err = run_query(mod, indices=[{"index": f"{PREFIX}-1"}],- search_hits=HIT,- argv=[CORPUS, "two way parse_two_way"])- blob = out + err- check("case3 exit code is 0 (success)", code == 0, f"got {code}")- check("case3 shows provenance file:line", "acme/src/lib.rs:42" in blob,- repr(blob))- check("case3 shows the retrieved definition",- "parse_two_way" in blob, repr(blob))-- # Case 4: --list distinguishes loaded from not-loaded per entry.- code, out, err = run_query(mod, indices=[], search_hits=[], argv=["--list"])- blob = out + err- check("list exit code is 0", code == 0, f"got {code}")- check("list flags the fixture as NOT loaded",- "NOT loaded here" in blob, repr(blob))-- # Case 5 (#930): a rebuilt corpus records the ONE verified build in- # `index_prefix`. xc.py must address that build, not the whole `xc-<corpus>`- # namespace — during `xc-index.sh --fresh` the namespace also holds the- # half-built replacement (or a retired build whose delete failed), and- # querying it would return every passage twice or from a partial index.- build = f"{PREFIX}-b20260918101500"- state_path = os.path.join(home, "state", f"{CORPUS}.json")- with open(state_path) as fh:- rebuilt = json.load(fh)- rebuilt.update({"build": "b20260918101500", "index_prefix": build})- with open(state_path, "w") as fh:- json.dump(rebuilt, fh)- del SEEN_URLS[:]- code, out, err = run_query(mod, indices=[{"index": f"{build}-1"}],- search_hits=HIT,- argv=[CORPUS, "two way parse_two_way"])- addressed = [u for u in SEEN_URLS if "/_cat/indices/" in u or "/_search" in u]- check("case5 exit code is 0", code == 0, f"got {code} {out + err!r}")- check("case5 state `prefix` is still the whole namespace",- rebuilt["prefix"] == PREFIX)- check("case5 every index-addressing request names the verified build",- bool(addressed) and all(f"/{build}*" in u for u in addressed),- repr(addressed))- check("case5 no request addresses the bare namespace glob",- not any(f"/{PREFIX}*" in u for u in addressed), repr(addressed))-- # Case 6: xc-index.sh keeps a build whose autoindex run did not finish when- # the alternative is no corpus at all, and records `salvaged` and the exit- # code. The reader must be TOLD: a miss against a half-built index is not- # evidence of absence. On stderr, so `--json` stdout stays parseable.- with open(state_path) as fh:- partial = json.load(fh)- partial.update({"autoindex_exit": 1, "salvaged": True})- with open(state_path, "w") as fh:- json.dump(partial, fh)- live = [{"index": f"{build}-1"}]- code, out, err = run_query(mod, indices=live, search_hits=HIT,- argv=[CORPUS, "two way parse_two_way"])- check("case6 a salvaged index still answers (exit 0)", code == 0,- f"got {code} {out + err!r}")- check("case6 the reader is told coverage is incomplete",- "INCOMPLETE" in err and "autoindex exit 1, kept unverified" in err, repr(err))- check("case6 the warning names the command that resumes it",- f"xc-index.sh {CORPUS}" in err, repr(err))- check("case6 the warning is not on stdout", "INCOMPLETE" not in out, repr(out))- code, out, err = run_query(mod, indices=live, search_hits=HIT,- argv=[CORPUS, "two way parse_two_way", "--json"])- try:- json.loads(out)- parseable = True- except ValueError:- parseable = False- check("case6 --json stdout is still one JSON document", parseable, repr(out))- check("case6 --json still warns on stderr", "INCOMPLETE" in err, repr(err))- code, out, err = run_query(mod, indices=live, search_hits=[], argv=["--list"])- check("case6 --list marks the corpus INCOMPLETE",- "INCOMPLETE (autoindex exit 1)" in out + err, repr(out + err))-- # A finished run says nothing: exit 3 is completed-with-junk, not partial.- partial.update({"autoindex_exit": 3, "salvaged": False})- with open(state_path, "w") as fh:- json.dump(partial, fh)- code, out, err = run_query(mod, indices=live, search_hits=HIT,- argv=[CORPUS, "two way parse_two_way"])- check("case6 exit 3 (completed with junk) is not reported as incomplete",- code == 0 and "INCOMPLETE" not in out + err, repr(out + err))-- # --json must be parseable for a genuine miss as well as a match. Keep the- # existing exit codes and the raw response (including BM25 metadata).- for mode, extra in (("bm25", []), ("hybrid", []), ("semantic", []),- ("bm25", ["--meatl"])):- label = mode + (" +meatl" if extra else "")- code, out, err = run_query(- mod, indices=[{"index": f"{PREFIX}-1"}], search_hits=[],- argv=[CORPUS, "nonexistent xyzzy plugh", "--json", "--mode", mode]- + extra)- expected = {"hits": {"hits": []}}- if mode == "bm25":- expected["hits"]["total"] = {"value": 0}- try:- payload = json.loads(out)- except ValueError:- payload = None- check(f"json {label} miss keeps exit code 1", code == 1, f"got {code}")- check(f"json {label} miss emits the empty response",- payload == expected, repr(out))- check(f"json {label} miss has no stderr", err == "", repr(err))-- code, out, err = run_query(- mod, indices=[{"index": f"{PREFIX}-1"}], search_hits=HIT,- argv=[CORPUS, "two way parse_two_way", "--json"])- check("json match keeps exit code 0", code == 0, f"got {code}")- check("json match preserves the raw response",- json.loads(out) == {"hits": {"total": {"value": 1}, "hits": HIT}},- repr(out))-- code, out, err = run_query(mod, indices=[], search_hits=[],- argv=[CORPUS, "two way string search", "--json"])- check("json unloaded corpus keeps exit code 3", code == 3, f"got {code}")- check("json unloaded corpus has no search response", out == "", repr(out))- check("json unloaded corpus keeps its actionable stderr",- "0 live indices" in err and "xc-index.sh" in err, repr(err))-- code, out, err = run_query(- mod, indices=[{"index": f"{PREFIX}-1"}], search_hits=[],- argv=[CORPUS, "nonexistent xyzzy plugh", "--meatl"])- check("meatl miss keeps exit code 1", code == 1, f"got {code}")- check("meatl miss keeps its no-match record",- out == '@no q="nonexistent xyzzy plugh" why=no-match-in-corpus\n',- repr(out))-- print(f"\n{passed} passed, {failed} failed")- sys.exit(1 if failed else 0)---if __name__ == "__main__":- main()diff --git a/tools/xerj-code/tests/test_xc_corpus.sh b/tools/xerj-code/tests/test_xc_corpus.shdeleted file mode 100755index bcbb0108e..000000000--- a/tools/xerj-code/tests/test_xc_corpus.sh+++ /dev/null@@ -1,340 +0,0 @@-#!/usr/bin/env bash-# Regression tests for xc-corpus.sh — the manifest round-trip (issue #319).-#-# A corpus manifest is only shareable if it can rebuild the corpus it describes.-# These tests pin that contract: full SHAs go in, the same bytes come back out,-# on a machine that has never seen the corpus.-#-# Offline by design. Fixtures are local git repositories served over file://,-# so nothing here touches the network or the real ~/.xerj-code.-set -uo pipefail--HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"-XC_CORPUS="$HERE/../scripts/xc-corpus.sh"--pass=0; fail=0-ok() { pass=$((pass+1)); echo " ok — $1"; }-bad() { fail=$((fail+1)); echo " FAIL — $1"; }-check() { if [ "$2" = "$3" ]; then ok "$1"; else bad "$1: expected '$3', got '$2'"; fi; }--TMP="$(mktemp -d)"-trap 'rm -rf "$TMP"' EXIT--# Fixture: a repo with two commits, so "pinned to the parent" is distinguishable-# from "whatever HEAD happens to be". uploadpack.allowAnySHA1InWant mirrors what-# github.com already permits — the issue verified fetch-by-full-SHA against it.-make_repo() {- local dir="$TMP/remote/$1" body="$2"- mkdir -p "$dir"- git -C "$dir" init -q -b main- git -C "$dir" config user.email [email protected]- git -C "$dir" config user.name test- git -C "$dir" config uploadpack.allowAnySHA1InWant true- printf 'MIT License\n\nPermission is hereby granted, free of charge, ...\n' > "$dir/LICENSE"- printf '%s\n' "$body" > "$dir/lib.rs"- git -C "$dir" add -A && git -C "$dir" commit -qm one- printf 'fn added_after_the_pin() {}\n' >> "$dir/lib.rs"- git -C "$dir" add -A && git -C "$dir" commit -qm two-}--# Every invocation gets its own XERJ_CODE_HOME so tests cannot leak into each-# other, and can never write to the developer's real corpora.-xc() {- local home="$1"; shift- XERJ_CODE_HOME="$home" "$XC_CORPUS" "$@" >"$TMP/out.log" 2>&1-}--make_repo alpha 'fn alpha() {}'-make_repo beta 'fn beta() {}'-ALPHA_URL="file://$TMP/remote/alpha"-BETA_URL="file://$TMP/remote/beta"-ALPHA_TIP="$(git -C "$TMP/remote/alpha" rev-parse HEAD)"-ALPHA_PIN="$(git -C "$TMP/remote/alpha" rev-parse HEAD~1)"--echo "test_xc_corpus.sh"--# ----------------------------------------------------------------------------# 1. The manifest records a FULL 40-char SHA.-#-# `git rev-parse --short HEAD` produced a 7-char abbreviation, which no remote-# will serve: `git fetch --depth 1 origin e449d17` fails with "couldn't find-# remote ref". A manifest that cannot be fetched from cannot rebuild anything.-# ----------------------------------------------------------------------------H1="$TMP/home1"-if xc "$H1" demo "$ALPHA_URL" "$BETA_URL"; then- M="$H1/corpora/demo/corpus.json"- sha="$(grep -o '"repo":"alpha"[^}]*"sha":"[0-9a-f]*"' "$M" | grep -o '"sha":"[0-9a-f]*"' | cut -d'"' -f4)"- check "manifest records a 40-char sha" "${#sha}" "40"- check "manifest sha is the cloned commit" "$sha" "$ALPHA_TIP"-else- bad "clone-by-url failed"; cat "$TMP/out.log"-fi--# ----------------------------------------------------------------------------# 2. `--from <manifest>` rebuilds the corpus on a fresh machine, at the pinned-# SHA — not at the remote's current tip. Same manifest in, same bytes out.-# ----------------------------------------------------------------------------cat > "$TMP/pinned.json" <<EOF-{"corpus":"pinned","cloned_at":"2026-08-12T00:00:00Z","repos":[- {"repo":"alpha","url":"$ALPHA_URL","licence":"MIT","sha":"$ALPHA_PIN","files":2,"bytes":0},- {"repo":"beta","url":"$BETA_URL","licence":"MIT","sha":"$(git -C "$TMP/remote/beta" rev-parse HEAD)","files":2,"bytes":0}-]}-EOF--H2="$TMP/home2"-if xc "$H2" --from "$TMP/pinned.json"; then- got="$(git -C "$H2/corpora/pinned/alpha" rev-parse HEAD 2>/dev/null || echo MISSING)"- check "--from checks out the pinned sha, not the tip" "$got" "$ALPHA_PIN"- # The pinned commit predates the second commit, so the marker must be absent.- if grep -q added_after_the_pin "$H2/corpora/pinned/alpha/lib.rs" 2>/dev/null; then- bad "--from produced tip content at a pinned sha"- else- ok "--from produced the pinned working tree"- fi- check "--from rebuilt every repo in the manifest" \- "$(git -C "$H2/corpora/pinned/beta" rev-parse HEAD 2>/dev/null || echo MISSING)" \- "$(git -C "$TMP/remote/beta" rev-parse HEAD)"-else- bad "--from <manifest> failed"; sed 's/^/ /' "$TMP/out.log"-fi--# ----------------------------------------------------------------------------# 3. An existing clone is MOVED to the recorded SHA, not silently skipped.-#-# Old behaviour printed "[skip] alpha already cloned" and left whatever was on-# disk — so re-running against a shared manifest gave two people different code.-# ----------------------------------------------------------------------------H3="$TMP/home3"-mkdir -p "$H3/corpora/pinned"-git clone -q "$TMP/remote/alpha" "$H3/corpora/pinned/alpha"-if xc "$H3" --from "$TMP/pinned.json"; then- check "existing clone is moved to the pinned sha" \- "$(git -C "$H3/corpora/pinned/alpha" rev-parse HEAD)" "$ALPHA_PIN"-else- bad "--from over an existing clone failed"; sed 's/^/ /' "$TMP/out.log"-fi--# ----------------------------------------------------------------------------# 4. Round trip: build from URLs, then rebuild elsewhere from the manifest that-# build produced. This is the actual shareability claim.-# ----------------------------------------------------------------------------H4="$TMP/home4"-if xc "$H4" --from "$H1/corpora/demo/corpus.json"; then- check "round-trip reproduces the recorded sha" \- "$(git -C "$H4/corpora/demo/alpha" rev-parse HEAD 2>/dev/null || echo MISSING)" \- "$ALPHA_TIP"-else- bad "round-trip rebuild from a generated manifest failed"; sed 's/^/ /' "$TMP/out.log"-fi--# ----------------------------------------------------------------------------# 5. A manifest whose SHA is short (every manifest written before this change)-# must fail loudly rather than silently rebuild at the tip.-# ----------------------------------------------------------------------------sed "s/$ALPHA_PIN/${ALPHA_PIN:0:7}/" "$TMP/pinned.json" > "$TMP/legacy.json"-H5="$TMP/home5"-if xc "$H5" --from "$TMP/legacy.json"; then- bad "short-sha manifest was accepted"-else- if grep -qi 'sha' "$TMP/out.log"; then- ok "short-sha manifest is rejected with a sha-specific error"- else- bad "short-sha manifest rejected, but the error never mentions the sha"- fi-fi--# ----------------------------------------------------------------------------# 6. Licence detection. A manifest published under the project's name carries a-# licence column, so a misread is a legal problem, not a cosmetic one. Both-# cases below are real corpus repos the detector got wrong.-# ----------------------------------------------------------------------------# shellcheck disable=SC1090-source <(sed -n '/^detect_licence()/,/^}/p;/^classify_one()/,/^}/p;/^classify_text()/,/^}/p' "$XC_CORPUS")--LIC="$TMP/lic"; mkdir -p "$LIC/mpl" "$LIC/es" "$LIC/qw" "$LIC/dual"--# MPL-2.0 names the GNU GPL inside its own definitions ("Secondary License"),-# so restrictive-first body matching read sonic's plain MPL file as GPL.-cat > "$LIC/mpl/LICENSE.md" <<'EOF'-Mozilla Public License Version 2.0-==================================--1. Definitions-----------------1.12. "Secondary License"- means either the GNU General Public License, Version 2.0, the GNU Lesser- General Public License, Version 2.1, or the GNU Affero General Public- License, Version 3.0.-EOF-check "MPL-2.0 is not read as GPL" "$(detect_licence "$LIC/mpl")" "MPL-2.0"--# The one that must never regress in the permissive direction.-cat > "$LIC/es/LICENSE.txt" <<'EOF'-Source code in this repository is covered by (i) a triple license under the-"GNU Affero General Public License v3.0 only", "the Server Side Public License,-v 1", and the "Elastic License 2.0" or (ii) an "Apache License 2.0" compatible-license.-EOF-check "triple-licensed source is read as AGPL, not Apache" "$(detect_licence "$LIC/es")" "AGPL"--# LICENSE-3rdparty.csv is an inventory of DEPENDENCY licences (quickwit); it-# used to add a spurious UNKNOWN arm to a plain Apache-2.0 repo.-printf 'Apache License\nVersion 2.0, January 2004\n' > "$LIC/qw/LICENSE"-printf 'Component,Origin,License\nfoo,https://example.invalid,MIT OR Apache-2.0\n' > "$LIC/qw/LICENSE-3rdparty.csv"-check "third-party inventories are not classified" "$(detect_licence "$LIC/qw")" "Apache-2.0"--# Dual licensing is reported as both, never collapsed to one.-printf 'Apache License\nVersion 2.0, January 2004\n' > "$LIC/dual/LICENSE-APACHE"-printf 'MIT License\n\nPermission is hereby granted, free of charge, ...\n' > "$LIC/dual/LICENSE-MIT"-check "dual licence is reported as both" "$(detect_licence "$LIC/dual")" "Apache-2.0/MIT"--# An empty LICENSE is a degenerate but real case (a placeholder committed before-# the text). grep exits 1 on it, and under `set -eo pipefail` that used to take-# the whole script down mid-corpus instead of recording UNKNOWN.-mkdir -p "$LIC/empty"; : > "$LIC/empty/LICENSE"-check "an empty licence file does not abort the run" "$(detect_licence "$LIC/empty")" "UNKNOWN"--# ----------------------------------------------------------------------------# 7. The vetted manifests shipped in hub/ are well-formed and reviewable.-# ----------------------------------------------------------------------------for m in "$HERE"/../hub/*.json; do- [ -f "$m" ] || continue- n="$(basename "$m")"- if python3 "$HERE/validate_manifest.py" --hub "$m" 2>"$TMP/hub.err"; then- ok "hub/$n is a valid, fully pinned, human-reviewed manifest"- else- bad "hub/$n: $(tr '\n' ';' < "$TMP/hub.err")"- fi-done--# The validator itself has to reject what it claims to catch, or the hub check-# above is decoration.-cat > "$TMP/bad.json" <<'EOF'-{"corpus":"bad","repos":[{"repo":"x","url":"https://example.invalid/x","licence":"MIT","sha":"e449d17"}]}-EOF-if python3 "$HERE/validate_manifest.py" "$TMP/bad.json" 2>/dev/null; then- bad "validate_manifest.py accepted a short sha"-else- ok "validate_manifest.py rejects a short sha"-fi--# ----------------------------------------------------------------------------# 8. A manifest is UNTRUSTED INPUT — `--from` exists to run files other people-# wrote. `repo` becomes a path that is force-checked-out and `clean -fd`ed,-# so a traversing name must be refused before any of that happens.-#-# Verified reachable before the guard: a manifest with-# repo="../../../victim" moved an unrelated git checkout to the manifest's-# commit, deleted its uncommitted changes and its untracked files, and-# rewrote its `origin` remote.-# ----------------------------------------------------------------------------VICTIM="$TMP/victim"-mkdir -p "$VICTIM"-git -C "$VICTIM" init -q -b main-git -C "$VICTIM" config user.email [email protected]-git -C "$VICTIM" config user.name test-git -C "$VICTIM" remote add origin https://example.invalid/untouched-printf 'committed\n' > "$VICTIM/tracked.txt"-git -C "$VICTIM" add -A && git -C "$VICTIM" commit -qm base-printf 'uncommitted work\n' >> "$VICTIM/tracked.txt"-printf 'untracked\n' > "$VICTIM/untracked.txt"--# home6/corpora/<name> is three levels below $TMP, so ../../../victim lands on it.-cat > "$TMP/traversal.json" <<EOF-{"corpus":"trav","cloned_at":"2026-08-12T00:00:00Z","repos":[- {"repo":"../../../victim","url":"$ALPHA_URL","licence":"MIT","sha":"$ALPHA_PIN","files":2,"bytes":0}-]}-EOF-H6="$TMP/home6"-if xc "$H6" --from "$TMP/traversal.json"; then- bad "a traversing repo name was accepted"-else- ok "a traversing repo name is rejected"-fi-check "traversal did not touch the victim's working tree" \- "$(cat "$VICTIM/tracked.txt" 2>/dev/null)" "$(printf 'committed\nuncommitted work')"-check "traversal did not delete the victim's untracked files" \- "$([ -f "$VICTIM/untracked.txt" ] && echo present || echo GONE)" "present"-check "traversal did not rewrite the victim's origin remote" \- "$(git -C "$VICTIM" remote get-url origin)" "https://example.invalid/untouched"--cat > "$TMP/trav-hub.json" <<'EOF'-{"corpus":"trav-hub","repos":[{"repo":"../evil","url":"https://example.invalid/x","licence":"MIT",- "sha":"0000000000000000000000000000000000000000",- "review":{"spdx":"MIT","use":"approach-only","by":"t","at":"2026-08-12"}}]}-EOF-if python3 "$HERE/validate_manifest.py" "$TMP/trav-hub.json" 2>/dev/null; then- bad "validate_manifest.py accepted a traversing repo name"-else- ok "validate_manifest.py rejects a traversing repo name"-fi--# ----------------------------------------------------------------------------# 9. xc-index.sh must not accept an instruction and drop it. `--frsh` used to-# set no flag and exit 0, running an INCREMENTAL index — and autoindex's-# incremental state makes that skip every file, leaving a corpus that-# retrieves nothing with no error anywhere.-# ----------------------------------------------------------------------------XC_INDEX="$HERE/../scripts/xc-index.sh"-mkdir -p "$TMP/home7/corpora/demo"-if XERJ_CODE_HOME="$TMP/home7" "$XC_INDEX" demo --frsh >"$TMP/idx.log" 2>&1; then- bad "xc-index.sh accepted an unknown argument"-elif grep -q "unknown argument '--frsh'" "$TMP/idx.log"; then- ok "xc-index.sh rejects an unknown argument by name"-else- bad "xc-index.sh rejected '--frsh' but never named it: $(tr '\n' ';' < "$TMP/idx.log")"-fi--# ----------------------------------------------------------------------------# 10. xc.py warns on every licence xc-corpus.sh warns about. The retrieval tool-# is where an agent is actually looking at the code, so a gap here is the-# one that matters. An exact-match ("GPL","LGPL") test was silent on the-# AGPL, BUSL and (after the detector fix) MPL-2.0 repos the hub ships.-# ----------------------------------------------------------------------------lic_warn="$(python3 - "$HERE/../scripts/xc.py" <<'PY'-import importlib.util, sys-spec = importlib.util.spec_from_file_location("xc", sys.argv[1])-xc = importlib.util.module_from_spec(spec); spec.loader.exec_module(xc)-warn = lambda l: bool(l) and any(r in l for r in xc.RESTRICTED)-must = ["AGPL", "SSPL", "Elastic", "BUSL", "GPL", "LGPL", "MPL-2.0",- "BUSL/MIT", "UNKNOWN", "NONE-FOUND", "Apache-2.0/UNKNOWN"]-mustnt = ["MIT", "Apache-2.0", "BSD", "Apache-2.0/MIT", ""]-bad = [l for l in must if not warn(l)] + [l for l in mustnt if warn(l)]-print("clean" if not bad else "wrong on " + ",".join(repr(b) for b in bad))-PY-)"-check "xc.py warns on every restricted licence and no permissive one" "$lic_warn" "clean"--# ----------------------------------------------------------------------------# 11. A rebuild that dropped a repository must not exit 0. The documented idiom-# is `xc-corpus.sh --from hub/<name>.json && xc-index.sh <name>`, so exit 0-# on a partial corpus indexes something that is not what the manifest-# describes while the "same manifest in, same bytes out" claim still reads-# as having held.-# ----------------------------------------------------------------------------cat > "$TMP/partial.json" <<EOF-{"corpus":"partial","cloned_at":"2026-08-12T00:00:00Z","repos":[- {"repo":"alpha","url":"$ALPHA_URL","licence":"MIT","sha":"$ALPHA_PIN","files":2,"bytes":0},- {"repo":"gone","url":"file://$TMP/remote/does-not-exist","licence":"MIT","sha":"$ALPHA_PIN","files":2,"bytes":0}-]}-EOF-H8="$TMP/home8"-if xc "$H8" --from "$TMP/partial.json"; then- bad "a partial rebuild exited 0"-else- ok "a partial rebuild exits non-zero"-fi-# The repo that DID land is still checked out, and the manifest still describes-# the real state — only the exit code says the corpus is not complete.-check "the repos that did land are still checked out" \- "$(git -C "$H8/corpora/partial/alpha" rev-parse HEAD 2>/dev/null || echo MISSING)" "$ALPHA_PIN"-if grep -q 'INCOMPLETE' "$TMP/out.log"; then- ok "a partial rebuild says which repos are missing"-else- bad "a partial rebuild failed without naming the gap"-fi--echo-echo "$pass passed, $fail failed"-[ "$fail" -eq 0 ]diff --git a/tools/xerj-code/tests/test_xc_index_fresh.py b/tools/xerj-code/tests/test_xc_index_fresh.pydeleted file mode 100755index 808bb65c4..000000000--- a/tools/xerj-code/tests/test_xc_index_fresh.py+++ /dev/null@@ -1,503 +0,0 @@-#!/usr/bin/env python3-"""Regression tests for `xc-index.sh <corpus> --fresh` (issue #930).--The bug: `--fresh` was forwarded to `xerj autoindex --fresh`, which is a-different thing (it discards autoindex's resume journal and is REFUSED once a-durable corpus generation exists), and a state directory written before the-`generation-v1` format cannot be adopted at all. So the documented rebuild —-the one xc.py itself prints when an index is older than 30 days — failed for-every corpus that had ever been indexed.--The fix is a build-verify-swap in the wrapper. These tests pin its contract:-- * --fresh really is fresh: a NEW --state-dir and a NEW index prefix, and the- `--fresh` flag is never forwarded to autoindex- * the state file's `prefix` stays `xc-<corpus>` (every `xc-<corpus>*` reader- keeps working); `index_prefix` names the one verified build- * the old index is retired ONLY after the replacement verified (count > 0),- by exact name, never by wildcard- * a failed or empty build leaves the old index AND the old state file exactly- as they were, and removes only what it created- * a sibling corpus (`battle` vs `battle-terse`) is never touched- * two --fresh runs inside one second cannot retire the build just verified- * an interrupted FIRST build (no index to fall back to) is kept, recorded as- salvaged with its real exit code, and resumed by a plain re-run- * a record count the node does not ANSWER is never read as zero: it cannot- get a working index retired, nor a finished build deleted--Offline: a fake node (http.server) and a fake `xerj` binary that behaves like-the real one where it matters — it refuses `--fresh` and refuses a legacy state-directory, with exit 1 and no records, exactly as in the #930 repro.-"""-import json-import os-import re-import stat-import subprocess-import sys-import tempfile-import threading-from fnmatch import fnmatchcase-from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer--HERE = os.path.dirname(os.path.abspath(__file__))-SCRIPT = os.path.join(HERE, "..", "scripts", "xc-index.sh")---class Node:- """The slice of the ES-compatible surface xc-index.sh talks to."""-- def __init__(self):- self.indices = {} # name -> record count- self.log = [] # (method, path) in arrival order- self.catalog_deletes = [] # delete-by-query bodies- self.count_outage = 0 # the next N `_count` requests answer 503- self.count_mute = set() # `_count` patterns that NEVER answer (503)- self.lock = threading.Lock()-- def matching(self, pattern):- return sorted(n for n in self.indices if fnmatchcase(n, pattern))---def make_handler(node):- class Handler(BaseHTTPRequestHandler):- def log_message(self, *args):- pass-- def reply(self, status, payload):- body = json.dumps(payload).encode()- self.send_response(status)- self.send_header("Content-Type", "application/json")- self.send_header("Content-Length", str(len(body)))- self.end_headers()- self.wfile.write(body)-- def body(self):- length = int(self.headers.get("Content-Length") or 0)- return self.rfile.read(length) if length else b""-- def do_GET(self):- path = self.path.split("?")[0]- with node.lock:- node.log.append(("GET", path))- if path == "/_cluster/health":- return self.reply(200, {"status": "green"})- if path.startswith("/_cat/indices/"):- pattern = path[len("/_cat/indices/"):]- return self.reply(200, [{"index": n} for n in node.matching(pattern)])- if path.endswith("/_count"):- # A busy node: it is up, it lists indices, it cannot count.- if path[1:-len("/_count")] in node.count_mute:- return self.reply(503, {"error": "busy"})- if node.count_outage > 0:- node.count_outage -= 1- return self.reply(503, {"error": "busy"})- pattern = path[1:-len("/_count")]- return self.reply(200, {"count": sum(node.indices[n] for n in node.matching(pattern))})- self.reply(404, {"error": "not found"})-- def do_DELETE(self):- name = self.path.split("?")[0].lstrip("/")- with node.lock:- node.log.append(("DELETE", "/" + name))- if "*" in name or "," in name or name.startswith("_"):- return self.reply(400, {"error": "wildcard delete refused"})- if node.indices.pop(name, None) is None:- return self.reply(404, {"error": "no such index"})- self.reply(200, {"acknowledged": True})-- def do_POST(self):- path = self.path.split("?")[0]- raw = self.body()- with node.lock:- node.log.append(("POST", path))- if path == "/__test/create":- spec = json.loads(raw)- node.indices[spec["index"]] = spec["docs"]- return self.reply(200, {})- if path == "/__test/outage":- node.count_outage = json.loads(raw)["requests"]- return self.reply(200, {})- if path == "/autoindex-catalog/_delete_by_query":- node.catalog_deletes.append(json.loads(raw))- return self.reply(200, {"deleted": 1})- self.reply(404, {"error": "not found"})-- return Handler---FAKE_XERJ = r'''#!/usr/bin/env bash-# Stand-in for `xerj autoindex`. Records its argv, then behaves as configured.-set -u-fake="$FAKE_DIR"-printf '%s\n' "$*" >> "$fake/argv.log"-url="" prefix="" state="$fake/default-state" fresh=0-args=("$@")-for ((i = 0; i < ${#args[@]}; i++)); do- case "${args[$i]}" in- --url) url="${args[$((i + 1))]}" ;;- --prefix) prefix="${args[$((i + 1))]}" ;;- --state-dir) state="${args[$((i + 1))]}" ;;- --fresh) fresh=1 ;;- esac-done-# The two refusals of issue #930, as the real binary makes them: exit 1, no-# remote mutation.-if [ "$fresh" = 1 ]; then- echo "error: this attempt made no remote mutations. \`--fresh\` cannot discard committed corpus generation 1 under the same destination" >&2- exit 1-fi-if [ -e "$state/LEGACY" ]; then- echo "error: this state directory contains a legacy nonempty plan that cannot become generation authority" >&2- exit 1-fi-rc="$(cat "$fake/rc" 2>/dev/null || echo 0)"-docs="$(cat "$fake/docs" 2>/dev/null || echo 7)"-if [ "$docs" -gt 0 ]; then- for dataset in docs code; do- curl -fsS -X POST "$url/__test/create" -H 'Content-Type: application/json' \- -d "{\"index\":\"$prefix-$dataset\",\"docs\":$docs}" >/dev/null- done-fi-mkdir -p "$state" && : > "$state/journal.ndjson"-if [ -f "$fake/outage" ]; then- curl -fsS -X POST "$url/__test/outage" -H 'Content-Type: application/json' \- -d "{\"requests\":$(cat "$fake/outage")}" >/dev/null-fi-exit "$rc"-'''---class Rig:- def __init__(self):- self.home = tempfile.mkdtemp(prefix="xc-index-fresh-")- self.fake = os.path.join(self.home, "fake")- os.makedirs(self.fake)- self.xerj = os.path.join(self.fake, "xerj")- with open(self.xerj, "w") as handle:- handle.write(FAKE_XERJ)- os.chmod(self.xerj, os.stat(self.xerj).st_mode | stat.S_IXUSR)- self.node = Node()- self.server = ThreadingHTTPServer(("127.0.0.1", 0), make_handler(self.node))- self.url = "http://127.0.0.1:%d" % self.server.server_address[1]- threading.Thread(target=self.server.serve_forever, daemon=True).start()-- def corpus(self, name):- os.makedirs(os.path.join(self.home, "corpora", name), exist_ok=True)-- def behave(self, rc=0, docs=7):- for key, value in (("rc", rc), ("docs", docs)):- with open(os.path.join(self.fake, key), "w") as handle:- handle.write(str(value))-- def legacy_state(self, name, docs=5):- """A corpus as the pre-#930 script left it: legacy ledger + legacy state dir."""- self.corpus(name)- os.makedirs(os.path.join(self.home, "state"), exist_ok=True)- with open(self.state_path(name), "w") as handle:- json.dump({"corpus": name, "indexed_at": "2026-08-07T08:43:16Z",- "prefix": "xc-" + name, "url": self.url, "autoindex_exit": 3}, handle)- os.makedirs(os.path.join(self.fake, "default-state"), exist_ok=True)- open(os.path.join(self.fake, "default-state", "LEGACY"), "w").close()- self.node.indices["xc-%s-docs" % name] = docs- self.node.indices["xc-%s-code" % name] = docs-- def state_path(self, name):- return os.path.join(self.home, "state", name + ".json")-- def state(self, name):- with open(self.state_path(name)) as handle:- return json.load(handle)-- def argv(self):- """One list of words per autoindex invocation (no test path has spaces)."""- path = os.path.join(self.fake, "argv.log")- if not os.path.exists(path):- return []- with open(path) as handle:- return [line.split() for line in handle if line.strip()]-- def run(self, *args):- env = dict(os.environ, XERJ_CODE_HOME=self.home, XERJ_URL=self.url,- XERJ_BIN=self.xerj, FAKE_DIR=self.fake, XC_COUNT_PAUSE="0")- env.pop("XERJ_API_KEY", None)- done = subprocess.run(["bash", SCRIPT, *args], env=env, capture_output=True,- text=True, timeout=120)- return done.returncode, done.stdout, done.stderr-- def close(self):- self.server.shutdown()---def flag(words, name):- return words[words.index(name) + 1] if name in words else ""---def main():- passed = failed = 0-- def check(name, cond, detail=""):- nonlocal passed, failed- if cond:- passed += 1- print(" ok — %s" % name)- else:- failed += 1- print(" FAIL — %s %s" % (name, detail))-- # 1 ── the defect: --fresh over a corpus indexed before generation-v1 ─────- print("--fresh over a legacy corpus (the #930 repro)")- rig = Rig()- rig.legacy_state("fix")- rig.behave(rc=3, docs=7)- code, out, err = rig.run("fix", "--fresh")- check("exits 0", code == 0, "code=%s stderr=%s" % (code, err))- argv = rig.argv()- check("autoindex ran exactly once", len(argv) == 1, str(argv))- words = argv[0] if argv else []- check("`--fresh` is NOT forwarded to autoindex", "--fresh" not in words, str(words))- check("a new --state-dir is passed", "/autoindex-state/fix/b" in flag(words, "--state-dir"), str(words))- built = flag(words, "--prefix")- check("the build prefix is xc-<corpus>-b<stamp>", re.fullmatch(r"xc-fix-b\d{14}", built) is not None, built)- state = rig.state("fix")- check("state `prefix` stays xc-<corpus>", state["prefix"] == "xc-fix", str(state))- check("state `index_prefix` names the verified build", state.get("index_prefix") == built, str(state))- check("state records the autoindex exit", state["autoindex_exit"] == 3, str(state))- check("old indices are retired", "xc-fix-docs" not in rig.node.indices- and "xc-fix-code" not in rig.node.indices, str(rig.node.indices))- check("the replacement is live", rig.node.indices.get(built + "-docs") == 7, str(rig.node.indices))- check("every xc-<corpus>* reader still resolves the corpus",- len(rig.node.matching("xc-fix*")) == 2, str(rig.node.indices))- deletes = [i for i, (method, _) in enumerate(rig.node.log) if method == "DELETE"]- verified = [i for i, (method, path) in enumerate(rig.node.log)- if method == "GET" and path == "/%s-*/_count" % built]- check("nothing is deleted before the replacement's count was read",- bool(deletes) and bool(verified) and min(deletes) > min(verified), str(rig.node.log))- check("deletes are by exact name, never a wildcard",- all("*" not in path for method, path in rig.node.log if method == "DELETE"), str(rig.node.log))- check("the old build's catalog scope is cleaned by exact value",- any(clause.get("term", {}).get("corpus_scope") == "xc-fix"- for body in rig.node.catalog_deletes- for clause in body["query"]["bool"]["should"]), str(rig.node.catalog_deletes))-- # 2 ── an update after a build reconciles THAT build in place ─────────────- print("plain re-run after a build")- code, out, err = rig.run("fix")- words = rig.argv()[-1]- check("exits 0", code == 0, err)- check("reuses the build's prefix", flag(words, "--prefix") == built, str(words))- check("reuses the build's state dir", flag(words, "--state-dir") == state["state_dir"], str(words))- check("index_prefix is unchanged", rig.state("fix").get("index_prefix") == built)-- # 3 ── a second --fresh: build beside, verify, retire the previous BUILD ──- print("--fresh over a previous build")- rig.behave(rc=0, docs=11)- code, out, err = rig.run("fix", "--fresh")- second = rig.state("fix").get("index_prefix")- check("exits 0", code == 0, err)- check("a different build id, even within the same second", bool(second) and second != built,- "%s vs %s" % (second, built))- check("the previous build is retired", not rig.node.matching(built + "-*"), str(rig.node.indices))- check("the new build survived its own retire step",- rig.node.indices.get("%s-docs" % second) == 11, str(rig.node.indices))- check("the previous build's state dir is removed", not os.path.exists(state["state_dir"]))- check("the new build's state dir is kept", os.path.isdir(rig.state("fix")["state_dir"]))- rig.close()-- # 4 ── a build that fails must not cost the working index ────────────────- for label, rc, docs in (("autoindex aborts", 1, 0), ("autoindex exits 0 with zero records", 0, 0)):- print("--fresh when %s" % label)- rig = Rig()- rig.legacy_state("fix", docs=5)- with open(rig.state_path("fix"), "rb") as handle:- ledger_before = handle.read()- rig.behave(rc=rc, docs=docs)- code, out, err = rig.run("fix", "--fresh")- check("exits non-zero", code != 0, "code=%s" % code)- check("the old index is untouched", rig.node.indices == {"xc-fix-docs": 5, "xc-fix-code": 5},- str(rig.node.indices))- with open(rig.state_path("fix"), "rb") as handle:- check("the state file is byte-identical", handle.read() == ledger_before)- check("says the existing index was not touched", "NOT touched" in err, err)- check("the failed build's state dir is removed",- not os.listdir(os.path.join(rig.home, "autoindex-state", "fix")))- rig.close()-- # 5 ── a partial build is removed, the old index is not ──────────────────- print("--fresh when autoindex aborts AFTER writing records, with a working index present")- rig = Rig()- rig.legacy_state("fix", docs=5)- rig.behave(rc=1, docs=9)- code, out, err = rig.run("fix", "--fresh")- check("exits with autoindex's code", code == 1, "code=%s" % code)- check("only the partial build is deleted; the working index stays",- rig.node.indices == {"xc-fix-docs": 5, "xc-fix-code": 5}, str(rig.node.indices))- check("state still points at the working index", "index_prefix" not in rig.state("fix"))- rig.close()-- # 6 ── sibling corpora share a name prefix and must never be touched ─────- print("--fresh next to a sibling corpus (battle / battle-terse)")- rig = Rig()- rig.legacy_state("battle", docs=5)- rig.corpus("battle-terse")- rig.node.indices["xc-battle-terse-docs"] = 42- rig.behave(rc=0, docs=7)- code, out, err = rig.run("battle", "--fresh")- check("exits 0", code == 0, err)- check("the sibling's index survives", rig.node.indices.get("xc-battle-terse-docs") == 42, str(rig.node.indices))- check("the sibling is never named in a DELETE",- not any("terse" in path for method, path in rig.node.log if method == "DELETE"), str(rig.node.log))- check("the corpus' own old indices are retired", "xc-battle-docs" not in rig.node.indices, str(rig.node.indices))- rig.close()-- # 7 ── first index of a corpus, and argument hygiene ─────────────────────- print("first index, and unknown flags")- rig = Rig()- rig.corpus("new")- rig.behave(rc=0, docs=3)- code, out, err = rig.run("new")- check("first index exits 0", code == 0, err)- check("first index is recorded as a build", bool(rig.state("new").get("index_prefix")), str(rig.state("new")))- check("nothing is deleted on a first index",- not any(method == "DELETE" for method, _ in rig.node.log), str(rig.node.log))- before = len(rig.argv())- code, out, err = rig.run("new", "--frsh")- check("a mistyped flag is rejected (exit 2), not silently ignored", code == 2, "code=%s" % code)- check("…and autoindex is not run", len(rig.argv()) == before)- rig.close()-- # 8 ── an interrupted FIRST build: nothing to fall back to, so it is kept ─- # The complement of 5. autoindex exits 1 part-way through a large corpus- # when the node keeps rejecting writes (#944); with no working index to- # protect, throwing the partial build away would leave no corpus at all.- # It is kept, recorded for what it is, and a plain re-run RESUMES it: same- # prefix, same state directory, so autoindex picks its journal back up.- print("an interrupted first build is kept, labelled, and resumed by a plain re-run")- rig = Rig()- rig.corpus("cut")- rig.behave(rc=1, docs=7)- code, out, err = rig.run("cut", "--fresh")- check("the script does not fail the salvaged build", code == 0, "code=%s stderr=%s" % (code, err))- check("it says so loudly", "WARNING" in err and "exited 1" in err, err)- state = rig.state("cut")- built = state.get("index_prefix", "")- check("the ledger records the real exit code", state.get("autoindex_exit") == 1, str(state))- check("the ledger records it as salvaged", state.get("salvaged") is True, str(state))- check("the ledger still names the build", re.fullmatch(r"xc-cut-b\d{14}", built) is not None, str(state))- check("the partial build's indices are kept", rig.node.indices.get(built + "-docs") == 7, str(rig.node.indices))- check("nothing was deleted", not any(method == "DELETE" for method, _ in rig.node.log), str(rig.node.log))- kept_state = state.get("state_dir", "")- check("its state directory is kept for the resume",- os.path.isfile(os.path.join(kept_state, "journal.ndjson")), kept_state)- rig.behave(rc=0, docs=9)- code, out, err = rig.run("cut")- words = rig.argv()[-1]- check("a plain re-run exits 0", code == 0, err)- check("it re-runs autoindex under the SAME prefix", flag(words, "--prefix") == built, str(words))- check("…and the SAME state directory, so the journal resumes", flag(words, "--state-dir") == kept_state, str(words))- state = rig.state("cut")- check("a finished resume clears the salvaged mark",- state.get("salvaged") is False and state.get("autoindex_exit") == 0, str(state))- check("the build id did not change", state.get("index_prefix") == built, str(state))- rig.close()-- # 9 ── "the node did not say" is not "zero": the OLD index ───────────────- # One 503 on one `_count` used to read a working index as "nothing to fall- # back to": the FAILED build was kept over it and the working index retired,- # exit 0. Only the OLD index's count is mute here — the new build's count- # answers, which is exactly the combination that did the damage.- print("--fresh when the node cannot count the WORKING index and the build fails")- rig = Rig()- rig.legacy_state("blind", docs=500)- before_state = rig.state("blind")- rig.behave(rc=1, docs=7)- rig.node.count_mute.add("xc-blind-*")- code, out, err = rig.run("blind", "--fresh")- check("the failed build is NOT accepted (non-zero exit)", code != 0, "code=%s" % code)- check("the working index survives", rig.node.indices.get("xc-blind-docs") == 500- and rig.node.indices.get("xc-blind-code") == 500, str(rig.node.indices))- check("the old index is never named in a DELETE",- not any(path in ("/xc-blind-docs", "/xc-blind-code")- for method, path in rig.node.log if method == "DELETE"), str(rig.node.log))- check("the state file still points at the working index", rig.state("blind") == before_state, str(rig.state("blind")))- check("it says the count was unknown and what it presumed", "did not answer a record count" in err- and "WORKING index" in err, err)- rig.close()-- # 10 ── …and the NEW build: a finished build must not be deleted unverified- # One 503 used to read a complete build as "empty": its indices AND its- # resume state were deleted.- print("--fresh when the build finishes but the node cannot count it (working index present)")- rig = Rig()- rig.legacy_state("mute", docs=500)- before_state = rig.state("mute")- rig.behave(rc=0, docs=7)- # The old count must succeed (1 request) and every later one fail: let the- # first through, then start the outage from inside the fake binary's run.- with open(os.path.join(rig.fake, "outage"), "w") as handle:- handle.write("6")- code, out, err = rig.run("mute", "--fresh")- built = [n for n in rig.node.indices if re.match(r"xc-mute-b\d{14}-", n)]- check("exits non-zero: the build could not be verified", code != 0, "code=%s" % code)- check("NOTHING is deleted", not any(method == "DELETE" for method, _ in rig.node.log), str(rig.node.log))- check("the unverified build's indices are kept", len(built) == 2, str(rig.node.indices))- check("the working index is kept", rig.node.indices.get("xc-mute-docs") == 500, str(rig.node.indices))- check("readers are NOT switched to an unverified build", rig.state("mute") == before_state, str(rig.state("mute")))- state_root = os.path.join(rig.home, "autoindex-state", "mute")- check("the build's resume state is kept",- os.path.isdir(state_root) and any(os.path.isfile(os.path.join(state_root, d, "journal.ndjson"))- for d in os.listdir(state_root)), state_root)- check("it says so", "NOTHING was deleted" in err and "NOT touched" in err, err)- rig.close()-- print("a FIRST build the node cannot count is kept and recorded as unverified")- rig = Rig()- rig.corpus("first")- rig.behave(rc=0, docs=7)- rig.node.count_outage = 6- code, out, err = rig.run("first", "--fresh")- check("exits non-zero", code != 0, "code=%s" % code)- check("nothing is deleted", not any(method == "DELETE" for method, _ in rig.node.log), str(rig.node.log))- state = rig.state("first")- check("the ledger records it as unverified (salvaged), with the real exit code",- state.get("salvaged") is True and state.get("autoindex_exit") == 0, str(state))- check("its indices are kept", rig.node.indices.get(state.get("index_prefix", "?") + "-docs") == 7, str(rig.node.indices))- rig.node.count_outage = 0- code, out, err = rig.run("first")- state = rig.state("first")- check("a plain re-run, once the node answers, confirms it and clears the mark",- code == 0 and state.get("salvaged") is False, "code=%s state=%s" % (code, state))- rig.close()-- # 11 ── patience: a node that answers on a later attempt is simply believed- print("--fresh when the count fails a few times and then answers")- rig = Rig()- rig.legacy_state("slow", docs=500)- rig.behave(rc=0, docs=7)- rig.node.count_outage = 3- code, out, err = rig.run("slow", "--fresh")- check("exits 0", code == 0, "code=%s stderr=%s" % (code, err))- check("the replacement was verified and readers switched",- re.fullmatch(r"xc-slow-b\d{14}", rig.state("slow").get("index_prefix", "")) is not None, str(rig.state("slow")))- check("the old index was retired only then", "xc-slow-docs" not in rig.node.indices, str(rig.node.indices))- rig.close()-- # 12 ── legacy path: without a count from BEFORE the run, nothing is salvaged- print("legacy update when the node could not count before the run")- rig = Rig()- rig.legacy_state("old", docs=500)- os.remove(os.path.join(rig.fake, "default-state", "LEGACY"))- before_state = rig.state("old")- rig.behave(rc=1, docs=9)- rig.node.count_outage = 6- code, out, err = rig.run("old")- check("a failed legacy run is not salvaged on an unknown baseline", code != 0, "code=%s" % code)- check("the ledger is not re-dated", rig.state("old") == before_state, str(rig.state("old")))- rig.close()-- print("\n%d passed, %d failed" % (passed, failed))- return 1 if failed else 0---if __name__ == "__main__":- sys.exit(main())diff --git a/tools/xerj-code/tests/validate_manifest.py b/tools/xerj-code/tests/validate_manifest.pydeleted file mode 100755index 05357adda..000000000--- a/tools/xerj-code/tests/validate_manifest.py+++ /dev/null@@ -1,96 +0,0 @@-#!/usr/bin/env python3-"""Validate a shareable corpus manifest.--A manifest published under the project's name is a claim about other people's-code: these URLs, at these commits, under these licences. This checks the parts-a machine can check, so review can spend its attention on the licence column.--usage: validate_manifest.py <manifest.json>...- validate_manifest.py --hub <manifest.json>... # also require review{}-"""--import json-import re-import sys--FULL_SHA = re.compile(r"[0-9a-f]{40}")-# `repo` is used as a directory name under the corpus root, which xc-corpus.sh-# then force-checks-out and cleans. A name containing '/' or '..' escapes the-# corpus and destroys whatever it lands on, so a manifest carrying one must-# never pass review — least of all one published under the project's name.-REPO_NAME = re.compile(r"[A-Za-z0-9_][A-Za-z0-9._-]*\Z")-USES = {"adapt-with-attribution", "approach-only", "mixed"}---def check(path: str, hub: bool) -> list[str]:- errs: list[str] = []- try:- with open(path) as fh:- m = json.load(fh)- except (OSError, json.JSONDecodeError) as e:- return [f"unreadable: {e}"]-- corpus = m.get("corpus")- if not corpus:- errs.append("no 'corpus' name")- repos = m.get("repos")- if not isinstance(repos, list) or not repos:- return errs + ["'repos' must be a non-empty array"]-- if hub:- stem = path.rsplit("/", 1)[-1].removesuffix(".json")- if corpus != stem:- errs.append(f"corpus '{corpus}' does not match filename '{stem}'")-- seen = set()- for r in repos:- name = r.get("repo") or "<unnamed>"- if name in seen:- errs.append(f"{name}: duplicate entry")- seen.add(name)- for k in ("repo", "url", "licence", "sha"):- if not r.get(k):- errs.append(f"{name}: missing '{k}'")- if not REPO_NAME.match(str(r.get("repo") or "")):- errs.append(- f"{name}: repo name is not a plain directory name "- "(letters, digits, '.', '_', '-'; not starting with '.' or '-')"- )- sha = r.get("sha") or ""- # A short sha is not fetchable from a remote, so it cannot pin a- # rebuild — the whole point of sharing the definition.- if not FULL_SHA.fullmatch(sha):- errs.append(f"{name}: sha '{sha}' is not a full 40-character sha")- if not hub:- continue- if not (r.get("url") or "").startswith("https://"):- errs.append(f"{name}: url must be https")- rev = r.get("review") or {}- if not rev.get("spdx"):- errs.append(f"{name}: no human-reviewed 'review.spdx'")- if rev.get("use") not in USES:- errs.append(f"{name}: review.use must be one of {sorted(USES)}")- if not (rev.get("by") and rev.get("at")):- errs.append(f"{name}: review needs 'by' and 'at'")- return errs---def main() -> int:- args = sys.argv[1:]- hub = "--hub" in args- paths = [a for a in args if a != "--hub"]- if not paths:- print(__doc__, file=sys.stderr)- return 2- bad = 0- for p in paths:- errs = check(p, hub)- if errs:- bad += 1- for e in errs:- print(f"{p}: {e}", file=sys.stderr)- return 1 if bad else 0---if __name__ == "__main__":- sys.exit(main())