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(xerj-code): ship the reference-coding tooling, and make corpus.json rebuild a corpus
xerj-org7bdda34a8d62
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex a0d55144b..d3d589bb1 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -51,6 +51,29 @@ jobs:PR_NUMBER: ${{ github.event.pull_request.number }}run: python3 scripts/check_cla_coauthors.py --pr "$PR_NUMBER"+ reference-coding:+ name: Reference-coding toolkit+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4++ - name: Shell syntax+ run: |+ 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++ # 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: Vetted hub manifests validate+ run: python3 tools/xerj-code/tests/validate_manifest.py --hub tools/xerj-code/hub/*.json+lint:name: Format + Clippyruns-on: ubuntu-latestdiff --git a/.gitignore b/.gitignoreindex 04f660a35..2e0cc4a59 100644--- a/.gitignore+++ b/.gitignore@@ -118,6 +118,13 @@ landing/resources/xerj-sales-kit.zip!ROADMAP.md!docs/**/*.md+# Re-include the shipped tooling's own docs. `tools/xerj-code/SKILL.md` is part+# of the tool, not a design note, and the blanket *.md rule above silently+# swallowed it — the same failure mode as the pull-request template below, and+# the reason issue #319 existed at all (the reference-coding tooling was+# documented everywhere and shipped nowhere).+!tools/**/*.md+# Re-include the public .github community files. The blanket *.md rule above# silently swallowed these: no pull-request template has ever existed in this# repo's history because `git add` refused it without anyone noticing, whilediff --git a/AGENTS.md b/AGENTS.mdindex e1033a6fc..5a3ba94f8 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -43,7 +43,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`).-- **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 `xc.py <corpus> "<what you need>"`. 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 `xc.py <corpus> "<what you need>"`; the tooling and the pinned corpus definitions are in [`tools/xerj-code/`](tools/xerj-code/). 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 ES-YAML conformance suite must stay at **0 failed** (currently 1365 passed / 0 failed / 3 skipped — the pass count grows 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).- **Git discipline:** non-trivial changes land with full commit bodies (motivation, before/after numbers, root cause, file pointers) — the git history is the project's engineering log; read it before re-deriving decisions.diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex f83e29e7a..9b9c361db 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 `xc.py` helper in the internal `xerj-code` tooling. 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 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.## Git workflowdiff --git a/docs/case-studies/reference-coding/CASE_STUDY.md b/docs/case-studies/reference-coding/CASE_STUDY.mdindex 8acd374fb..f34dfceb7 100644--- a/docs/case-studies/reference-coding/CASE_STUDY.md+++ b/docs/case-studies/reference-coding/CASE_STUDY.md@@ -5,8 +5,8 @@> unfamiliar-code libraries plus two memorised controls (tantivy, valkey+memcached).> Every number produced by `csrun.py` / `csmulti.py` + `summarize.py` on this> machine. Full method (what/which repos indexed, how indexed, how searched, how to-> reproduce) below and in `MEASURE.md`. Raw data in `results-*.json`; captured-> generated programs in `generated/`.+> reproduce) below. Raw data in `data/results-*.json`; captured generated+> programs in `generated/`.>> **One-line answer:** on the seven domains carrying a contract the model cannot> recall (a seal, a generational handle, a lazy refill, a specific hash scheme, an@@ -123,13 +123,20 @@ Two kinds of reference deliberately:## How they were indexed-Two commands, both shipped with the skill:+Two commands, both shipped in [`tools/xerj-code/`](../../../tools/xerj-code/):```shxc-corpus.sh <name> <git-url>… # shallow clone (--depth 1) + record each repo's licencexc-index.sh <name> # xerj autoindex <dir> --url <XERJ> --prefix xc-<name> --no-graph```+`xc-corpus.sh` writes a `corpus.json` next to the clones — URLs, full commit+SHAs and licences, a few hundred bytes, no source. That file is the shareable+definition of a corpus: `xc-corpus.sh --from <manifest>` rebuilds it at the same+commits somewhere else, which is what makes two people's retrieval results+comparable. Pinned, licence-reviewed definitions for the corpora used here are+in [`tools/xerj-code/hub/`](../../../tools/xerj-code/hub/).+`xc-index.sh` runs **`xerj autoindex`** — XERJ's zero-config folder ingester: itsniffs file types, extracts per-file records (for source it pulls symbol/definitionmetadata via tree-sitter), and bulk-loads them into the local engine under the@@ -157,16 +164,25 @@ returns ranked passages with `file:line` provenance:The `xerj` arm gets that passage injected into its prompt. The `native` arm ishanded the same corpus tree on disk and must `grep`/read to find the API itself —that search cost is what the two arms differ by. See a worked query and its output-in `SKILL.md`.+in [`tools/xerj-code/SKILL.md`](../../../tools/xerj-code/SKILL.md).## How you reproduce it-End-to-end recipe in **`MEASURE.md`**: start XERJ → `xc-corpus.sh`/`xc-index.sh` a-corpus → `validate_*` the tasks → `csrun.py`/`csmulti.py` across the three arms →-`summarize.py`. It needs the `xerj` binary, the `claude` CLI (no API key — token-counts and cost come from `claude -p --output-format json`), and the language-toolchains. To measure retrieval on **your own** code, point `xc-index.sh` at your-repo and write a task with a hidden test — that is the real use case.+The **retrieval half** is shipped and runs as printed: start XERJ, then+`xc-corpus.sh` (or `xc-corpus.sh --from tools/xerj-code/hub/<corpus>.json`, which+pins the exact commits these runs used) → `xc-index.sh` → `xc.py`. It needs the+`xerj` binary, `git` and `python3`. To point it at **your own** code, index your+repo instead of a corpus — that is the real use case.++The **measurement harness** — the three-arm runner, the purpose-built reference+libraries, the hidden-test task specs — is **not** in this repository; only its+outputs are (`data/results-*.json`, `generated/`). What it does, if you want to+build the equivalent: run three arms of the same agent (memory only / grep-driven+/ retrieval-injected) over tasks whose verdict is objective — the code compiles+and passes a hidden test the model never sees — using the `claude` CLI's own+token and cost accounting (`claude -p --output-format json`, no API key), and+report medians. Validate each task first by injecting a known-correct and a+known-wrong solution; a benchmark whose tests pass wrong code measures nothing.---diff --git a/docs/case-studies/reference-coding/OPENER_PROMPT.md b/docs/case-studies/reference-coding/OPENER_PROMPT.mdindex 56ea8c355..1f25702cf 100644--- a/docs/case-studies/reference-coding/OPENER_PROMPT.md+++ b/docs/case-studies/reference-coding/OPENER_PROMPT.md@@ -8,7 +8,7 @@ look up.--insecure`).2. Look at this project — its dependencies, the domains its code touches — anddecide which well-known open-source libraries already solve those problems.- Clone them into a reference corpus with the skill's `xc-corpus.sh`, grouped by+ Clone them into a reference corpus with `tools/xerj-code/scripts/xc-corpus.sh`, grouped byproblem domain (async, parsers, storage, …), not by language.3. Index that corpus with `xc-index.sh` (it runs `xerj autoindex`).4. From now on, for **every** coding task this session: before you writediff --git a/docs/case-studies/reference-coding/SUMMARY.md b/docs/case-studies/reference-coding/SUMMARY.mdindex 894a711ca..0ee8e0dfd 100644--- a/docs/case-studies/reference-coding/SUMMARY.md+++ b/docs/case-studies/reference-coding/SUMMARY.md@@ -53,5 +53,7 @@ memorization, and the line is sharp.retrieval-vs-none, which both server versions deliver equally.Full write-up: `CASE_STUDY.md`. Raw per-run data: `data/`. Captured generated-programs (the 503-line failure vs the 4-line success): `generated/`. Reproduce with-the harness in the `xerj-code` skill (`MEASURE.md`).+programs (the 503-line failure vs the 4-line success): `generated/`. The retrieval+tooling — and pinned, licence-reviewed definitions of the corpora used here — ship+in `tools/xerj-code/`; see "How you reproduce it" in `CASE_STUDY.md` for what is+and is not included.diff --git a/landing/case-studies/reference-coding.html b/landing/case-studies/reference-coding.htmlindex 6f5481fad..78237fd14 100644--- a/landing/case-studies/reference-coding.html+++ b/landing/case-studies/reference-coding.html@@ -286,13 +286,14 @@ Do this proactively for the rest of the session without me asking again.</pre><!-- Reproduce guide --><section class="scene-section"><h2 class="scene" style="font-size:var(--fs-56);">DO IT <span class="accent">YOURSELF.</span></h2>- <p class="wide">The whole study reproduces from the repo. The method works on any repository — including your own private code, which is the real use case.</p>+ <p class="wide">The tooling ships in the repo, at <a class="mono" href="https://github.com/xerj-org/xerj/tree/main/tools/xerj-code" rel="external" style="color:var(--accent);">tools/xerj-code/</a>. The method works on any repository — including your own private code, which is the real use case.</p><ol class="steps" style="margin-top:var(--sp-6); max-width:820px;"><li><strong>Start XERJ.</strong> <code class="inline">xerj -d ./.xerj-data --insecure</code> — the ES-compatible API comes up on <code class="inline">:9200</code>.</li><li><strong>Build a corpus.</strong> <code class="inline">xc-corpus.sh async-rust https://github.com/tokio-rs/tokio https://github.com/hyperium/hyper</code> — group by problem domain, not language.</li>+ <li><strong>Or rebuild one someone already vetted.</strong> <code class="inline">xc-corpus.sh --from hub/xerj-search.json</code> — a corpus definition is URLs, pinned commit SHAs and licences; no source, so nothing to redistribute, and the same file gives two machines the same bytes.</li><li><strong>Index it.</strong> <code class="inline">xc-index.sh async-rust</code> — runs <code class="inline">xerj autoindex</code>; a 100k-record tree indexes in ~10 s.</li><li><strong>Retrieve before you write.</strong> <code class="inline">xc.py async-rust "graceful shutdown with a broadcast channel"</code> — returns the matching definition with <code class="inline">file:line</code>.</li>- <li><strong>Measure it honestly.</strong> The 3-arm harness (<code class="inline">csrun.py</code>, <code class="inline">csmulti.py</code>) runs bare / native / XERJ, one hidden-test verdict, real tokens from <code class="inline">claude -p --output-format json</code> — no API key. Full recipe in <a href="https://github.com/xerj-org/xerj/blob/main/docs/case-studies/reference-coding/CASE_STUDY.md" rel="external" style="color:var(--accent);">MEASURE / CASE_STUDY.md</a>.</li>+ <li><strong>Measure it honestly.</strong> Three arms of the same agent — memory only, grep-driven, retrieval-injected — one hidden-test verdict, real tokens from <code class="inline">claude -p --output-format json</code>, no API key. The numbers and every per-run record are in <a href="https://github.com/xerj-org/xerj/blob/main/docs/case-studies/reference-coding/CASE_STUDY.md" rel="external" style="color:var(--accent);">CASE_STUDY.md</a>; the harness itself is not shipped.</li></ol></section>diff --git a/landing/index.html b/landing/index.htmlindex 59079ed4d..5b72f9434 100644--- a/landing/index.html+++ b/landing/index.html@@ -80,14 +80,21 @@(260,916 → 9,982), <strong>2.1× cheaper</strong> ($1.58 vs $3.27). In acompanion run on a Rust library the model had never seen:<strong>9/9 with retrieval vs 0/9 from memory</strong>. The three helper- scripts below ship with the case study — the hero prompt sets them up.+ scripts below ship in the repo, under+ <a class="mono" href="https://github.com/xerj-org/xerj/tree/main/tools/xerj-code" rel="external" style="color:var(--z-mute);">tools/xerj-code/</a>.</p>-<pre class="code">$ xc-corpus.sh xerj-storage https://github.com/spacejam/sled … # clone the peers, once-$ xc-index.sh xerj-storage # xerj autoindex, once per corpus+<pre class="code">$ xc-corpus.sh --from hub/xerj-storage.json # or: xc-corpus.sh xerj-storage <git-url>…+$ xc-index.sh xerj-storage # xerj autoindex, once per corpus$ xc.py xerj-storage "how does sled fsync its WAL segment on rotation?"→ the exact function, file:line, contract included — a passage to read, not a tree to grep</pre>+ <p class="wide" style="margin-top:var(--sp-3);">+ A corpus definition is a few hundred bytes of URLs, pinned commit SHAs and+ licences — no source, so nothing to redistribute. Share the file, and+ <code class="inline">--from</code> rebuilds the same commits on the other machine.+ </p>+<p class="viz-caption"><a class="mono" href="/case-studies/reference-coding.html" style="color:var(--z-mute);">THE FULL CASE STUDY — EVERY NUMBER, EVERY TASK, THE EXACT PROMPT →</a></p></section>diff --git a/tools/xerj-code/README.md b/tools/xerj-code/README.mdnew file mode 100644index 000000000..c785fe981--- /dev/null+++ b/tools/xerj-code/README.md@@ -0,0 +1,95 @@+# XERJ.code — the reference-coding toolkit++An agent that does not know an API guesses, runs, fails, and guesses again. Each+lap costs **output** tokens, the expensive kind. This toolkit replaces laps with+a 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)).++```sh+scripts/xc-corpus.sh xerj-storage https://github.com/spacejam/sled … # clone the peers, once+scripts/xc-index.sh xerj-storage # xerj autoindex, once per corpus+scripts/xc.py 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+```++## 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`.++Clones land in `~/.xerj-code/corpora/`, overridable with `XERJ_CODE_HOME`.++## Sharing a corpus: definitions, not indexes++`corpus.json` is a few hundred bytes of URLs, commit SHAs and licences. It+contains no source, so there is no redistribution question, and it rebuilds the+corpus anywhere:++```json+{"corpus":"xerj-storage","cloned_at":"2026-08-06T20:24:00Z","repos":[+ {"repo":"sled","url":"https://github.com/spacejam/sled","licence":"Apache-2.0/MIT",+ "sha":"e449d17111f4a097e1c66b6db241962ccb6a4136","files":70,"bytes":1322994}+]}+```++`xc-corpus.sh` 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+cheap shallow fetch per repo. A manifest carrying short SHAs (anything written+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 local+edits or untracked files inside it are discarded. Same manifest in, same bytes+out — which is what makes a shared prompt or a shared measurement comparable+across two machines.++Pre-built *indexes* are a different question (on-disk format version, embedder+identity, 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+text-matching heuristics and **has been wrong**, in both directions:++- Elasticsearch's triple licence (AGPL-3.0 / SSPL-1.0 / Elastic-2.0) was+ recorded as `Apache-2.0`, because its text contains the phrase *an "Apache+ License 2.0" compatible license*. Fixed by checking restrictive phrases first.+- sonic's plain MPL-2.0 was recorded as `GPL`, because MPL-2.0 defines+ "Secondary License" in terms of the GNU GPL inside its own text. Fixed by+ reading the title before the body.++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).++**Retrieved code is evidence, not authority.** It shows how *that* project+solved it under *its* constraints. Cite `file:line`, and say plainly when you+are adapting rather than copying.++## Honest scope++Retrieval wins decisively on code the model has **not** memorised — private,+internal, niche, or post-cutoff. On popular public library code the model+already knows, it is overhead. `SKILL.md` and+[`docs/case-studies/reference-coding/`](../../docs/case-studies/reference-coding/)+carry the measured numbers, including the cases where this loses.++## Tests++```sh+tools/xerj-code/tests/test_xc_corpus.sh # offline; local git fixtures over file://+```diff --git a/tools/xerj-code/SKILL.md b/tools/xerj-code/SKILL.mdnew file mode 100644index 000000000..f90378515--- /dev/null+++ b/tools/xerj-code/SKILL.md@@ -0,0 +1,258 @@+---+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.+---++# XERJ.code — reference coding++An agent that does not know an API guesses, runs, fails, and guesses again. Each+lap costs **output** tokens, which are the expensive kind. This skill replaces+laps with a lookup: clone the repositories that already contain a correct+implementation, index them with XERJ, and retrieve the passage before writing.++The trade is deliberate. Retrieval spends **input** tokens, which are cheaper per+token and cacheable; loops spend **output** tokens. See [`COSTS.md`](../../docs/case-studies/reference-coding/COSTS.md) for+the arithmetic and for the conditions under which this trade **loses**.++> **Status, stated plainly: measured, and the value is real but narrow.**+> (Full case study with real tokens and dollars: [`docs/case-studies/reference-coding/CASE_STUDY.md`](../../docs/case-studies/reference-coding/CASE_STUDY.md), 2026-08-05.)+>+> The comparison that matters is against **native Claude Code** — the same agent+> with tools that would grep the source itself — not a bare model. Measured across+> three regimes, same agent, one objective verdict (compiles + passes hidden tests):+>+> - **Unfamiliar code with a contract the model can't recall** (a seal, a+> generational handle, a lazy refill, a specific hash scheme — measured across+> **seven purpose-built libraries, 21 runs**): native and xerj both solve+> **21/21**; **xerj uses 1.5× fewer output tokens and costs 1.3× less than+> native**, because retrieval replaces the grep. Pure memory **fails 1/21** and+> burns **6.5× the cost** flailing. This is the win, and it is decisive. The+> compiler can leak an API *name* across a retry loop, but never a *contract*.+> - **Memorised code** (any popular public crate — even a 256-value table, or a+> protobuf-style varint): retrieval is **overhead**. Pure memory is cheapest;+> injecting a big reference can be the *worst* arm, because the model re-emits+> what it was handed.+>+> So: **use this when the reference is code the model has not memorised** — your+> own private/proprietary code, an internal API, a post-cutoff or niche library.+> On public library references the model already knows, it costs more than it+> saves. The native-vs-xerj gap grows with corpus size (grep pulls the whole tree+> into context; retrieval pulls one passage).++## Standing corpora for this repository (MANDATORY since 2026-08-06)++In the xerj repo, retrieval-before-writing is **required** for non-trivial+engine 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:++| corpus | projects | use it for |+|---|---|---|+| `xerj-search` | tantivy, meilisearch, quickwit, sonic, elasticsearch | FTS, BM25, postings, merge policy, typo tolerance, segment layout, ES wire semantics |+| `xerj-vector` | qdrant, usearch, instant-distance, hnswlib | HNSW build, neighbour heuristics, quantisation, filtered kNN |+| `xerj-storage` | sled, fjall, redb | WAL, flush epochs, crash recovery, compaction, page allocation |+| `xerj-columnar` | clickhouse | columnar storage, aggregation execution, compression codecs, vectorised scans |++**Approach-only sources:** `elasticsearch` (AGPL-3.0 / SSPL-1.0 / Elastic-2.0)+and `sonic` (MPL-2.0). Never copy their code into Apache-2.0 XERJ; for ES,+pasting source would also falsify the project's public "shares no code with+Elasticsearch" claim. `meilisearch` is MIT at the core but **BUSL-1.1 for its+Enterprise Edition** parts — check the header/path first. Read the design,+write our own implementation. Each manifest's `review.use` field says which+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.+- **`--fresh` is required after the data dir is wiped or moved.** `autoindex`+ keeps incremental state in `~/.xerj/autoindex/`; run it without `--fresh`+ against an empty instance and every file is skipped as "already indexed",+ leaving **0 documents** and a corpus that returns nothing without erroring.+ Always verify: `curl -s "$URL/xc-<corpus>*/_count"` must be > 0.++## When this is worth it++Use it when the task touches code someone else has already written correctly:++- an unfamiliar library, framework, or protocol+- porting an algorithm whose reference implementation exists+- matching an established convention across a large codebase+- **any time you have already looped twice on the same error** — that is the+ signal that guessing is not converging++Do not use it for code that only exists in this repository (ordinary file reads+are cheaper), for one-line edits, or when you already know the API. Indexing has+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)+```++### 1. Build a corpus++Group repositories by *problem domain*, not by language. A corpus for "async+Rust" holds tokio, hyper, and tower; a corpus for "parsers" holds nom, pest, and+tree-sitter. Keep corpora small and sharp — a corpus that contains everything+retrieves like a search engine with no query.++```sh+scripts/xc-corpus.sh async-rust \+ https://github.com/tokio-rs/tokio \+ https://github.com/hyperium/hyper+```++Clones are shallow (`--depth 1`) and land in `~/.xerj-code/corpora/<name>/`.+Every build writes a `corpus.json` beside them — URLs, full commit SHAs and+licences, a few hundred bytes, no source. That file *is* the shareable corpus+definition: hand it to someone else and++```sh+scripts/xc-corpus.sh --from their-corpus.json+```++rebuilds the same commits on their machine (an existing clone is moved to the+recorded SHA, so both trees match). Vetted definitions for the corpora this+project uses live in [`hub/`](hub/):++```sh+scripts/xc-corpus.sh --from hub/xerj-storage.json && scripts/xc-index.sh xerj-storage+```++### 2. Index it++```sh+scripts/xc-index.sh async-rust+```++This runs `xerj autoindex` against the local XERJ instance. **Exit code 3 means+"completed with junk files" and is not a failure** — some files in any real+repository are unparseable. Treat 0 and 3 as success; anything else is real.++### 3. Retrieve before writing++```sh+scripts/xc.py async-rust "graceful shutdown with a broadcast channel"+```++`xc.py` returns the **matching definition**, not a byte window:++```+─── valkey/src/networking.c (score 12.68, BSD)+ [function addBulkStringToReplyIOV @ line 2635 — 366 of 272,498 chars]+static void addBulkStringToReplyIOV(char *buf, size_t buf_len, ...) {+```++That line number is the whole point. A record is one whole file, so ranking can+only tell you *which* file matched; the definition is located from the `symbols[]`+the index already carries. Before this, an 8 KB slice of a 272 KB file was a coin+flip on whether the answer was inside it — a query about null replies correctly+ranked `networking.c` and then returned its licence banner, because `addReplyNull`+lives at line 1460. Read the named definition, cite it, and if the top hits are+irrelevant 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).++### Retrieval modes++The default is **`bm25`**. Measured across two corpora and twelve hand-labelled+queries:++| | rust-text | | kv-oss (C) | | combined | |+|----------|----------:|-----:|-----------:|-----:|---------:|------:|+| | 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 |++top-3 is the operative metric — the agent reads *k* passages, not one — and BM25+is perfect on it while never being the worst arm on either corpus. It is also+~5× faster, with no vector round trip and no mapping lookup.++Hybrid was previously the default, chosen on `rust-text` alone where it wins+top-1. That was a corpus-specific result: on the C corpus the vector arm reaches+only **5 of 407** indices (issue #173), so fusion mixes a good ranking with one+that cannot see 98.8% of the material. Use `--mode hybrid` when a corpus has+broad `semantic_text` coverage *and* you specifically care about top-1 — and+measure 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+```++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.++## Rules that keep this honest++**Retrieved code is evidence, not authority.** A passage proves how *that*+project solved the problem under *its* constraints. Cite `file:line` when you+rely 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.++**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+answer from an index older than 30 days unless you pass `--stale-ok`; re-run+`xc-index.sh` instead.++**Never index the working repository into a shared corpus.** Reference corpora+are for other people's code. Mixing your own in makes retrieval return your own+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.++## Measuring it++The published numbers, the per-run raw data and the price model live in+[`docs/case-studies/reference-coding/`](../../docs/case-studies/reference-coding/):+`CASE_STUDY.md` for the write-up, `COSTS.md` for why output tokens are the+expensive kind, `data/results-*.json` for the runs behind each figure, and+`generated/` for code the two arms actually produced.++The measurement harness itself (`csrun.py`, the purpose-built reference+libraries, 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.++Two rules that decide whether a result means anything:++- **Validate the tasks before spending a token.** Inject the reference-correct+ solution (must pass) and a plausible wrong one — correct but quadratic, or+ missing the contract — which must **fail**. A benchmark whose tests pass wrong+ code measures nothing.+- **Do not measure on code the model has memorised.** It reproduces even a+ 256-value table from recall, and retrieval then shows as pure overhead. The+ honest test bed is code that was never in a training set — your own private+ code is the realistic case.diff --git a/tools/xerj-code/hub/README.md b/tools/xerj-code/hub/README.mdnew file mode 100644index 000000000..60c66a809--- /dev/null+++ b/tools/xerj-code/hub/README.md@@ -0,0 +1,66 @@+# Vetted corpus definitions++Each file here defines a reference corpus by **domain**, pinned to exact+commits. 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+```++| corpus | projects | use it for | approx. checkout |+|---|---|---|---|+| [`xerj-search`](xerj-search.json) | tantivy, quickwit, meilisearch, sonic, elasticsearch | FTS, BM25, postings, merge policy, typo tolerance, segment layout, ES wire semantics | ~680 MB |+| [`xerj-vector`](xerj-vector.json) | qdrant, usearch, instant-distance, hnswlib | HNSW construction, neighbour heuristics, quantisation, filtered kNN | ~44 MB |+| [`xerj-storage`](xerj-storage.json) | sled, fjall, redb | WAL, flush epochs, crash recovery, compaction, page allocation | ~28 MB |+| [`xerj-columnar`](xerj-columnar.json) | clickhouse | columnar storage, aggregation execution, compression codecs, vectorised scans | ~1.2 GB |++Group by problem domain, not by language. A corpus that contains everything+retrieves like a search engine with no query.++## The `review` block++The `licence` field is what the detector read from the checkout. The `review`+block is what a human concluded, and it is why these manifests are contributed+by PR:++```json+"review": {"spdx": "AGPL-3.0-only OR SSPL-1.0 OR Elastic-2.0",+ "use": "approach-only", "by": "xerj-org", "at": "2026-08-12",+ "note": "Triple-licensed; the detector reports only the first match."}+```++`use` is one of:++- **`adapt-with-attribution`** — permissive (Apache-2.0 / MIT / BSD). Adapt+ freely; still cite `file:line` when you do.+- **`approach-only`** — copyleft or source-available (AGPL, SSPL, Elastic, BUSL,+ GPL, LGPL, MPL). Read the design, write your own code. Never paste.+- **`mixed`** — permissive core with restricted parts (Meilisearch: MIT core,+ BUSL-1.1 Enterprise Edition). Check the file's header and path before copying+ anything.++XERJ is Apache-2.0. Copying an incompatibly licensed implementation in is a real+problem, not a technicality. Elasticsearch is in `xerj-search` to answer *"what+does ES actually do here?"* for wire-protocol and semantics questions — XERJ's+public position is that it shares no code and no architecture with it, and+pasting ES source would make that claim false.++## Contributing a corpus++1. Build it locally: `xc-corpus.sh <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 per+ entry. Do not copy the detector's answer without looking; it has been wrong+ in both directions (see [`../README.md`](../README.md)).+4. Check it: `python3 tools/xerj-code/tests/validate_manifest.py --hub hub/<name>.json`+5. Open a PR. Say what the corpus is *for* — a domain a reviewer can judge, not+ a pile of repositories.++## Refreshing a pin++The SHAs are deliberately frozen: a shared pin is what makes two people's+retrieval results comparable. To move a corpus forward, rebuild without `--from`+(`xc-corpus.sh <name> <url>...` in a clean `XERJ_CODE_HOME`), re-review any+licence that changed, and open a PR with the new manifest.diff --git a/tools/xerj-code/hub/xerj-columnar.json b/tools/xerj-code/hub/xerj-columnar.jsonnew file mode 100644index 000000000..38837807d--- /dev/null+++ b/tools/xerj-code/hub/xerj-columnar.json@@ -0,0 +1,5 @@+{"corpus":"xerj-columnar","cloned_at":"2026-08-07T08:28:36Z","repos":[+ {"repo":"ClickHouse","url":"https://github.com/ClickHouse/ClickHouse","licence":"Apache-2.0","sha":"31081d9f05014003321333553bb3e657eb3da168","files":72754,"bytes":1195576661,+ "review":{"spdx":"Apache-2.0","use":"adapt-with-attribution","by":"xerj-org","at":"2026-08-12",+ "note":"~1.2 GB checkout — by far the largest entry in the hub."}}+]}diff --git a/tools/xerj-code/hub/xerj-search.json b/tools/xerj-code/hub/xerj-search.jsonnew file mode 100644index 000000000..fe68b6940--- /dev/null+++ b/tools/xerj-code/hub/xerj-search.json@@ -0,0 +1,16 @@+{"corpus":"xerj-search","cloned_at":"2026-08-07T08:24:23Z","repos":[+ {"repo":"tantivy","url":"https://github.com/quickwit-oss/tantivy","licence":"MIT","sha":"3a55bc986d1062fce618943c4dbd43d55ca87828","files":527,"bytes":36482562,+ "review":{"spdx":"MIT","use":"adapt-with-attribution","by":"xerj-org","at":"2026-08-12"}},+ {"repo":"quickwit","url":"https://github.com/quickwit-oss/quickwit","licence":"Apache-2.0","sha":"fb99535bccc4a9745840378f6cf77ff839a21fa6","files":1555,"bytes":31824429,+ "review":{"spdx":"Apache-2.0","use":"adapt-with-attribution","by":"xerj-org","at":"2026-08-12",+ "note":"LICENSE is plain Apache-2.0; LICENSE-3rdparty.csv is a dependency inventory, not this project's licence."}},+ {"repo":"meilisearch","url":"https://github.com/meilisearch/meilisearch","licence":"BUSL/MIT","sha":"be181e115792eae868b1b7c0934a2a29b9d2fde7","files":1734,"bytes":54038985,+ "review":{"spdx":"MIT AND BUSL-1.1","use":"mixed","by":"xerj-org","at":"2026-08-12",+ "note":"MIT core, but Enterprise Edition parts are BUSL-1.1 (LICENSE-EE). Check the file's header and path before copying anything."}},+ {"repo":"sonic","url":"https://github.com/valeriansaliou/sonic","licence":"MPL-2.0","sha":"484339e891a5c9f62840990391f0b3251618de22","files":244,"bytes":1680442,+ "review":{"spdx":"MPL-2.0","use":"approach-only","by":"xerj-org","at":"2026-08-12",+ "note":"File-level copyleft. XERJ is Apache-2.0, so read the design and write your own code; do not lift MPL files in."}},+ {"repo":"elasticsearch","url":"https://github.com/elastic/elasticsearch","licence":"AGPL","sha":"ac375eb50ac52fb9438b26bca7cfe9ecd93e60ad","files":46387,"bytes":586728834,+ "review":{"spdx":"AGPL-3.0-only OR SSPL-1.0 OR Elastic-2.0","use":"approach-only","by":"xerj-org","at":"2026-08-12",+ "note":"Triple-licensed; the detector reports only the first (most restrictive) match. Never copy ES code into XERJ — beyond the licence, XERJ's public position is that it shares no code and no architecture with Elasticsearch."}}+]}diff --git a/tools/xerj-code/hub/xerj-storage.json b/tools/xerj-code/hub/xerj-storage.jsonnew file mode 100644index 000000000..5a6fa3093--- /dev/null+++ b/tools/xerj-code/hub/xerj-storage.json@@ -0,0 +1,8 @@+{"corpus":"xerj-storage","cloned_at":"2026-08-06T20:24:00Z","repos":[+ {"repo":"sled","url":"https://github.com/spacejam/sled","licence":"Apache-2.0/MIT","sha":"e449d17111f4a097e1c66b6db241962ccb6a4136","files":70,"bytes":1322994,+ "review":{"spdx":"Apache-2.0 OR MIT","use":"adapt-with-attribution","by":"xerj-org","at":"2026-08-12"}},+ {"repo":"fjall","url":"https://github.com/fjall-rs/fjall","licence":"Apache-2.0/MIT","sha":"7870992c9b61e2110caf5483785a866edd05c921","files":274,"bytes":24173777,+ "review":{"spdx":"Apache-2.0 OR MIT","use":"adapt-with-attribution","by":"xerj-org","at":"2026-08-12"}},+ {"repo":"redb","url":"https://github.com/cberner/redb","licence":"Apache-2.0/MIT","sha":"f551b96f43d36314db076ad38a49c8eb6e8ee311","files":118,"bytes":2060729,+ "review":{"spdx":"Apache-2.0 OR MIT","use":"adapt-with-attribution","by":"xerj-org","at":"2026-08-12"}}+]}diff --git a/tools/xerj-code/hub/xerj-vector.json b/tools/xerj-code/hub/xerj-vector.jsonnew file mode 100644index 000000000..4e2d14b7c--- /dev/null+++ b/tools/xerj-code/hub/xerj-vector.json@@ -0,0 +1,10 @@+{"corpus":"xerj-vector","cloned_at":"2026-08-06T20:23:57Z","repos":[+ {"repo":"qdrant","url":"https://github.com/qdrant/qdrant","licence":"Apache-2.0","sha":"74f3e85b9473c62560006c043e13737ce6b48412","files":2244,"bytes":40487722,+ "review":{"spdx":"Apache-2.0","use":"adapt-with-attribution","by":"xerj-org","at":"2026-08-12"}},+ {"repo":"usearch","url":"https://github.com/unum-cloud/usearch","licence":"Apache-2.0","sha":"cc23bbaf21ef52313c5a495adbc40cbd733cdcfb","files":175,"bytes":2743638,+ "review":{"spdx":"Apache-2.0","use":"adapt-with-attribution","by":"xerj-org","at":"2026-08-12"}},+ {"repo":"instant-distance","url":"https://github.com/instant-labs/instant-distance","licence":"Apache-2.0","sha":"13ea89ac1ca038d19fbbe3c095c1aeddf713f859","files":27,"bytes":300572,+ "review":{"spdx":"Apache-2.0","use":"adapt-with-attribution","by":"xerj-org","at":"2026-08-12"}},+ {"repo":"hnswlib","url":"https://github.com/nmslib/hnswlib","licence":"Apache-2.0","sha":"d9b3608c83d83b46c96e25088cb1d729b29dcfe9","files":64,"bytes":469626,+ "review":{"spdx":"Apache-2.0","use":"adapt-with-attribution","by":"xerj-org","at":"2026-08-12"}}+]}diff --git a/tools/xerj-code/scripts/xc-corpus.sh b/tools/xerj-code/scripts/xc-corpus.shnew file mode 100755index 000000000..1de34704d--- /dev/null+++ b/tools/xerj-code/scripts/xc-corpus.sh@@ -0,0 +1,320 @@+#!/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]+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'")+ # 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=()++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+ 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" || 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+ 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>)"+echo "next: xc-index.sh $name"diff --git a/tools/xerj-code/scripts/xc-index.sh b/tools/xerj-code/scripts/xc-index.shnew file mode 100755index 000000000..f5979a76a--- /dev/null+++ b/tools/xerj-code/scripts/xc-index.sh@@ -0,0 +1,53 @@+#!/usr/bin/env bash+# Index a corpus into the local XERJ instance.+set -euo pipefail++ROOT="${XERJ_CODE_HOME:-$HOME/.xerj-code}"+CORPORA="$ROOT/corpora"+URL="${XERJ_URL:-http://localhost:9200}"+XERJ_BIN="${XERJ_BIN:-xerj}"++[ $# -ge 1 ] || { echo "usage: xc-index.sh <corpus-name> [--fresh]" >&2; exit 2; }+name="$1"; shift+fresh=""+[ "${1:-}" = "--fresh" ] && fresh="--fresh"++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; }++curl -fsS -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; }++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.+set +e+"$XERJ_BIN" autoindex "$dir" \+ --url "$URL" \+ --prefix "xc-$name" \+ --no-graph \+ $fresh+rc=$?+set -e++# Exit 3 is "completed, some files were unparseable" — expected on any real+# repository (binaries, fixtures, vendored blobs). Treat it as success.+case $rc in+ 0) echo "indexed cleanly" ;;+ 3) echo "indexed (exit 3: some files skipped as junk — normal for real repos)" ;;+ *) echo "xc-index: autoindex failed with exit $rc" >&2; exit $rc ;;+esac++mkdir -p "$ROOT/state"+cat > "$ROOT/state/$name.json" <<EOF+{"corpus":"$name","indexed_at":"$(date -u +%Y-%m-%dT%H:%M:%SZ)","prefix":"xc-$name","url":"$URL","autoindex_exit":$rc}+EOF++docs=$(curl -fsS -m 5 "$URL/xc-$name*/_count" 2>/dev/null \+ | sed 's/.*"count":\([0-9]*\).*/\1/' || echo "?")+echo "corpus '$name' searchable: $docs records"+echo "next: xc.py $name \"<what you need>\""diff --git a/tools/xerj-code/scripts/xc.py b/tools/xerj-code/scripts/xc.pynew file mode 100755index 000000000..f0faab395--- /dev/null+++ b/tools/xerj-code/scripts/xc.py@@ -0,0 +1,568 @@+#!/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 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+++def die(msg, code=2):+ print(f"xc: {msg}", file=sys.stderr)+ sys.exit(code)+++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 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. With fatal=False, an HTTP error is returned, not fatal.++ 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:+ msg = e.read()[:200].decode(errors="replace")+ if not fatal:+ return {"_xc_error": f"{e.code}: {msg}"}+ die(f"search failed ({e.code}): {msg}")+ except urllib.error.URLError as e:+ die(f"cannot reach XERJ at {URL}: {e.reason}")+++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"):+ """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.+ """+ req = urllib.request.Request(f"{URL}/{prefix}*/_mapping")+ try:+ with urllib.request.urlopen(req, timeout=30) as resp:+ mapping = json.load(resp)+ except (urllib.error.HTTPError, urllib.error.URLError, ValueError):+ 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"):+ """The vector arm. Returns [] on any error — the caller degrades to BM25."""+ 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=False)+ 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 index under '{prefix}*' maps `body` as "+ f"semantic_text, so the vector arm cannot run")+ sem = semantic_search(capable, query, depth, lang)+ if not sem:+ return bm[:k], (f"BM25 only — the vector arm returned nothing 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 `width`-char slice of `body` densest in query terms, snapped to lines.++ 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+ low = body.lower()+ # 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):+ chunk = low[start:start + width]+ 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+ # Snap to line boundaries so the excerpt is readable code, not a torn line.+ 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)+ 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 main():+ ap = argparse.ArgumentParser(description="retrieve reference passages")+ ap.add_argument("corpus")+ ap.add_argument("query")+ 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.+ ap.add_argument("--full", type=int, metavar="CHARS",+ help="emit up to CHARS of each passage's real source instead of highlights")+ ap.add_argument("--no-symbol", action="store_true",+ help="with --full, 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)")+ args = ap.parse_args()++ state = load_state(args.corpus)+ age = check_fresh(state, args.stale_ok)++ note = None+ if args.mode == "hybrid":+ hits, note = hybrid_search(state["prefix"], args.query, args.k, args.lang)+ res = {"hits": {"hits": hits}}+ elif args.mode == "semantic":+ capable, total = semantic_indices(state["prefix"])+ hits = semantic_search(capable, args.query, args.k, args.lang)+ res = {"hits": {"hits": hits}}+ note = (f"vector only over {len(capable)} of {total} index(es)" if capable+ else f"no index under '{state['prefix']}*' maps `body` as semantic_text")+ else:+ res = search(state["prefix"], 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 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)++ if args.json:+ print(json.dumps(res, indent=1))+ return++ 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:+ frags = []+ for vals in (h.get("highlight") or {}).values():+ frags.extend(vals)+ if frags:+ for f in frags[:2]:+ print(" " + f.replace("\n", "\n ")[:600])+ else:+ body = src.get("body") or ""+ print(" " + str(body)[:400].replace("\n", "\n "))+ if lic in ("GPL", "LGPL"):+ 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.")+++if __name__ == "__main__":+ main()diff --git a/tools/xerj-code/tests/test_xc_corpus.sh b/tools/xerj-code/tests/test_xc_corpus.shnew file mode 100755index 000000000..96e6d1f34--- /dev/null+++ b/tools/xerj-code/tests/test_xc_corpus.sh@@ -0,0 +1,224 @@+#!/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++echo+echo "$pass passed, $fail failed"+[ "$fail" -eq 0 ]diff --git a/tools/xerj-code/tests/validate_manifest.py b/tools/xerj-code/tests/validate_manifest.pynew file mode 100755index 000000000..7a514fc31--- /dev/null+++ b/tools/xerj-code/tests/validate_manifest.py@@ -0,0 +1,86 @@+#!/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}")+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}'")+ 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())