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(hub): publish the record corpora as Corpus Hub v2 hubpacks (#1736)
xerj-org7be465522f5c
diff --git a/.github/workflows/hub-packs.yml b/.github/workflows/hub-packs.ymlindex b17eec9cb..57415dd48 100644--- a/.github/workflows/hub-packs.yml+++ b/.github/workflows/hub-packs.yml@@ -64,8 +64,12 @@# way do not trigger other workflows, so the registry's own validation does not# run on them until a human pushes to the branch or closes and reopens the PR.#-# NOT BUILT HERE: lane-B corpora (harvested pack recipes under tools/packs/) are-# published by pack-publish.yml in the v1 pack format, not as hub packs.+# NOT BUILT HERE: lane-B corpora (record packs from tools/packs/<slug>/recipe.toml).+# pack-publish.yml builds them daily and turns each into a hubpack with+# `xerj hub build-pack --from-pack` (same key, same verify and consumer e2e, same+# `pack-<slug>-<pin8>` release name). Their pin is a CONTENT pin with no manifest+# behind it, so the catalogue job below lists each one's most recently published+# pin (fetch-list --published-at) and check-catalogue checks it against the release.name: hub packs@@ -686,11 +690,14 @@ jobs:GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}run: |set -euo pipefail- gh release list --repo "$GITHUB_REPOSITORY" --limit 5000 --json tagName,isDraft \- --jq '.[] | select(.isDraft | not) | .tagName | select(startswith("pack-"))' \- > "$RUNNER_TEMP/tags.txt"+ # tag<TAB>publishedAt: a record pack's current pin is its newest published one.+ gh release list --repo "$GITHUB_REPOSITORY" --limit 5000 --json tagName,isDraft,publishedAt \+ --jq '.[] | select(.isDraft | not) | select(.tagName | startswith("pack-")) | "\(.tagName)\t\(.publishedAt)"' \+ > "$RUNNER_TEMP/published-at.tsv"+ cut -f1 "$RUNNER_TEMP/published-at.tsv" > "$RUNNER_TEMP/tags.txt"python3 tools/hub-packs/hub_packs.py fetch-list --registry "$REGISTRY" --backlog "$BACKLOG" \- --published-tags "$RUNNER_TEMP/tags.txt" > "$RUNNER_TEMP/fetch.tsv"+ --published-tags "$RUNNER_TEMP/tags.txt" --published-at "$RUNNER_TEMP/published-at.tsv" \+ > "$RUNNER_TEMP/fetch.tsv"# A flat directory, like `hub build-pack --out`. ANY failed download aborts the# job: the catalogue is a complete snapshot, and a missing pack would delist# its corpus.diff --git a/.github/workflows/pack-publish.yml b/.github/workflows/pack-publish.ymlindex 24d025dbf..473d4d5d8 100644--- a/.github/workflows/pack-publish.yml+++ b/.github/workflows/pack-publish.yml@@ -16,6 +16,28 @@## Manual runs welcome: workflow_dispatch built the first release and rebuilds# after a recipe change without waiting for the cron tick.+#+# CORPUS HUB V2 (docs/CORPUS_HUB_V2_IMPLEMENTATION.md §12.1, §12.2)+# The same record packs are also rebuilt as hubpacks (`format_version` 1,+# snapshot layout) by the `hubpack` job: `xerj hub build-pack --from-pack`,+# signed with HUB_SIGNING_SEED and verified against the key clients embed+# (HUB_PUBKEY_HEX), then the §12.3 consumer end-to-end+# (tools/hub-packs/consumer_e2e.sh) — the hub-packs.yml pipeline, step for+# step. A record pack has no commit, so its pin is a CONTENT pin (the first 40+# hex of a sha256 over its record files): unchanged records give the same pin+# and publish nothing new.+#+# The repository VARIABLE RECORD_HUBPACKS stages the switch-over; nothing in+# this file deletes a hubpack release, and retiring the JSON releases means+# only that no NEW ones are published (the existing ones stay):+# unset the hubpack job builds, verifies and runs the consumer e2e, and+# publishes nothing; the JSON jobs run as before.+# publish the hubpack job also publishes `pack-<slug>-<pin8>` releases+# (draft, e2e against the draft's own bytes, then publish); the+# JSON jobs run as before.+# only set once the published hubpacks have verified (12.2): the JSON+# jobs are skipped — no JSON release is built, published or+# retired — and the hubpacks are the only releases.name: pack publish@@ -38,6 +60,8 @@ concurrency:jobs:rust-vulns:name: build + sign + publish rust-vulns+ # 12.2: retired (no new JSON release) once RECORD_HUBPACKS is `only`.+ if: vars.RECORD_HUBPACKS != 'only'runs-on: ubuntu-latesttimeout-minutes: 45steps:@@ -233,6 +257,8 @@ jobs:agent-session-trajectories:name: build + sign + publish agent-session-trajectories+ # 12.2: retired (no new JSON release) once RECORD_HUBPACKS is `only`.+ if: vars.RECORD_HUBPACKS != 'only'runs-on: ubuntu-latesttimeout-minutes: 45steps:@@ -405,3 +431,254 @@ jobs:[ -n "$tag" ] && gh release delete "$tag" \--repo "$GITHUB_REPOSITORY" --cleanup-tag --yesdone++ # ── the same record packs as Corpus Hub v2 hubpacks (§12.1) ────────────────+ hubpack:+ name: hubpack ${{ matrix.slug }}+ runs-on: ubuntu-latest+ timeout-minutes: 60+ strategy:+ fail-fast: false+ matrix:+ slug: [rust-vulns, agent-session-trajectories]+ env:+ SLUG: ${{ matrix.slug }}+ PUBLISH: ${{ vars.RECORD_HUBPACKS == 'publish' || vars.RECORD_HUBPACKS == 'only' }}+ # consumer_e2e.sh builds its one-entry catalogue from the registry, which+ # lives on corpus-hub (checked out below).+ REGISTRY: registry-src/tools/xerj-code/hub+ BACKLOG: registry-src/tools/xerj-code/hub/backlog/backlog-100.json+ BUILDER_PORT: "19200"+ steps:+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0+ with:+ persist-credentials: false++ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0+ with:+ ref: corpus-hub+ path: registry-src+ persist-credentials: false+ sparse-checkout: tools/xerj-code/hub++ # The hub-packs.yml preflight: a key clients embed, and a secret that is its+ # private half. Without the key this job is dormant (a notice, not a failure).+ - name: Hub key and secret in place?+ id: key+ env:+ HUB_SIGNING_SEED: ${{ secrets.HUB_SIGNING_SEED }}+ run: |+ set -euo pipefail+ pub=$(sed -n 's/^pub const HUB_PUBKEY_HEX: &str = "\([0-9a-fA-F]*\)";.*/\1/p' \+ engine/crates/xerj-common/src/hub.rs | head -n 1 | tr 'A-F' 'a-f')+ if [ -z "$pub" ]; then+ echo "::notice title=hubpack dormant::HUB_PUBKEY_HEX is empty on this branch"+ echo "ready=false" >> "$GITHUB_OUTPUT"; exit 0+ fi+ if [ -z "$HUB_SIGNING_SEED" ]; then+ echo "::error title=hubpack::HUB_PUBKEY_HEX is set but the HUB_SIGNING_SEED secret is not"+ exit 1+ fi+ umask 077+ printf '%s' "$HUB_SIGNING_SEED" > "$RUNNER_TEMP/k"+ derived=$(bash tools/hub-packs/ed25519.sh derive "$RUNNER_TEMP/k"); rm -f "$RUNNER_TEMP/k"+ if [ "$derived" != "$pub" ]; then+ echo "::error title=hubpack::the HUB_SIGNING_SEED secret does not match HUB_PUBKEY_HEX"+ exit 1+ fi+ echo "HUB_PUBKEY_HEX=$pub" >> "$GITHUB_ENV"+ echo "ready=true" >> "$GITHUB_OUTPUT"++ - uses: dtolnay/rust-toolchain@stable+ if: steps.key.outputs.ready == 'true'++ - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2+ if: steps.key.outputs.ready == 'true'+ with:+ workspaces: engine++ - name: Build the xerj binary+ if: steps.key.outputs.ready == 'true'+ working-directory: engine+ run: cargo build --profile ci-test -p xerj-server++ # The record pack, exactly as the JSON jobs build it (same recipe, same+ # binary). It is the input, not an artifact: nothing here publishes it.+ - name: Build the record pack+ if: steps.key.outputs.ready == 'true'+ env:+ XERJ_CODE_HOME: ${{ github.workspace }}/.pack-home+ run: |+ engine/target/ci-test/xerj corpus build "$SLUG" \+ --recipe "tools/packs/$SLUG/recipe.toml"+ echo "RECORD_PACK=$XERJ_CODE_HOME/builds/$SLUG/pack/$SLUG" >> "$GITHUB_ENV"++ - name: Start a throwaway builder node+ if: steps.key.outputs.ready == 'true'+ run: |+ set -euo pipefail+ NODE="$RUNNER_TEMP/node"+ mkdir -p "$NODE/data" "$RUNNER_TEMP/pack-out"+ OUT="$(realpath "$RUNNER_TEMP/pack-out")"+ printf '[limits]\nsnapshot_repo_allowlist = ["%s"]\n' "$OUT" > "$NODE/config.toml"+ engine/target/ci-test/xerj --insecure --bind 127.0.0.1 --port "$BUILDER_PORT" \+ --data-dir "$NODE/data" --config "$NODE/config.toml" > "$NODE/node.log" 2>&1 &+ echo "NODE_PID=$!" >> "$GITHUB_ENV"+ echo "PACK_OUT=$OUT" >> "$GITHUB_ENV"+ for _ in $(seq 1 120); do+ if curl -fs -m1 "http://127.0.0.1:$BUILDER_PORT/_cluster/health" >/dev/null 2>&1; then+ echo "builder node is up"; exit 0+ fi+ sleep 0.5+ done+ echo "the builder node did not become healthy"; cat "$NODE/node.log"; exit 1++ - name: Build and sign the hubpack+ if: steps.key.outputs.ready == 'true'+ env:+ HUB_SIGNING_SEED: ${{ secrets.HUB_SIGNING_SEED }}+ XERJ_CODE_HOME: ${{ runner.temp }}/code-home+ run: |+ set -euo pipefail+ umask 077+ printf '%s' "$HUB_SIGNING_SEED" > "$RUNNER_TEMP/pack.key"+ unset HUB_SIGNING_SEED+ trap 'rm -f "$RUNNER_TEMP/pack.key"' EXIT+ engine/target/ci-test/xerj hub build-pack "$SLUG" --from-pack "$RECORD_PACK" \+ --out "$PACK_OUT" --url "http://127.0.0.1:$BUILDER_PORT" \+ --sign-key "$RUNNER_TEMP/pack.key" | tee "$RUNNER_TEMP/build.txt"+ # Last stdout line: `pack <slug> <pin8> <bytes> <indices> <defs>`+ read -r tag slug pin8 bytes indices defs < <(tail -n 1 "$RUNNER_TEMP/build.txt")+ if [ "$tag" != "pack" ] || [ "$slug" != "$SLUG" ]; then+ echo "::error::the builder reported '$tag $slug' but this job builds $SLUG"; exit 1+ fi+ echo "PIN8=$pin8" >> "$GITHUB_ENV"+ echo "built $slug $pin8: $bytes bytes, $indices indices, $defs definitions"++ - name: Verify the signature and the layout+ if: steps.key.outputs.ready == 'true'+ run: |+ set -euo pipefail+ ARCHIVE="$PACK_OUT/$SLUG-$PIN8.hubpack.tar.zst"+ test -s "$ARCHIVE"; test -s "$ARCHIVE.sig"+ bash tools/hub-packs/ed25519.sh verify "$HUB_PUBKEY_HEX" "$ARCHIVE" "$ARCHIVE.sig"+ zstd -dc "$ARCHIVE" | tar -tf - | sort > "$RUNNER_TEMP/members.txt"+ for m in pack.json SHA256SUMS defs.jsonl files.jsonl; do+ grep -qx "$m" "$RUNNER_TEMP/members.txt" || { echo "::error::the archive lacks $m"; exit 1; }+ done+ grep -q '^snapshot/' "$RUNNER_TEMP/members.txt" || { echo "::error::the archive lacks snapshot/"; exit 1; }+ zstd -dc "$ARCHIVE" | tar -xOf - pack.json | jq -e --arg slug "$SLUG" --arg pin8 "$PIN8" \+ '.format_version == 1 and .slug == $slug and (.pin_sha | startswith($pin8))' >/dev/null+ echo "layout ok: $(wc -l < "$RUNNER_TEMP/members.txt") members"++ # A content pin that already has a published release means the records did+ # not change since: there is nothing new to publish.+ - name: Is this pin already released?+ if: steps.key.outputs.ready == 'true'+ env:+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}+ run: |+ set -euo pipefail+ if gh release list --repo "$GITHUB_REPOSITORY" --limit 5000 --json tagName,isDraft \+ --jq '.[] | select(.isDraft | not) | .tagName' \+ | grep -qxE "pack-$SLUG-$PIN8(-r[0-9]+)?"; then+ echo "::notice title=hubpack $SLUG::pin $PIN8 is already released (records unchanged); nothing to publish"+ echo "RELEASED=true" >> "$GITHUB_ENV"+ else+ echo "RELEASED=false" >> "$GITHUB_ENV"+ fi++ - name: Pick an unused release tag+ if: steps.key.outputs.ready == 'true' && env.PUBLISH == 'true' && env.RELEASED == 'false'+ env:+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}+ run: |+ set -euo pipefail+ BASE="pack-$SLUG-$PIN8"+ TAG="$BASE"; N=1+ while gh release view "$TAG" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1 \+ || gh api "repos/$GITHUB_REPOSITORY/git/ref/tags/$TAG" >/dev/null 2>&1; do+ N=$((N + 1)); TAG="$BASE-r$N"+ done+ echo "PACK_TAG=$TAG" >> "$GITHUB_ENV"++ - name: Upload the hubpack to a draft release+ if: steps.key.outputs.ready == 'true' && env.PUBLISH == 'true' && env.RELEASED == 'false'+ env:+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}+ run: |+ set -euo pipefail+ ARCHIVE="$PACK_OUT/$SLUG-$PIN8.hubpack.tar.zst"+ zstd -dc "$ARCHIVE" | tar -xOf - pack.json > "$RUNNER_TEMP/pack.json"+ {+ echo "Pre-indexed, signed Corpus Hub v2 pack for the \`$SLUG\` record corpus."+ echo+ jq -r '"- content pin: `\(.pin_sha)` (records of \(.pin_date))\n- licence: \(.licence_spdx) (\(.licence_class))\n- definitions: \(.defs_count), files: \(.files_count)\n- built by: \(.builder_version)"' "$RUNNER_TEMP/pack.json"+ echo+ echo "Use it: \`xerj hub pull $SLUG\`. The archive is checked against the hub key (sha256, then ed25519 signature) before anything is extracted."+ echo+ echo "Built by $GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID from tools/packs/$SLUG/recipe.toml"+ } > "$RUNNER_TEMP/notes.md"+ gh release create "$PACK_TAG" "$ARCHIVE" "$ARCHIVE.sig" --repo "$GITHUB_REPOSITORY" \+ --draft --prerelease --latest=false --target "$GITHUB_SHA" \+ --title "hub pack: $SLUG @ $PIN8" --notes-file "$RUNNER_TEMP/notes.md"++ # §12.3 before anything is published: a fresh node, an empty HOME, `hub pull`+ # through a signed one-entry catalogue, one --def from the pack's own+ # defs.jsonl and one question. A publishing run tests the DRAFT's bytes.+ - name: Consumer end-to-end (pull, --def, one question)+ if: steps.key.outputs.ready == 'true'+ env:+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}+ HUB_SIGNING_SEED: ${{ secrets.HUB_SIGNING_SEED }}+ run: |+ set -euo pipefail+ FILE="$SLUG-$PIN8.hubpack.tar.zst"+ SRC="$RUNNER_TEMP/e2e-src"; mkdir -p "$SRC"+ if [ "$PUBLISH" = "true" ] && [ "$RELEASED" = "false" ]; then+ TAG="$PACK_TAG"+ gh release download "$TAG" --repo "$GITHUB_REPOSITORY" --dir "$SRC" \+ --pattern "$FILE" --pattern "$FILE.sig"+ cmp "$SRC/$FILE" "$PACK_OUT/$FILE"+ cmp "$SRC/$FILE.sig" "$PACK_OUT/$FILE.sig"+ else+ TAG="pack-$SLUG-$PIN8"+ cp "$PACK_OUT/$FILE" "$PACK_OUT/$FILE.sig" "$SRC/"+ fi+ umask 077+ printf '%s' "$HUB_SIGNING_SEED" > "$RUNNER_TEMP/e2e.key"+ unset HUB_SIGNING_SEED+ trap 'rm -f "$RUNNER_TEMP/e2e.key"' EXIT+ bash tools/hub-packs/consumer_e2e.sh engine/target/ci-test/xerj "$SLUG" "$PIN8" "$TAG" "$SRC" \+ "$RUNNER_TEMP/e2e.key" | tee "$RUNNER_TEMP/e2e.txt"+ { echo "### hubpack consumer e2e: $SLUG @ $PIN8"; echo; sed 's/^/ /' "$RUNNER_TEMP/e2e.txt"; } >> "$GITHUB_STEP_SUMMARY"++ - name: Publish the draft (retag past a burned tag if refused)+ if: steps.key.outputs.ready == 'true' && env.PUBLISH == 'true' && env.RELEASED == 'false'+ env:+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}+ run: |+ set -euo pipefail+ if gh release edit "$PACK_TAG" --repo "$GITHUB_REPOSITORY" --draft=false; then+ echo "published $PACK_TAG"; exit 0+ fi+ RELID=$(gh api "repos/$GITHUB_REPOSITORY/releases?per_page=100" --paginate \+ --jq ".[] | select(.draft and .tag_name == \"$PACK_TAG\") | .id" | head -n 1 || true)+ if [ -z "$RELID" ]; then+ echo "::error::publish refused and no draft named $PACK_TAG found"; exit 1+ fi+ N=1; NEW="$PACK_TAG"+ while gh release view "$NEW" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1 \+ || gh api "repos/$GITHUB_REPOSITORY/git/ref/tags/$NEW" >/dev/null 2>&1; do+ N=$((N + 1)); NEW="$PACK_TAG-r$N"+ done+ gh api -X PATCH "repos/$GITHUB_REPOSITORY/releases/$RELID" -f tag_name="$NEW" -F draft=false+ echo "published $NEW"++ - name: Builder node log (on failure)+ if: failure()+ run: tail -n 100 "$RUNNER_TEMP/node/node.log" || true++ - name: Stop the builder node+ if: always()+ run: kill "${NODE_PID:-}" 2>/dev/null || truediff --git a/engine/crates/xerj-hub/src/build_catalogue.rs b/engine/crates/xerj-hub/src/build_catalogue.rsindex 03817fa52..a437c76f7 100644--- a/engine/crates/xerj-hub/src/build_catalogue.rs+++ b/engine/crates/xerj-hub/src/build_catalogue.rs@@ -17,12 +17,18 @@//! is not the private half of [`xerj_common::hub::HUB_PUBKEY_HEX`] fails here//! instead of publishing a catalogue no client can load.//!+//! Live lane-B corpora (record packs, `build-pack --from-pack`) have no+//! registry manifest and no commit pin: their entry comes from the backlog row+//! and the pack's own signed `pack.json`, and their current pin is the newest+//! verified pack for the slug in `--packs` (see [`record_entries`]).+//!//! `quality_grade` comes only from the graded G7 suites in//! `<registry>/backlog/*graded*.json`, read exactly as the hub site generator//! reads them (`tools/corpus-hub-site/gen.py` `parse_graded_suites` and//! `g7_badge`), so the catalogue and the corpus page show the same grade. A-//! corpus with no graded suite gets `None`: the field's contract is "never-//! invent one" (see [`read_graded_suites`]).+//! lane-A corpus with no graded suite gets `None`, and a lane-B record pack+//! always does: the field's contract is "never invent one" (see+//! [`read_graded_suites`]).use std::collections::{BTreeMap, HashSet};use std::fs;@@ -33,8 +39,10 @@ use anyhow::{anyhow, bail, Context, Result};use serde_json::Value;use sha2::{Digest, Sha256};-use xerj_autoindex::harvest::sign::verify_bytes;-use xerj_common::hub::{Catalogue, DefRecord, PackManifest, PACK_FORMAT_VERSION};+use xerj_autoindex::harvest::sign::{sign_bytes, verify_bytes};+use xerj_common::hub::{+ Catalogue, CatalogueEntry, DefRecord, LicenceClass, PackManifest, PACK_FORMAT_VERSION,+};use crate::catalogue::{build_catalogue, canonical_json, CorpusBuildInput};use crate::pack::PackFileEntry;@@ -366,7 +374,8 @@ pub fn build(opts: &Options, seed_hex: &str, pubkey_hex: &str) -> Result<Built>ask_for: backlog_domain.to_string(),});}- if inputs.is_empty() {+ let records = record_entries(opts, rows, pubkey_hex, &mut used, &mut without_pack)?;+ if inputs.is_empty() && records.is_empty() {bail!("no live corpus has a pack for its current pin in {}",opts.packs.display()@@ -384,7 +393,12 @@ pub fn build(opts: &Options, seed_hex: &str, pubkey_hex: &str) -> Result<Built>}unmatched.sort();- let (catalogue, sig_hex) = build_catalogue(&inputs, &opts.generated_at, seed_hex)?;+ let (mut catalogue, mut sig_hex) = build_catalogue(&inputs, &opts.generated_at, seed_hex)?;+ if !records.is_empty() {+ catalogue.corpora.extend(records);+ catalogue.corpora.sort_by(|a, b| a.slug.cmp(&b.slug));+ sig_hex = sign_bytes(&canonical_json(&catalogue)?, seed_hex).context("sign catalogue")?;+ }let bytes = canonical_json(&catalogue)?;verify_bytes(&bytes, &sig_hex, pubkey_hex).context("the catalogue's signature does not verify under the hub key this build embeds: the \@@ -470,6 +484,135 @@ pub fn read_graded_suites(backlog_dir: &Path) -> Result<BTreeMap<String, String>Ok(out)}+/// One entry per LIVE lane-B corpus (a record pack built by `hub build-pack+/// --from-pack`) with a pack in `--packs`. A record pack's pin is a content+/// pin, not a registry fact, so its current pack is the newest one for the+/// slug in `--packs` (by `pack.json` `built_at`); the catalogue job downloads+/// the record packs' published releases for it to choose from. Every candidate+/// is verified like a lane-A pack; a failure aborts. Fields: slug, pin, licence+/// and sources from the signed `pack.json`; domain, refresh, `ask_for` and+/// `topics` from the backlog row.+fn record_entries(+ opts: &Options,+ rows: &[Value],+ pubkey_hex: &str,+ used: &mut HashSet<String>,+ without_pack: &mut Vec<String>,+) -> Result<Vec<CatalogueEntry>> {+ let mut names: Vec<String> = Vec::new();+ for entry in+ fs::read_dir(&opts.packs).with_context(|| format!("list {}", opts.packs.display()))?+ {+ names.push(entry?.file_name().to_string_lossy().into_owned());+ }+ names.sort();+ let mut out = Vec::new();+ for row in rows {+ let field = |k: &str| row.get(k).and_then(Value::as_str).unwrap_or("");+ if field("status") != "live" || field("lane") != "B" {+ continue;+ }+ let slug = field("slug");+ let mut best: Option<(String, PackFacts)> = None;+ for name in &names {+ let Some(pin8) = name+ .strip_prefix(&format!("{slug}-"))+ .and_then(|r| r.strip_suffix(".hubpack.tar.zst"))+ else {+ continue;+ };+ if pin8.len() != 8 || !pin8.chars().all(|c| matches!(c, '0'..='9' | 'a'..='f')) {+ continue;+ }+ let pack = read_pack(&opts.packs.join(name), pubkey_hex)+ .with_context(|| format!("pack {name}"))?;+ if pack.manifest.slug != slug {+ bail!(+ "{name}: pack.json names slug '{}', not '{slug}'",+ pack.manifest.slug+ );+ }+ if !pack.manifest.pin_sha.starts_with(pin8) {+ bail!(+ "{name}: pack.json pin {} does not start with the file's {pin8}",+ pack.manifest.pin_sha+ );+ }+ used.insert(name.clone());+ let newer = match &best {+ Some((_, b)) => pack.manifest.built_at > b.manifest.built_at,+ None => true,+ };+ if newer {+ best = Some((name.clone(), pack));+ }+ }+ let Some((file, pack)) = best else {+ without_pack.push(slug.to_string());+ continue;+ };+ if pack.manifest.licence_class == LicenceClass::Excluded {+ // Plan §12.1: an excluded licence gets no listing.+ continue;+ }+ let pin8 = &pack.manifest.pin_sha[..8];+ let ask_for = field("domain").trim().to_string();+ let topics: Vec<String> = row+ .pointer("/tags/topics")+ .and_then(Value::as_array)+ .map(|a| {+ a.iter()+ .filter_map(Value::as_str)+ .map(str::to_string)+ .collect()+ })+ .unwrap_or_default();+ let mut terms: Vec<String> = Vec::new();+ let mut push = |t: &str| {+ if !t.is_empty() {+ terms.push(t.to_string());+ terms.push(t.to_lowercase());+ }+ };+ for d in &pack.defs {+ push(&d.symbol);+ }+ for f in &pack.files {+ for comp in f.path.split('/') {+ push(strip_extension(comp));+ }+ }+ for text in std::iter::once(ask_for.as_str()).chain(topics.iter().map(String::as_str)) {+ terms.extend(words(text));+ }+ let tag = opts+ .tags+ .get(&(slug.to_string(), pin8.to_string()))+ .cloned()+ .unwrap_or_else(|| format!("pack-{slug}-{pin8}"));+ let pack_url = format!("{}/{tag}/{file}", opts.release_base.trim_end_matches('/'));+ out.push(CatalogueEntry {+ slug: slug.to_string(),+ domain: field("cat").to_string(),+ topics,+ ask_for,+ pin_sha: pack.manifest.pin_sha.clone(),+ pin_date: pack.manifest.pin_date.clone(),+ refresh_cadence_days: cadence_days(field("refresh")),+ licence_spdx: pack.manifest.licence_spdx.clone(),+ licence_class: pack.manifest.licence_class,+ pack_bytes: pack.bytes,+ sig_url: format!("{pack_url}.sig"),+ pack_url,+ pack_sha256: pack.sha256,+ dependency_names: Vec::new(),+ quality_grade: None,+ term_sketch: crate::sketch::build(terms),+ });+ }+ Ok(out)+}+/// gen.py `suite_median`: relevant-of-5 from the per-query verdicts, or/// `None` when no query carries a gradable verdict.fn suite_median(queries: &Value) -> Option<f64> {@@ -823,6 +966,130 @@ mod tests {assert!(json.contains(r#""quality_grade":"G7 3.1/5""#), "{json}");}+ /// Adds a live lane-B record corpus `rv` to the fixture's backlog and writes+ /// a signed record hubpack for it per `(pin, built_at)`.+ fn add_record_corpus(opts: &Options, seed: &str, packs: &[(&str, &str)]) {+ let mut backlog: Value =+ serde_json::from_str(&fs::read_to_string(&opts.backlog).unwrap()).unwrap();+ backlog["corpora"]+ .as_array_mut()+ .unwrap()+ .push(serde_json::json!({+ "slug": "rv", "status": "live", "lane": "B", "cat": "SEC", "refresh": "daily",+ "domain": "an agent reviewing Rust code queries this for vulnerability precedent",+ "tags": { "topics": ["vulnerabilities"] }+ }));+ fs::write(&opts.backlog, backlog.to_string()).unwrap();+ let snap = opts.packs.parent().unwrap().join("snap");+ for (pin, built_at) in packs {+ let mut m = manifest("rv", pin);+ m.built_at = built_at.to_string();+ m.licence_spdx = "CC0-1.0".into();+ let defs = vec![DefRecord {+ symbol: format!("RUSTSEC-{}", &pin[..4]),+ kind: "record".into(),+ lang: String::new(),+ file: "rustsec/records.jsonl".into(),+ line: 1,+ text: "x".into(),+ value: None,+ }];+ let files = vec![PackFileEntry {+ path: "rustsec/records.jsonl".into(),+ lang: String::new(),+ bytes: 10,+ licence: "CC0-1.0".into(),+ }];+ write_pack(+ &opts.packs.join(format!("rv-{}.hubpack.tar.zst", &pin[..8])),+ &m,+ &defs,+ &files,+ &snap,+ seed,+ )+ .unwrap();+ }+ }++ #[test]+ fn a_live_record_corpus_is_listed_at_its_newest_verified_pack() {+ let tmp = tempfile::tempdir().unwrap();+ let (seed, public) = generate_keypair().unwrap();+ let opts = fixture(tmp.path(), &seed);+ let old = "1111aaaa1111aaaa1111aaaa1111aaaa1111aaaa";+ let new = "2222bbbb2222bbbb2222bbbb2222bbbb2222bbbb";+ add_record_corpus(+ &opts,+ &seed,+ &[(old, "2026-10-16T04:30:00Z"), (new, "2026-10-17T04:30:00Z")],+ );+ let built = build(&opts, &seed, &public).unwrap();+ let slugs: Vec<&str> = built+ .catalogue+ .corpora+ .iter()+ .map(|e| e.slug.as_str())+ .collect();+ assert_eq!(slugs, ["lz4", "rv"], "sorted, both lanes");+ let e = &built.catalogue.corpora[1];+ assert_eq!(e.pin_sha, new);+ assert_eq!(+ e.pack_url,+ "https://github.com/xerj-org/xerj/releases/download/pack-rv-2222bbbb/rv-2222bbbb.hubpack.tar.zst"+ );+ assert_eq!(e.domain, "SEC");+ assert_eq!(e.refresh_cadence_days, 1);+ assert_eq!(e.topics, ["vulnerabilities"]);+ assert!(e.ask_for.contains("vulnerability precedent"));+ assert_eq!(e.licence_spdx, "CC0-1.0");+ assert_eq!(e.quality_grade, None);+ assert!(sketch::contains(&e.term_sketch, "RUSTSEC-2222"));+ assert!(sketch::contains(&e.term_sketch, "rustsec"));+ assert!(built.unmatched.is_empty(), "{:?}", built.unmatched);+ // The signature covers the merged list.+ verify_bytes(&built.bytes, &built.sig_hex, &public).unwrap();+ assert_eq!(built.bytes, canonical_json(&built.catalogue).unwrap());+ }++ #[test]+ fn a_record_pack_whose_pin_disagrees_with_its_file_name_is_refused() {+ let tmp = tempfile::tempdir().unwrap();+ let (seed, public) = generate_keypair().unwrap();+ let opts = fixture(tmp.path(), &seed);+ add_record_corpus(+ &opts,+ &seed,+ &[("3333cccc3333cccc3333cccc3333cccc3333cccc", "x")],+ );+ fs::rename(+ opts.packs.join("rv-3333cccc.hubpack.tar.zst"),+ opts.packs.join("rv-4444dddd.hubpack.tar.zst"),+ )+ .unwrap();+ fs::rename(+ opts.packs.join("rv-3333cccc.hubpack.tar.zst.sig"),+ opts.packs.join("rv-4444dddd.hubpack.tar.zst.sig"),+ )+ .unwrap();+ let err = format!("{:#}", build(&opts, &seed, &public).err().unwrap());+ assert!(+ err.contains("does not start with the file's 4444dddd"),+ "{err}"+ );+ }++ #[test]+ fn a_live_record_corpus_without_a_pack_is_reported_not_invented() {+ let tmp = tempfile::tempdir().unwrap();+ let (seed, public) = generate_keypair().unwrap();+ let opts = fixture(tmp.path(), &seed);+ add_record_corpus(&opts, &seed, &[]);+ let built = build(&opts, &seed, &public).unwrap();+ assert_eq!(built.catalogue.corpora.len(), 1);+ assert_eq!(built.without_pack, ["zstd", "rv"]);+ }+#[test]fn a_retag_from_the_tags_file_and_a_custom_base_shape_the_url() {let tmp = tempfile::tempdir().unwrap();diff --git a/engine/crates/xerj-hub/src/cli.rs b/engine/crates/xerj-hub/src/cli.rsindex 518f48c68..c257fd474 100644--- a/engine/crates/xerj-hub/src/cli.rs+++ b/engine/crates/xerj-hub/src/cli.rs@@ -29,6 +29,7 @@ use std::time::Duration;use anyhow::{anyhow, bail, Context, Result};use serde_json::{json, Value};+use sha2::{Digest, Sha256};use xerj_common::hub::{render, Answer, CatalogueEntry, LicenceClass, PackIndex, PackManifest, PackSource,@@ -49,6 +50,10 @@ const HUB_USAGE: &str = "usage: xerj hub <command>build-pack <slug> --registry <dir> --out <dir> --url <node> --sign-key <seed-file>Build a signed, pre-indexed pack from a registry manifest (CI).+ build-pack <slug> --from-pack <dir> --out <dir> --url <node> --sign-key <seed-file>+ The same, from a record pack `xerj corpus build` made (rust-vulns,+ agent-session-trajectories): its pin is the first 40 hex of a sha256+ over its record files, so the same records give the same pin.build-catalogue --registry <dir> --packs <dir> --out <file> --sign-key <seed-file>Build and sign the catalogue from verified packs (CI; see -h).sync [--url <node>] | sync --install-timer@@ -122,6 +127,7 @@ pub fn run_hub_cli(args: &[String]) -> i32 {fn run_build_pack(args: &[String]) -> i32 {let mut slug: Option<String> = None;let mut registry: Option<String> = None;+ let mut from_pack: Option<String> = None;let mut out: Option<String> = None;let mut url: Option<String> = None;let mut sign_key: Option<String> = None;@@ -147,6 +153,7 @@ fn run_build_pack(args: &[String]) -> i32 {return 0;}"--registry" => registry = Some(val!("--registry")),+ "--from-pack" => from_pack = Some(val!("--from-pack")),"--out" => out = Some(val!("--out")),"--url" => url = Some(val!("--url")),"--sign-key" => sign_key = Some(val!("--sign-key")),@@ -169,16 +176,32 @@ fn run_build_pack(args: &[String]) -> i32 {// It must never fall through to resolve_url's localhost:9200 default — the// builder clones + indexes + snapshots into the node it is handed, and a// silent default would mutate whatever shared node happens to answer there.- let (Some(slug), Some(registry), Some(out), Some(sign_key), Some(url)) =- (slug, registry, out, sign_key, url)- else {+ let source = match (registry, from_pack) {+ (Some(r), None) => BuildSource::Registry(r),+ (None, Some(p)) => BuildSource::RecordPack(p),+ (Some(_), Some(_)) => {+ eprintln!(+ "xerj hub build-pack: --registry and --from-pack name two different sources; \+ pass one\n\n{HUB_USAGE}"+ );+ return 2;+ }+ (None, None) => {+ eprintln!(+ "xerj hub build-pack: <slug>, --registry (or --from-pack), --out, --url and \+ --sign-key are all required\n\n{HUB_USAGE}"+ );+ return 2;+ }+ };+ let (Some(slug), Some(out), Some(sign_key), Some(url)) = (slug, out, sign_key, url) else {eprintln!(- "xerj hub build-pack: <slug>, --registry, --out, --url and --sign-key are all \- required\n\n{HUB_USAGE}"+ "xerj hub build-pack: <slug>, --registry (or --from-pack), --out, --url and \+ --sign-key are all required\n\n{HUB_USAGE}");return 2;};- match build_pack(&slug, ®istry, &out, &url, &sign_key) {+ match build_pack(&slug, &source, &out, &url, &sign_key) {Ok(summary) => {println!("{summary}");0@@ -192,9 +215,17 @@ fn run_build_pack(args: &[String]) -> i32 {/// Build the pack and return the one-line summary `pack <slug> <pin8> <bytes>/// <indices> <defs>` (plan §2 step 6).+/// What `build-pack` builds from.+enum BuildSource {+ /// `--registry <dir>`: the git manifest `<dir>/<slug>.json`.+ Registry(String),+ /// `--from-pack <dir>`: a record pack (`xerj corpus build` output).+ RecordPack(String),+}+fn build_pack(slug: &str,- registry: &str,+ source: &BuildSource,out: &str,url: &str,sign_key_file: &str,@@ -203,25 +234,38 @@ fn build_pack(.with_context(|| format!("read sign key {sign_key_file}"))?.trim().to_string();- let manifest_path = Path::new(registry).join(format!("{slug}.json"));- if !manifest_path.is_file() {- bail!("no registry manifest at {}", manifest_path.display());- }// 1. Licence, pin and sources — from the EXISTING parsers (no second parser// for the registry manifest, plan §11): `read_hub_manifest` for the// per-repo sources, and the catalogue builder for the restrictive-first- // licence class + pin date it already computes.- let meta = resolve_pack_metadata(&manifest_path, &seed)- .with_context(|| format!("read licence/pin from {}", manifest_path.display()))?;+ // licence class + pin date it already computes. A record pack's come from+ // its own verified manifest (`harvest::pack::read_manifest`).+ let (meta, add_from) = match source {+ BuildSource::Registry(registry) => {+ let manifest_path = Path::new(registry).join(format!("{slug}.json"));+ if !manifest_path.is_file() {+ bail!("no registry manifest at {}", manifest_path.display());+ }+ let meta = resolve_pack_metadata(&manifest_path, &seed)+ .with_context(|| format!("read licence/pin from {}", manifest_path.display()))?;+ (meta, manifest_path)+ }+ BuildSource::RecordPack(dir) => {+ let dir = PathBuf::from(dir);+ let meta = record_pack_metadata(&dir, slug)+ .with_context(|| format!("read record pack {}", dir.display()))?;+ (meta, dir)+ }+ };let pin8 = pin8_of(&meta.pin_sha)?;- // 2. Clone + index into the builder node (the SAME lifecycle the CLI runs).+ // 2. Clone (or materialize the records) + index into the builder node (the+ // SAME lifecycle the CLI runs).let rc = xerj_autoindex::xc::run_corpus_cli(&["add".into(),slug.into(),"--from".into(),- manifest_path.to_string_lossy().into_owned(),+ add_from.to_string_lossy().into_owned(),]);if rc != 0 {bail!("`corpus add` failed (exit {rc})");@@ -253,8 +297,11 @@ fn build_pack(.filter(|s| !s.is_empty()).unwrap_or_else(|| overall_licence.clone())};- let (defs, files) = pack::build_defs_and_files(&corpus_root, &licence_of)- .with_context(|| format!("extract defs from {}", corpus_root.display()))?;+ let (defs, files) = match source {+ BuildSource::Registry(_) => pack::build_defs_and_files(&corpus_root, &licence_of),+ BuildSource::RecordPack(_) => pack::record_defs_and_files(&corpus_root, &licence_of),+ }+ .with_context(|| format!("extract defs from {}", corpus_root.display()))?;// 4. Build + index the `-defs` index (plan §3 mapping) on the builder node.let node = HubNode::connect_with_key(url, None)?;@@ -372,6 +419,95 @@ fn resolve_pack_metadata(manifest_path: &Path, seed: &str) -> Result<PackMetadat})}+/// Pack metadata for a record pack (`xerj corpus build` output), from its own+/// manifest after `harvest::pack::read_manifest` has re-hashed every file+/// SHA256SUMS names.+///+/// - pin: a record pack has no commit, so its pin is a CONTENT pin: the first+/// 40 hex of sha256 over `"<file> <sha256>\n"` for each record file, in name+/// order. The same records give the same pin whatever the build date, and a+/// changed record gives a new one (the hub's release-per-pin rule then+/// applies unchanged). 40 hex keeps every pin the same shape.+/// - pin_date: the pack's `created_at` date.+/// - licence: each source's recorded SPDX; the class from the repo's one+/// licence policy (`xccode::licence::is_restricted`, which also counts+/// UNKNOWN as restricted). A source with no licence is refused.+fn record_pack_metadata(dir: &Path, slug: &str) -> Result<PackMetadata> {+ let meta = xerj_autoindex::harvest::pack::read_manifest(dir)?;+ if meta.name != slug {+ bail!("the pack is '{}', not '{slug}'", meta.name);+ }+ let raw: Value = serde_json::from_str(+ &fs::read_to_string(dir.join("manifest.json")).context("read manifest.json")?,+ )+ .context("parse manifest.json")?;+ let mut listing = String::new();+ for f in &meta.files {+ // read_manifest checked each of these is 64 hex and matches the bytes.+ let sha = raw+ .pointer(&format!(+ "/files/{}/sha256",+ f.name.replace('~', "~0").replace('/', "~1")+ ))+ .and_then(Value::as_str)+ .ok_or_else(|| anyhow!("manifest.json lists no sha256 for {}", f.name))?;+ listing.push_str(&format!("{} {sha}\n", f.name));+ }+ if meta.files.is_empty() {+ bail!("the pack has no record files");+ }+ let digest = Sha256::digest(listing.as_bytes());+ let pin_sha: String = digest+ .iter()+ .map(|b| format!("{b:02x}"))+ .collect::<String>()[..40]+ .to_string();+ let pin_date = raw+ .get("created_at")+ .and_then(Value::as_str)+ .and_then(|c| c.get(0..10))+ .ok_or_else(|| anyhow!("manifest.json has no created_at date"))?+ .to_string();++ let mut spdx: Vec<String> = Vec::new();+ for s in &meta.sources {+ let lic = s.licence.trim();+ if lic.is_empty() {+ bail!("source '{}' records no licence", s.slug);+ }+ if !spdx.iter().any(|l| l == lic) {+ spdx.push(lic.to_string());+ }+ }+ if spdx.is_empty() {+ bail!("the pack declares no sources");+ }+ let licence_class = if spdx+ .iter()+ .any(|l| xerj_common::xccode::licence::is_restricted(l))+ {+ LicenceClass::ApproachOnly+ } else {+ LicenceClass::AdaptWithAttribution+ };+ Ok(PackMetadata {+ pin_sha,+ pin_date,+ licence_spdx: spdx.join("/"),+ licence_class,+ sources: meta+ .sources+ .iter()+ .map(|s| PackSource {+ repo: s.slug.clone(),+ url: s.url.clone().unwrap_or_default(),+ sha: s.watermark.clone().unwrap_or_default(),+ licence: s.licence.clone(),+ })+ .collect(),+ })+}+/// `PUT /<index>` with the plan's §3 defs mapping.fn create_defs_index(node: &HubNode, index: &str) -> Result<()> {let body = json!({@@ -1563,6 +1699,121 @@ fn now_rfc3339() -> String {mod tests {use super::*;+ /// A minimal record pack in the layout `xerj corpus build` writes and+ /// `harvest::pack::read_manifest` verifies.+ fn record_pack(dir: &Path, slug: &str, created_at: &str, records: &str, licence: &str) {+ fs::create_dir_all(dir).unwrap();+ let hex = |b: &[u8]| -> String {+ Sha256::digest(b)+ .iter()+ .map(|x| format!("{x:02x}"))+ .collect()+ };+ fs::write(dir.join("records-000.jsonl"), records).unwrap();+ fs::write(dir.join("recipe.toml"), "[recipe]\n").unwrap();+ let n = records.lines().filter(|l| !l.trim().is_empty()).count();+ let manifest = json!({+ "format_version": 1, "kind": "harvested", "pack": slug,+ "created_at": created_at, "generation": 3,+ "counts": { "records": n },+ "files": { "records-000.jsonl": { "sha256": hex(records.as_bytes()), "records": n } },+ "sources": [ { "slug": "src", "licence": licence, "url": "https://x.test/src" } ],+ });+ let manifest = serde_json::to_string_pretty(&manifest).unwrap();+ fs::write(dir.join("manifest.json"), &manifest).unwrap();+ let sums = format!(+ "{} manifest.json\n{} recipe.toml\n{} records-000.jsonl\n",+ hex(manifest.as_bytes()),+ hex(b"[recipe]\n"),+ hex(records.as_bytes())+ );+ fs::write(dir.join("SHA256SUMS"), sums).unwrap();+ }++ const RECORDS: &str = "{\"id\":\"A-1\",\"source\":\"src\"}\n";++ #[test]+ fn a_record_packs_pin_is_its_content_not_its_build_date() {+ let tmp = tempfile::tempdir().unwrap();+ let (a, b, c) = (+ tmp.path().join("a"),+ tmp.path().join("b"),+ tmp.path().join("c"),+ );+ record_pack(&a, "rv", "2026-10-16T04:23:00Z", RECORDS, "CC0-1.0");+ record_pack(&b, "rv", "2026-10-17T04:23:00Z", RECORDS, "CC0-1.0");+ record_pack(+ &c,+ "rv",+ "2026-10-17T04:23:00Z",+ "{\"id\":\"A-2\",\"source\":\"src\"}\n",+ "CC0-1.0",+ );+ let ma = record_pack_metadata(&a, "rv").unwrap();+ let mb = record_pack_metadata(&b, "rv").unwrap();+ let mc = record_pack_metadata(&c, "rv").unwrap();+ assert_eq!(ma.pin_sha.len(), 40);+ assert!(ma.pin_sha.chars().all(|c| c.is_ascii_hexdigit()));+ assert_eq!(ma.pin_sha, mb.pin_sha, "same records, same pin");+ assert_ne!(mb.pin_sha, mc.pin_sha, "a changed record moves the pin");+ assert_eq!(ma.pin_date, "2026-10-16");+ assert_eq!(mb.pin_date, "2026-10-17");+ assert_eq!(ma.licence_spdx, "CC0-1.0");+ assert_eq!(ma.licence_class, LicenceClass::AdaptWithAttribution);+ assert_eq!(ma.sources.len(), 1);+ assert_eq!(ma.sources[0].repo, "src");+ assert_eq!(ma.sources[0].url, "https://x.test/src");+ }++ #[test]+ fn a_record_packs_licence_follows_the_one_licence_policy_and_fails_closed() {+ let tmp = tempfile::tempdir().unwrap();+ let gpl = tmp.path().join("gpl");+ record_pack(&gpl, "rv", "2026-10-16T00:00:00Z", RECORDS, "GPL-3.0");+ let m = record_pack_metadata(&gpl, "rv").unwrap();+ assert_eq!(m.licence_class, LicenceClass::ApproachOnly);+ let none = tmp.path().join("none");+ record_pack(&none, "rv", "2026-10-16T00:00:00Z", RECORDS, "");+ let err = format!("{:#}", record_pack_metadata(&none, "rv").err().unwrap());+ assert!(err.contains("records no licence"), "{err}");+ }++ #[test]+ fn a_record_pack_for_another_slug_or_a_tampered_one_is_refused() {+ let tmp = tempfile::tempdir().unwrap();+ let dir = tmp.path().join("p");+ record_pack(&dir, "rv", "2026-10-16T00:00:00Z", RECORDS, "CC0-1.0");+ let err = format!("{:#}", record_pack_metadata(&dir, "other").err().unwrap());+ assert!(err.contains("not 'other'"), "{err}");+ fs::write(+ dir.join("records-000.jsonl"),+ "{\"id\":\"B\",\"source\":\"src\"}\n",+ )+ .unwrap();+ assert!(record_pack_metadata(&dir, "rv").is_err());+ }++ #[test]+ fn build_pack_takes_one_source_not_two() {+ let args: Vec<String> = [+ "rv",+ "--registry",+ "r",+ "--from-pack",+ "p",+ "--out",+ "o",+ "--url",+ "http://127.0.0.1:1",+ "--sign-key",+ "k",+ ]+ .iter()+ .map(|s| s.to_string())+ .collect();+ assert_eq!(run_build_pack(&args), 2);+ }+#[test]fn a_refused_restore_names_the_exact_config_line_that_fixes_it() {let hub = tempfile::tempdir().unwrap();diff --git a/engine/crates/xerj-hub/src/pack.rs b/engine/crates/xerj-hub/src/pack.rsindex fffe6c373..894e1819e 100644--- a/engine/crates/xerj-hub/src/pack.rs+++ b/engine/crates/xerj-hub/src/pack.rs@@ -505,6 +505,119 @@ pub fn build_defs_and_files(Ok((defs, files))}+/// [`build_defs_and_files`] for a RECORD corpus (a record pack `xerj corpus add`+/// materialized as `<source>/records.jsonl`, one canonical JSON record per+/// line). A record pack has no source code to parse; its definitions are what+/// its recipe declares:+///+/// - every record is one definition of its `id` (kind `record`), so+/// `--def RUSTSEC-2021-0003` or `--def GHSA-…` lands on the line holding it;+/// - every identifier the recipe's `defs_from` put in the record's `defs` field+/// (rust-vulns: the advisory's affected functions, `smallvec::SmallVec::insert_many`)+/// is a definition of kind `record_def` at the same line. Only tokens shaped+/// like identifiers or paths count; `defs` is space-joined, so free text a+/// recipe routed there splits into words, and words are not definitions.+///+/// `file` is the records file and `line` the record's 1-based line in it, so a+/// hit opens at the record. The inventory lists each records file.+pub fn record_defs_and_files(+ corpus_root: &Path,+ licence_of: &dyn Fn(&str) -> String,+) -> Result<(Vec<DefRecord>, Vec<PackFileEntry>)> {+ let mut found: Vec<(String, PathBuf)> = Vec::new();+ walk_corpus(corpus_root, corpus_root, &mut found)?;+ let mut defs: Vec<DefRecord> = Vec::new();+ let mut files: Vec<PackFileEntry> = Vec::new();+ for (rel, abs) in &found {+ if rel == "corpus.json" {+ continue;+ }+ let bytes = fs::metadata(abs).map(|m| m.len()).unwrap_or(0);+ files.push(PackFileEntry {+ path: rel.clone(),+ lang: String::new(),+ bytes,+ licence: licence_of(rel),+ });+ if !rel.ends_with("/records.jsonl") {+ continue;+ }+ let text = fs::read_to_string(abs).with_context(|| format!("read {rel}"))?;+ for (n, line) in text.lines().enumerate() {+ if line.trim().is_empty() {+ continue;+ }+ let v: serde_json::Value = serde_json::from_str(line)+ .with_context(|| format!("{rel} line {}: not JSON", n + 1))?;+ let field = |k: &str| v.get(k).and_then(serde_json::Value::as_str).unwrap_or("");+ let id = field("id").trim();+ if id.is_empty() {+ continue;+ }+ let title = field("title").trim();+ let line_no = u32::try_from(n + 1).unwrap_or(u32::MAX);+ let summary = if title.is_empty() || title == id {+ id.to_string()+ } else {+ format!("{id}: {title}")+ };+ let summary = truncate_chars(&summary, 400);+ defs.push(DefRecord {+ symbol: id.to_string(),+ kind: "record".into(),+ lang: String::new(),+ file: rel.clone(),+ line: line_no,+ text: summary.clone(),+ value: None,+ });+ let mut seen: Vec<&str> = vec![id];+ for tok in field("defs").split_whitespace() {+ if is_symbol_token(tok) && !seen.contains(&tok) {+ seen.push(tok);+ defs.push(DefRecord {+ symbol: tok.to_string(),+ kind: "record_def".into(),+ lang: String::new(),+ file: rel.clone(),+ line: line_no,+ text: summary.clone(),+ value: None,+ });+ }+ }+ }+ }+ defs.sort_by(|a, b| {+ a.file+ .cmp(&b.file)+ .then(a.line.cmp(&b.line))+ .then(a.symbol.cmp(&b.symbol))+ });+ files.sort_by(|a, b| a.path.cmp(&b.path));+ Ok((defs, files))+}++/// An identifier (`insert_many`) or a `::`/`.`-separated path of identifiers+/// (`smallvec::SmallVec::insert_many`, `os.path.join`), at most 200 bytes.+fn is_symbol_token(tok: &str) -> bool {+ if tok.is_empty() || tok.len() > 200 {+ return false;+ }+ tok.split("::").flat_map(|p| p.split('.')).all(|part| {+ let mut chars = part.chars();+ matches!(chars.next(), Some(c) if c.is_ascii_alphabetic() || c == '_')+ && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')+ })+}++fn truncate_chars(s: &str, max: usize) -> String {+ match s.char_indices().nth(max) {+ Some((i, _)) => s[..i].to_string(),+ None => s.to_string(),+ }+}+/// Recursively collect regular files as `(relative-forward-slash path, abs)`,/// skipping `.git`. Mirrors the snapshot walker but keyed on a corpus root.fn walk_corpus(base: &Path, dir: &Path, out: &mut Vec<(String, PathBuf)>) -> Result<()> {diff --git a/tools/hub-packs/consumer_e2e.sh b/tools/hub-packs/consumer_e2e.shindex 1d4dd716c..ff9808fdf 100755--- a/tools/hub-packs/consumer_e2e.sh+++ b/tools/hub-packs/consumer_e2e.sh@@ -92,10 +92,15 @@ done"$BIN" hub pull "$SLUG" || fail "xerj hub pull $SLUG failed (exit $?)"# 4. --def for a symbol from the pack's own defs.jsonl: the first identifier of-# four or more characters (a stable, deterministic choice).+# four or more characters (a stable, deterministic choice). A record pack+# (build-pack --from-pack) may have none: its definitions are record ids+# (RUSTSEC-2021-0003, nst-…) and paths (smallvec::SmallVec::insert_many), so+# the first such symbol is the fallback.zstd -dc "$WORK/rel/$TAG/$FILE" | tar -xOf - defs.jsonl > "$WORK/defs.jsonl"DEF=$(jq -cn 'first(inputs | select(.symbol | test("^[A-Za-z_][A-Za-z0-9_]{3,}$"))) // empty' \"$WORK/defs.jsonl")+[ -n "$DEF" ] || DEF=$(jq -cn 'first(inputs | select(.symbol | test("^[A-Za-z0-9_][A-Za-z0-9_:.-]{3,}$"))) // empty' \+ "$WORK/defs.jsonl")[ -n "$DEF" ] || fail "defs.jsonl has no identifier to look up"SYM=$(jq -r .symbol <<<"$DEF")"$BIN" code "$SLUG" --def "$SYM" --json > "$WORK/def.json" \@@ -130,14 +135,20 @@ WORDS=$(tr -cs 'A-Za-z' '\n' <<<"$ASK" | tr 'A-Z' 'a-z' | awk 'length >= 4' \| grep -vxE 'agent|agents|working|needing|queries|query|this|that|with|from|when|into|their|about|does' \| awk '{ print length, $0 }' | sort -rn -k1,1 -s | cut -d' ' -f2 | awk '!seen[$0]++' | head -n 3 || true)[ -n "$WORDS" ] || WORDS=$SLUG+# A located hit: code hits carry a file/path AND a line (passage-level), the+# stricter primary check; a RECORD corpus (rust-vulns, agent-session-+# trajectories) has no lines — its records are addressed by `ax_path`+# (dataset/records.jsonl), the provenance every XERJ hit carries — so a hit+# located by a non-empty `ax_path` also counts. The filter is shared by the+# test and the echo so they never disagree.+LOCATED='[.. | objects | select(((.file? // .path? // "") != "" and (.line? // .start_line? // null) != null) or (.ax_path? // "") != "")]'hit=""for w in $WORDS; doif "$BIN" code "$SLUG" "$w" --json > "$WORK/q.json" 2> "$WORK/q.err" \- && jq -e '[.. | objects | select((.file? // .path? // "") != "" and (.line? // .start_line? // null) != null)] | length > 0' \- "$WORK/q.json" >/dev/null 2>&1; then+ && jq -e "$LOCATED | length > 0" "$WORK/q.json" >/dev/null 2>&1; thenhit=$w; breakfidone-[ -n "$hit" ] || { cat "$WORK/q.json" "$WORK/q.err" 2>/dev/null | head -c 4000; fail "no question from ask_for ($WORDS) returned a file:line hit"; }-echo "question ok: \"$hit\" -> $(jq -r '[.. | objects | select((.file? // .path? // "") != "" and (.line? // .start_line? // null) != null)][0] | "\(.file // .path):\(.line // .start_line)"' "$WORK/q.json")"+[ -n "$hit" ] || { cat "$WORK/q.json" "$WORK/q.err" 2>/dev/null | head -c 4000; fail "no question from ask_for ($WORDS) returned a located hit"; }+echo "question ok: \"$hit\" -> $(jq -r "$LOCATED"'[0] | (.file // .path // .ax_path) + (if (.line // .start_line) then ":" + ((.line // .start_line) | tostring) else "" end)' "$WORK/q.json")"echo "consumer e2e passed for $SLUG @ $PIN8"diff --git a/tools/hub-packs/hub_packs.py b/tools/hub-packs/hub_packs.pyindex 529ba1da5..d5ef24133 100644--- a/tools/hub-packs/hub_packs.py+++ b/tools/hub-packs/hub_packs.py@@ -29,6 +29,11 @@ Registry facts this relies on (tools/xerj-code/hub/):(A = git manifest, B = harvested pack recipe) and `refresh`(pinned|weekly|daily). Only live lane-A rows have a manifest this pipelinecan build.+ * Live lane-B rows are RECORD packs (rust-vulns, agent-session-trajectories):+ pack-publish.yml builds them as hubpacks (`xerj hub build-pack --from-pack`)+ under the same `pack-<slug>-<pin8>` release names, with a CONTENT pin (no+ commit exists), so `fetch-list` and `check-catalogue` take their pin from+ the releases and the catalogue rather than from a manifest."""from __future__ import annotations@@ -554,11 +559,45 @@ def fetch_list(corpora: list[Corpus], published_tags: Iterable[str]) -> list[tupreturn out+def load_record_slugs(backlog: pathlib.Path) -> list[str]:+ """Live lane-B corpora: the record packs pack-publish.yml builds as hubpacks."""+ rows = json.loads(backlog.read_text()).get("corpora", [])+ return sorted(+ r["slug"]+ for r in rows+ if r.get("status") == "live" and r.get("lane") == "B" and SLUG_RE.match(str(r.get("slug", "")))+ )+++def record_fetch_list(+ slugs: Iterable[str],+ published_tags: Iterable[str],+ published_at: Optional[dict[str, str]] = None,+) -> list[tuple[str, str, str]]:+ """`(slug, pin8, tag)` for the record packs' hubpack releases. A record pack's+ pin is a content pin, so no manifest names the current one: with+ `published_at` (tag -> ISO time) only the most recently published pin of each+ slug is listed, otherwise every published pin (build-catalogue then lists the+ newest `built_at`). The pack-publish JSON releases (`pack-<slug>-<date>`) never+ match: a pin8 is 8 hex digits."""+ tags = list(published_tags)+ out = []+ for slug in slugs:+ rx = re.compile(re.escape(f"pack-{slug}-") + r"([0-9a-f]{8})(?:-r\d+)?")+ pins = sorted({m.group(1) for t in tags if (m := rx.fullmatch(t))})+ rows = [(slug, pin8, released_tag(tags, slug, pin8)) for pin8 in pins]+ if published_at is not None and rows:+ rows = [max(rows, key=lambda r: (published_at.get(r[2] or "", ""), r[1]))]+ out.extend((s_, p, t) for s_, p, t in rows if t)+ return out++def check_catalogue(raw: bytes,corpora: list[Corpus],repo: str,previous: Optional[bytes] = None,+ record_slugs: Iterable[str] = (),) -> list[str]:"""Everything that must hold before a freshly built catalogue replaces the liveone; the list of violations (empty = fine).@@ -582,26 +621,35 @@ def check_catalogue(return [*errors, "no corpora"]live = {c.slug: c for c in corpora}+ records = set(record_slugs)listed: set[str] = set()for e in entries:slug = e.get("slug", "")c = live.get(slug)- if c is None:+ if c is None and slug not in records:errors.append(f"{slug or '?'}: not a live lane-A corpus in the registry")continueif slug in listed:errors.append(f"{slug}: listed twice")listed.add(slug)- if e.get("pin_sha") != c.pin_sha:- errors.append(f"{slug}: pin_sha {str(e.get('pin_sha'))[:12]} is not the manifest's {c.pin8}")+ if c is not None:+ pin8 = c.pin8+ if e.get("pin_sha") != c.pin_sha:+ errors.append(f"{slug}: pin_sha {str(e.get('pin_sha'))[:12]} is not the manifest's {c.pin8}")+ else:+ # A record pack: its content pin is whatever the signed pack says, but+ # it must have the shape of a pin and its URL must name that pin.+ pin8 = str(e.get("pin_sha", ""))[:8]+ if not SHA_RE.match(str(e.get("pin_sha", ""))):+ errors.append(f"{slug}: pin_sha {str(e.get('pin_sha'))[:12]!r} is not 40 hex")url = e.get("pack_url", "")want = (r"^https://github\.com/" + re.escape(repo) + r"/releases/download/"- + re.escape(pack_tag(slug, c.pin8)) + r"(?:-r\d+)?/"- + re.escape(f"{slug}-{c.pin8}.hubpack.tar.zst") + "$"+ + re.escape(pack_tag(slug, pin8)) + r"(?:-r\d+)?/"+ + re.escape(f"{slug}-{pin8}.hubpack.tar.zst") + "$")if not re.match(want, url):- errors.append(f"{slug}: pack_url {url!r} is not the release asset of pin {c.pin8}")+ errors.append(f"{slug}: pack_url {url!r} is not the release asset of pin {pin8}")if e.get("sig_url") != url + ".sig":errors.append(f"{slug}: sig_url is not pack_url + '.sig'")if not re.fullmatch(r"[0-9a-f]{64}", str(e.get("pack_sha256", ""))):@@ -624,7 +672,7 @@ def check_catalogue(if before_list is None or not all(isinstance(x, dict) for x in before_list):return [*errors, "the previous (live) catalogue is not a catalogue; cannot tell which corpora it lists"]before = {x.get("slug") for x in before_list}- for slug in sorted((before & set(live)) - listed):+ for slug in sorted((before & (set(live) | records)) - listed):errors.append(f"{slug}: in the live catalogue and still live, but missing from the new one")return errors@@ -902,7 +950,17 @@ def cmd_fetch_list(a: argparse.Namespace) -> int:tags = pathlib.Path(a.published_tags).read_text().split()rows = fetch_list(corpora, tags)print(f"fetch-list: {len(rows)} of {len(corpora)} live corpora have a published pack", file=sys.stderr)- for slug, pin8, tag in rows:+ published_at = None+ if a.published_at:+ published_at = {}+ for line in pathlib.Path(a.published_at).read_text().splitlines():+ tag, _, when = line.partition("\t")+ if tag.strip():+ published_at[tag.strip()] = when.strip()+ records = load_record_slugs(pathlib.Path(a.backlog))+ rec_rows = record_fetch_list(records, tags, published_at)+ print(f"fetch-list: {len(rec_rows)} record-pack release(s) for {len(records)} live record corpora", file=sys.stderr)+ for slug, pin8, tag in rows + rec_rows:print(f"{slug}\t{pin8}\t{tag}")return 0@@ -911,7 +969,8 @@ def cmd_check_catalogue(a: argparse.Namespace) -> int:corpora, _ = load_live(pathlib.Path(a.registry), pathlib.Path(a.backlog))raw = pathlib.Path(a.catalogue).read_bytes()previous = pathlib.Path(a.previous).read_bytes() if a.previous else None- errors = check_catalogue(raw, corpora, a.repo, previous)+ records = load_record_slugs(pathlib.Path(a.backlog))+ errors = check_catalogue(raw, corpora, a.repo, previous, records)if a.allow_drops:errors = [e for e in errors if "missing from the new one" not in e]for e in errors:@@ -1022,6 +1081,10 @@ def main(argv: Optional[list[str]] = None) -> int:f.add_argument("--registry", required=True)f.add_argument("--backlog", required=True)f.add_argument("--published-tags", required=True)+ f.add_argument(+ "--published-at",+ help="tag<TAB>published-at lines; list only each record pack's newest pin",+ )f.set_defaults(fn=cmd_fetch_list)k = sub.add_parser("check-catalogue", help="refuse a catalogue that disagrees with the registry")diff --git a/tools/hub-packs/test_hub_packs.py b/tools/hub-packs/test_hub_packs.pyindex d44c60f00..05654b27e 100644--- a/tools/hub-packs/test_hub_packs.py+++ b/tools/hub-packs/test_hub_packs.py@@ -646,6 +646,86 @@ class CatalogueTests(unittest.TestCase):self.assertIn("1 of 2 live corpora", out.stderr)+class RecordPackTests(unittest.TestCase):+ """Live lane-B corpora (record packs) as hubpacks: no manifest, a content pin."""++ REPO = "xerj-org/xerj"+ PIN = "0123abcd" + "e" * 32++ def setUp(self):+ self._tmp = tempfile.TemporaryDirectory()+ self.root = pathlib.Path(self._tmp.name)+ rows = [row("alpha"), row("rust-vulns", lane="B", refresh="daily"),+ row("old-records", status="candidate", lane="B")]+ mans = {"alpha": manifest_text("alpha", [("alpha", "https://x.test/a", SHA_A)])}+ self.reg, self.backlog = write_registry(self.root, rows, mans)+ self.corpora, _ = hp.load_live(self.reg, self.backlog)++ def tearDown(self):+ self._tmp.cleanup()++ def test_only_live_lane_b_rows_are_record_corpora(self):+ self.assertEqual(hp.load_record_slugs(self.backlog), ["rust-vulns"])++ def test_record_fetch_list_ignores_the_dated_json_releases(self):+ tags = ["pack-rust-vulns-2026-10-08", "pack-rust-vulns-2026-10-08-r2",+ "pack-rust-vulns-0123abcd", "pack-rust-vulns-0123abcd-r2", "pack-rust-vulns-99999999",+ "pack-rust-vulns-x-0123abcd"]+ self.assertEqual(+ hp.record_fetch_list(["rust-vulns"], tags),+ [("rust-vulns", "0123abcd", "pack-rust-vulns-0123abcd-r2"), ("rust-vulns", "99999999", "pack-rust-vulns-99999999")],+ )+ newest = {"pack-rust-vulns-0123abcd-r2": "2026-10-17T04:30:00Z", "pack-rust-vulns-99999999": "2026-10-16T04:30:00Z"}+ self.assertEqual(+ hp.record_fetch_list(["rust-vulns"], tags, newest),+ [("rust-vulns", "0123abcd", "pack-rust-vulns-0123abcd-r2")],+ )+ self.assertEqual(hp.record_fetch_list(["rust-vulns"], ["pack-rust-vulns-2026-10-08"]), [])++ def test_fetch_list_command_adds_the_record_packs(self):+ tags = self.root / "tags.txt"+ tags.write_text("pack-alpha-aaaaaaaa\npack-rust-vulns-2026-10-08\npack-rust-vulns-0123abcd\npack-rust-vulns-11111111\n")+ at = self.root / "at.tsv"+ at.write_text("pack-rust-vulns-0123abcd\t2026-10-17T00:00:00Z\npack-rust-vulns-11111111\t2026-10-16T00:00:00Z\n")+ out = subprocess.run(+ [sys.executable, hp.__file__, "fetch-list", "--registry", str(self.reg), "--backlog", str(self.backlog),+ "--published-tags", str(tags), "--published-at", str(at)],+ capture_output=True, text=True,+ )+ self.assertEqual(out.returncode, 0, out.stderr)+ self.assertEqual(out.stdout, "alpha\taaaaaaaa\tpack-alpha-aaaaaaaa\nrust-vulns\t0123abcd\tpack-rust-vulns-0123abcd\n")++ def entry(self, slug: str, sha: str, tag_pin8: str = "") -> dict:+ pin8 = tag_pin8 or sha[:8]+ url = (f"https://github.com/{self.REPO}/releases/download/pack-{slug}-{pin8}/"+ f"{slug}-{pin8}.hubpack.tar.zst")+ return {"slug": slug, "pin_sha": sha, "pack_url": url, "sig_url": url + ".sig",+ "pack_sha256": "ab" * 32, "pack_bytes": 1}++ def cat(self, *entries: dict) -> bytes:+ return json.dumps({"format_version": 1, "generated_at": "x", "corpora": list(entries)}).encode()++ def check(self, raw: bytes, previous=None) -> list[str]:+ return hp.check_catalogue(raw, self.corpora, self.REPO, previous, hp.load_record_slugs(self.backlog))++ def test_a_record_entry_with_its_own_pin_passes(self):+ self.assertEqual(self.check(self.cat(self.entry("alpha", SHA_A), self.entry("rust-vulns", self.PIN))), [])++ def test_a_record_entry_must_name_its_pin_in_the_url_and_be_live(self):+ joined = "\n".join(self.check(self.cat(+ self.entry("rust-vulns", self.PIN, tag_pin8="99999999"),+ self.entry("old-records", self.PIN),+ )))+ self.assertIn("rust-vulns: pack_url", joined)+ self.assertIn("old-records: not a live lane-A corpus", joined)+ self.assertIn("is not 40 hex", "\n".join(self.check(self.cat(self.entry("rust-vulns", "0123abcd")))))++ def test_a_live_record_corpus_may_not_vanish(self):+ live = self.cat(self.entry("alpha", SHA_A), self.entry("rust-vulns", self.PIN))+ errors = self.check(self.cat(self.entry("alpha", SHA_A)), previous=live)+ self.assertEqual(errors, ["rust-vulns: in the live catalogue and still live, but missing from the new one"])++class ReportTests(unittest.TestCase):STAGES = ["start", "build", "verify", "tag", "upload", "e2e", "publish"]