Skip to content

armgit / xerj

Public Imported from GitHub
0

AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.

ci(hub): hub-packs workflow, planning and re-pin logic (plan §8)

xerj-orgb4c1a0043667
diff --git a/.github/workflows/hub-packs.yml b/.github/workflows/hub-packs.yml
new file mode 100644
index 000000000..651f50482
--- /dev/null
+++ b/.github/workflows/hub-packs.yml
@@ -0,0 +1,652 @@
+# Corpus Hub v2 pack pipeline (plan §8, docs/CORPUS_HUB_V2_IMPLEMENTATION.md).
+#
+# PUSH to corpus-hub (or a manual run)
+# every LIVE corpus whose CURRENT pin has no published release gets a pack
+# built (`xerj hub build-pack`), signed, verified and uploaded as the release
+# `pack-<slug>-<pin8>`; then the signed catalogue is rebuilt from those
+# releases and, once the owner opts in (see DEPLOY), deployed to hub.xerj.org.
+#
+# SCHEDULE
+# for corpora whose upstream moved, open a re-pin PULL REQUEST: weekly for the
+# `weekly` refresh class, daily for `daily` (refresh_cadence_days = 1). A human
+# merges; the push above then builds the packs. Nothing here ever moves a pin
+# by itself. The `pinned` class (code at a release tag; PROGRAM-100.md §3: "the
+# pin is the promise") is not proposed automatically: its default-branch head
+# differs from the tag for ~500 corpora every week. `include_pinned` on a
+# manual run opts in.
+#
+# WHY "no release for the current pin" AND NOT "manifest changed in this push"
+# Deciding from release state makes every run a reconcile: a dropped, cancelled
+# or failed run costs nothing, because the next run sees the same unreleased pin
+# and builds it. (GitHub replaces a queued run with a newer queued one, so a diff
+# of "what this push touched" would lose changes.) It also covers the first
+# backfill of ~500 packs: --max-builds spreads that over runs. For an ordinary
+# push the two readings coincide: a changed pin is a pin with no release.
+#
+# BRANCHES
+# This file belongs on `corpus-hub`, where the registry (tools/xerj-code/hub/,
+# backlog/backlog-100.json) lives; `push` runs the copy in the pushed commit.
+# `schedule` runs the DEFAULT branch's copy, so the re-pin job checks out
+# `corpus-hub` explicitly and opens its PRs against it.
+#
+# CHAIN OF CUSTODY (the shape of pack-publish.yml)
+# build -> sign (PACK_SIGNING_SEED, the secret pack-publish.yml already uses)
+# -> verify against the key CLIENTS embed (HUB_PUBKEY_HEX in
+# engine/crates/xerj-common/src/hub.rs) in the same run -> publish. A seed that
+# does not match that key fails here instead of shipping packs no client can
+# verify; clients independently refuse any pack whose sha256 or signature fails
+# (`xerj hub pull`), and extract nothing before both pass.
+#
+# DORMANT UNTIL THE KEY EXISTS
+# HUB_PUBKEY_HEX is "" until the hub signing key is generated and committed.
+# Until then the `preflight` job reports "dormant" and every publishing job is
+# skipped; the re-pin job does not need the key and runs regardless.
+#
+# DEPLOY (opt-in)
+# The catalogue job always builds, checks and uploads the signed catalogue as an
+# artifact. It deploys to Cloudflare Pages only when the repository VARIABLE
+# HUB_CATALOGUE_DEPLOY is "true" (a variable, not a secret): read the first
+# artifact, then flip it. It uses the same Pages project and secrets as
+# deploy-hub-pages.yml, which replaces the whole site on every deploy, so the
+# two must not disagree about whether /api/v1/catalogue.json is part of it.
+#
+# REPOSITORY SETTINGS this relies on
+# * Settings > Actions > General > "Allow GitHub Actions to create and approve
+# pull requests" (the re-pin job opens PRs with GITHUB_TOKEN). PRs opened that
+# 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.
+
+name: hub packs
+
+on:
+ push:
+ branches: [corpus-hub]
+ paths:
+ - tools/xerj-code/hub/*.json
+ - tools/xerj-code/hub/backlog/backlog-100.json
+ - tools/hub-packs/**
+ - .github/workflows/hub-packs.yml
+ schedule:
+ # Monday 05:17 UTC: re-pin the `weekly` class. Off the :00/:30 marks.
+ - cron: "17 5 * * 1"
+ # Every day 04:41 UTC: re-pin the `daily` class (feeds).
+ - cron: "41 4 * * *"
+ workflow_dispatch:
+ inputs:
+ slugs:
+ description: "Build only these corpora (comma list), or 'all' for everything due"
+ type: string
+ default: ""
+ force:
+ description: "Rebuild pins that already have a release (published under a -rN tag)"
+ type: boolean
+ default: false
+ max_builds:
+ description: "Cap on packs built in this run (the next run continues)"
+ type: string
+ default: "40"
+ dry_run:
+ description: "Build and verify, but publish nothing (no release, no deploy); works from any branch"
+ type: boolean
+ default: false
+ allow_drops:
+ description: "Let the catalogue delist corpora that are still live (after a failed pack build)"
+ type: boolean
+ default: false
+ repin:
+ description: "Also run the re-pin job now"
+ type: boolean
+ default: false
+ repin_classes:
+ description: "Refresh classes the re-pin job may propose (weekly,daily)"
+ type: string
+ default: "weekly,daily"
+ include_pinned:
+ description: "Also re-pin the `pinned` class (release-tag corpora; expect hundreds of PRs)"
+ type: boolean
+ default: false
+ max_prs:
+ description: "Cap on re-pin PRs opened in this run"
+ type: string
+ default: "25"
+
+permissions:
+ contents: read
+
+# Never two publishes at once (a release tag is single-use under immutable
+# releases), and re-pin runs queue apart from publish runs.
+concurrency:
+ group: hub-packs-${{ github.event_name == 'schedule' && 'repin' || 'publish' }}
+ cancel-in-progress: false
+
+env:
+ REGISTRY: tools/xerj-code/hub
+ BACKLOG: tools/xerj-code/hub/backlog/backlog-100.json
+ HUB_RS: engine/crates/xerj-common/src/hub.rs
+ # Every matrix job has its own runner, so one fixed loopback port cannot collide.
+ # The node also listens on the next two ports (native REST, gRPC).
+ BUILDER_PORT: "19200"
+
+jobs:
+ # ── the scripts every job below trusts ─────────────────────────────────────
+ # The same guard deploy-hub-pages.yml puts in front of its site generator:
+ # nothing is planned, published or proposed by a script whose tests fail.
+ selftest:
+ name: unit-test the pipeline scripts
+ runs-on: ubuntu-latest
+ timeout-minutes: 10
+ steps:
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
+ with:
+ persist-credentials: false
+
+ - name: Plan, re-pin and catalogue-check logic
+ run: python3 tools/hub-packs/test_hub_packs.py
+
+ - name: Shell syntax
+ run: bash -n tools/hub-packs/ed25519.sh
+
+ # ── is there a key to sign with and verify against? ────────────────────────
+ preflight:
+ name: hub key and secret in place?
+ if: github.event_name != 'schedule'
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ outputs:
+ ready: ${{ steps.check.outputs.ready }}
+ pubkey: ${{ steps.check.outputs.pubkey }}
+ steps:
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
+ with:
+ persist-credentials: false
+
+ - id: check
+ env:
+ PACK_SIGNING_SEED: ${{ secrets.PACK_SIGNING_SEED }}
+ DRY_RUN: ${{ inputs.dry_run }}
+ run: |
+ set -euo pipefail
+ ready=false; pub=""; why=""
+ if [ "$GITHUB_REF" != "refs/heads/corpus-hub" ] && [ "$DRY_RUN" != "true" ]; then
+ why="publishing runs only from corpus-hub, not $GITHUB_REF (a manual run with dry_run builds and verifies anywhere)"
+ elif [ ! -f engine/crates/xerj-hub/Cargo.toml ] || [ ! -f "$HUB_RS" ]; then
+ why="this branch has no Corpus Hub v2 engine code (engine/crates/xerj-hub); merge main into it first"
+ else
+ pub=$(sed -n 's/^pub const HUB_PUBKEY_HEX: &str = "\([0-9a-fA-F]*\)";.*/\1/p' "$HUB_RS" | head -n 1 | tr 'A-F' 'a-f')
+ if [ -z "$pub" ]; then
+ why="HUB_PUBKEY_HEX in $HUB_RS is empty: the hub signing key has not been provisioned (xerj corpus keygen; set PACK_SIGNING_SEED; commit the public half there)"
+ elif [ -z "$PACK_SIGNING_SEED" ]; then
+ echo "::error title=hub packs::HUB_PUBKEY_HEX is set but the PACK_SIGNING_SEED secret is not"
+ exit 1
+ else
+ # Prove the secret is the private half of the key clients embed.
+ umask 077
+ printf '%s' "$PACK_SIGNING_SEED" > "$RUNNER_TEMP/pack.key"
+ derived=$(bash tools/hub-packs/ed25519.sh derive "$RUNNER_TEMP/pack.key")
+ rm -f "$RUNNER_TEMP/pack.key"
+ if [ "$derived" != "$pub" ]; then
+ echo "::error title=hub packs::the PACK_SIGNING_SEED secret does not match HUB_PUBKEY_HEX; refusing to publish packs no client can verify"
+ exit 1
+ fi
+ ready=true
+ fi
+ fi
+ if [ "$ready" != "true" ]; then
+ echo "::notice title=hub packs dormant::$why"
+ { echo "### hub packs: dormant"; echo; echo "$why"; } >> "$GITHUB_STEP_SUMMARY"
+ fi
+ echo "ready=$ready" >> "$GITHUB_OUTPUT"
+ echo "pubkey=$pub" >> "$GITHUB_OUTPUT"
+
+ # ── which live corpora have no pack for their current pin? ─────────────────
+ plan:
+ name: plan the builds
+ needs: [selftest, preflight]
+ if: needs.preflight.outputs.ready == 'true'
+ runs-on: ubuntu-latest
+ timeout-minutes: 10
+ outputs:
+ matrix: ${{ steps.plan.outputs.matrix }}
+ count: ${{ steps.plan.outputs.count }}
+ steps:
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
+ with:
+ persist-credentials: false
+
+ - name: Published pack releases
+ env:
+ 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"
+ echo "$(wc -l < "$RUNNER_TEMP/tags.txt") published pack releases"
+
+ - id: plan
+ env:
+ SLUGS: ${{ inputs.slugs }}
+ FORCE: ${{ inputs.force }}
+ MAX_BUILDS: ${{ inputs.max_builds }}
+ run: |
+ set -euo pipefail
+ args=(plan --registry "$REGISTRY" --backlog "$BACKLOG" \
+ --published-tags "$RUNNER_TEMP/tags.txt" --max-builds "${MAX_BUILDS:-40}")
+ [ -n "${SLUGS:-}" ] && args+=(--slugs "$SLUGS")
+ [ "${FORCE:-}" = "true" ] && args+=(--force)
+ plan=$(python3 tools/hub-packs/hub_packs.py "${args[@]}")
+ # The matrix may hold only `include`: any other key would be read as a dimension.
+ echo "matrix=$(jq -c '{include: .include}' <<<"$plan")" >> "$GITHUB_OUTPUT"
+ echo "count=$(jq -r '.count' <<<"$plan")" >> "$GITHUB_OUTPUT"
+ {
+ echo "### hub packs: plan"
+ echo
+ echo "$(jq -r '.due' <<<"$plan") corpora have no pack for their current pin; $(jq -r '.count' <<<"$plan") scheduled in this run."
+ jq -r '.include[] | "- `\(.slug)` @ `\(.pin8)`"' <<<"$plan"
+ } >> "$GITHUB_STEP_SUMMARY"
+
+ # ── one xerj binary for the matrix and the catalogue ───────────────────────
+ build-xerj:
+ name: build xerj
+ needs: preflight
+ if: needs.preflight.outputs.ready == 'true'
+ runs-on: ubuntu-latest
+ timeout-minutes: 45
+ steps:
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
+ with:
+ persist-credentials: false
+
+ - uses: dtolnay/rust-toolchain@032958afbdc797a9164d3bc0b56325c1308924a5 # 1.97.1
+
+ - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
+ with:
+ workspaces: engine
+
+ # Same profile pack-publish.yml uses: opt-level 3, assertions on. The binary
+ # lands in target/ci-test/, not target/release/.
+ - name: Build the xerj binary
+ working-directory: engine
+ run: cargo build --profile ci-test -p xerj-server
+
+ - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
+ with:
+ name: xerj-bin
+ path: engine/target/ci-test/xerj
+ if-no-files-found: error
+ retention-days: 1
+
+ # ── build, sign, verify and release one pack per due corpus ────────────────
+ pack:
+ name: pack ${{ matrix.slug }}
+ needs: [preflight, plan, build-xerj]
+ if: needs.plan.result == 'success' && needs.plan.outputs.count != '0'
+ runs-on: ubuntu-latest
+ timeout-minutes: 120
+ permissions:
+ contents: write # release assets
+ strategy:
+ fail-fast: false
+ max-parallel: 4
+ matrix: ${{ fromJSON(needs.plan.outputs.matrix) }}
+ env:
+ SLUG: ${{ matrix.slug }}
+ PIN8: ${{ matrix.pin8 }}
+ HUB_PUBKEY_HEX: ${{ needs.preflight.outputs.pubkey }}
+ steps:
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
+ with:
+ persist-credentials: false
+
+ - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
+ with:
+ name: xerj-bin
+ path: bin
+
+ # The builder clones, indexes and snapshots into whatever node it is handed,
+ # so it gets a node of its own: loopback only, no data worth keeping, and
+ # snapshot repositories allowed under the output directory ONLY (the engine's
+ # allowlist, not a weakened check). One node PER PACK is load-bearing, not
+ # tidiness: a second build of near-identical content on the same node failed
+ # once with "exact read-back count 0 disagrees with sealed count 1" (the
+ # autoindex group already exists there).
+ - name: Start a throwaway builder node
+ run: |
+ set -euo pipefail
+ chmod +x bin/xerj
+ 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"
+ bin/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 pack
+ env:
+ PACK_SIGNING_SEED: ${{ secrets.PACK_SIGNING_SEED }}
+ XERJ_CODE_HOME: ${{ runner.temp }}/code-home
+ run: |
+ set -euo pipefail
+ umask 077
+ printf '%s' "$PACK_SIGNING_SEED" > "$RUNNER_TEMP/pack.key"
+ # The builder parses untrusted source trees: keep the seed out of its environment.
+ unset PACK_SIGNING_SEED
+ trap 'rm -f "$RUNNER_TEMP/pack.key"' EXIT
+ bin/xerj hub build-pack "$SLUG" --registry "$REGISTRY" --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" ] || [ "$pin8" != "$PIN8" ]; then
+ echo "::error::the builder reported '$tag $slug $pin8' but the plan expected pack $SLUG $PIN8 (did the manifest change mid-run?)"
+ exit 1
+ fi
+ echo "built $slug $pin8: $bytes bytes, $indices indices, $defs definitions"
+ if [ "$bytes" -gt 52428800 ]; then
+ echo "::notice::$SLUG's pack is $bytes bytes, over the 50 MiB auto-pull cap: clients answer from the hosted route until they run 'xerj hub pull $SLUG'"
+ fi
+
+ # The proof pack-publish.yml also makes in the publishing run: the archive
+ # verifies under the key clients embed, and carries the layout `hub pull`
+ # reads. (Clients re-verify sha256 and signature themselves.)
+ - name: Verify the signature and the layout
+ 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"
+
+ # Immutable releases make a tag SINGLE-USE: one that has named a release can
+ # never name another, even after the release is deleted. Pick the first tag
+ # nobody has used (pack-<slug>-<pin8>, else -r2, -r3, ...), create the
+ # release as a DRAFT, upload to the draft, publish last. Published releases
+ # are never deleted by a rebuild.
+ - name: Pick an unused release tag
+ if: ${{ !inputs.dry_run }}
+ 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"
+
+ # --prerelease and --latest=false: a pack must never become the repository's
+ # "latest" release, which the installer chain reads.
+ - name: Upload the pack to a draft release
+ if: ${{ !inputs.dry_run }}
+ 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 \`$SLUG\`."
+ echo
+ jq -r '"- pinned: `\(.pin_sha)` (\(.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\`, or just ask a question. 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"
+ } > "$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"
+
+ # Draft first, publish last: the step GitHub's own error message prescribes
+ # for immutable-release repositories. A tag whose release was DELETED is burned
+ # with no queryable trace, so the picker cannot foresee the refusal: on
+ # "tag_name was used by an immutable release" retag this draft to the next
+ # free -rN and publish that.
+ - name: Publish the draft (retag past a burned tag if refused)
+ if: ${{ !inputs.dry_run }}
+ 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"
+
+ # Keep the newest 3 pins of THIS corpus (a client holding a slightly stale
+ # catalogue can still fetch the previous pin). Sorted by published_at: not by
+ # tag, so a -rN suffix cannot upset the order, and not by created_at, which
+ # GitHub sets to the date of the release's TARGET COMMIT. A draft has no
+ # published_at, so an abandoned one sorts oldest and is retired first. The
+ # regex is exact so a slug that is a prefix of another (lz4 / lz4-extra) never
+ # reaches the neighbour. Best effort: retention must never cost a publish.
+ - name: Retire this corpus's older pack releases
+ if: ${{ !inputs.dry_run }}
+ continue-on-error: true
+ env:
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ run: |
+ set -euo pipefail
+ gh api "repos/$GITHUB_REPOSITORY/releases?per_page=100" --paginate \
+ | jq -s -r --arg slug "$SLUG" '
+ add
+ | [ .[] | select(.tag_name | test("^pack-" + ($slug | gsub("[.]"; "[.]")) + "-[0-9a-f]{8}(-r[0-9]+)?$")) ]
+ | sort_by(.published_at) | reverse | .[3:] | .[].tag_name' \
+ | while read -r tag; do
+ if [ -n "$tag" ]; then
+ gh release delete "$tag" --repo "$GITHUB_REPOSITORY" --cleanup-tag --yes
+ fi
+ done
+
+ - 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 || true
+
+ # ── rebuild, check, sign and (opt-in) deploy the catalogue ─────────────────
+ catalogue:
+ name: catalogue
+ needs: [preflight, plan, build-xerj, pack]
+ # Runs even when some pack jobs failed: the catalogue is rebuilt from RELEASES,
+ # and check-catalogue refuses to delist a corpus that is still live.
+ if: ${{ !cancelled() && needs.preflight.outputs.ready == 'true' && needs.plan.result == 'success' && needs.build-xerj.result == 'success' }}
+ runs-on: ubuntu-latest
+ timeout-minutes: 120
+ env:
+ HUB_PUBKEY_HEX: ${{ needs.preflight.outputs.pubkey }}
+ HUB_URL: https://hub.xerj.org
+ steps:
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
+ with:
+ persist-credentials: false
+
+ - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
+ with:
+ name: xerj-bin
+ path: bin
+
+ # `xerj hub build-catalogue` (plan §4) is the builder this job calls. If the
+ # binary has no such subcommand, say so plainly instead of failing obscurely.
+ - name: The catalogue builder exists in this binary
+ run: |
+ set -euo pipefail
+ chmod +x bin/xerj
+ if ! bin/xerj hub build-catalogue --help >/dev/null 2>&1; then
+ echo "::error title=catalogue::this xerj has no 'hub build-catalogue' subcommand (plan §4 CLI): the packs are published, but the catalogue cannot be rebuilt until the builder lands"
+ exit 1
+ fi
+
+ - name: Download the current pin's pack of every live corpus
+ env:
+ 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"
+ python3 tools/hub-packs/hub_packs.py fetch-list --registry "$REGISTRY" --backlog "$BACKLOG" \
+ --published-tags "$RUNNER_TEMP/tags.txt" > "$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.
+ mkdir -p "$RUNNER_TEMP/packs"
+ while IFS=$'\t' read -r slug pin8 tag; do
+ for attempt in 1 2 3; do
+ if gh release download "$tag" --repo "$GITHUB_REPOSITORY" --dir "$RUNNER_TEMP/packs" \
+ --pattern "$slug-$pin8.hubpack.tar.zst" --pattern "$slug-$pin8.hubpack.tar.zst.sig"; then
+ break
+ fi
+ [ "$attempt" = 3 ] && { echo "::error::cannot download $tag"; exit 1; }
+ sleep $((attempt * 5))
+ done
+ done < "$RUNNER_TEMP/fetch.tsv"
+ echo "$(wc -l < "$RUNNER_TEMP/fetch.tsv") packs, $(du -sh "$RUNNER_TEMP/packs" | cut -f1)"
+
+ - name: Build and sign the catalogue
+ env:
+ PACK_SIGNING_SEED: ${{ secrets.PACK_SIGNING_SEED }}
+ run: |
+ set -euo pipefail
+ umask 077
+ printf '%s' "$PACK_SIGNING_SEED" > "$RUNNER_TEMP/pack.key"
+ unset PACK_SIGNING_SEED
+ trap 'rm -f "$RUNNER_TEMP/pack.key"' EXIT
+ bin/xerj hub build-catalogue --registry "$REGISTRY" --packs "$RUNNER_TEMP/packs" \
+ --out catalogue.json --sign-key "$RUNNER_TEMP/pack.key"
+ test -s catalogue.json
+ test -s catalogue.json.sig || { echo "::error::build-catalogue wrote no catalogue.json.sig"; exit 1; }
+
+ # The signature proves who built it; this proves it is the right thing to
+ # publish: it verifies under the key clients embed, agrees with the registry
+ # (pins, release URLs), is under 2 MB, and drops no live corpus.
+ - name: Check the catalogue
+ env:
+ ALLOW_DROPS: ${{ inputs.allow_drops }}
+ run: |
+ set -euo pipefail
+ bash tools/hub-packs/ed25519.sh verify "$HUB_PUBKEY_HEX" catalogue.json catalogue.json.sig
+ args=(check-catalogue --registry "$REGISTRY" --backlog "$BACKLOG" --catalogue catalogue.json \
+ --repo "$GITHUB_REPOSITORY")
+ # Compare with the LIVE catalogue so a half-failed build cannot delist a corpus.
+ # Only a clean 404 means "first publish"; any other failure to read it must
+ # not quietly switch the guard off.
+ code=$(curl -sS --max-time 60 -o "$RUNNER_TEMP/live.json" -w '%{http_code}' \
+ "$HUB_URL/api/v1/catalogue.json" || echo 000)
+ case "$code" in
+ 200) args+=(--previous "$RUNNER_TEMP/live.json") ;;
+ 404) echo "no live catalogue yet (first publish)" ;;
+ *) echo "::error::cannot read the live catalogue (HTTP $code); not publishing without the delisting guard"; exit 1 ;;
+ esac
+ [ "${ALLOW_DROPS:-}" = "true" ] && args+=(--allow-drops)
+ python3 tools/hub-packs/hub_packs.py "${args[@]}"
+
+ - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
+ with:
+ name: catalogue
+ path: |
+ catalogue.json
+ catalogue.json.sig
+ retention-days: 14
+
+ # Same generator, validation and Pages project as deploy-hub-pages.yml, with the
+ # catalogue added under api/v1/ (the path the client fetches).
+ - name: Generate the hub site with the catalogue
+ if: ${{ !inputs.dry_run && vars.HUB_CATALOGUE_DEPLOY == 'true' }}
+ run: |
+ set -euo pipefail
+ python3 tools/corpus-hub-site/test_gen.py
+ python3 tools/corpus-hub-site/gen.py
+ python3 tools/xerj-code/hub/validate_hub.py
+ mkdir -p tools/corpus-hub-site/out/api/v1
+ cp catalogue.json catalogue.json.sig tools/corpus-hub-site/out/api/v1/
+
+ - name: Deploy to Cloudflare Pages
+ if: ${{ !inputs.dry_run && vars.HUB_CATALOGUE_DEPLOY == 'true' }}
+ run: npx wrangler@3 pages deploy tools/corpus-hub-site/out --project-name=xerj-hub --branch=corpus-hub
+ env:
+ CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
+ CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
+
+ - name: Deploy skipped
+ if: ${{ inputs.dry_run || vars.HUB_CATALOGUE_DEPLOY != 'true' }}
+ run: |
+ {
+ echo "### catalogue built and checked, NOT deployed"
+ echo
+ echo "Download the \`catalogue\` artifact. To deploy from now on, set the repository variable HUB_CATALOGUE_DEPLOY to \`true\`."
+ } >> "$GITHUB_STEP_SUMMARY"
+
+ # ── open re-pin PRs for corpora whose upstream moved ───────────────────────
+ repin:
+ name: re-pin moved upstreams (opens PRs)
+ needs: selftest
+ if: github.event_name == 'schedule' || (github.event_name == 'workflow_dispatch' && inputs.repin)
+ runs-on: ubuntu-latest
+ timeout-minutes: 30
+ permissions:
+ contents: write # push the re-pin branches
+ pull-requests: write # open the PRs
+ steps:
+ # The scripts come from the ref the workflow runs on (main for a schedule);
+ # the registry and the PR base come from corpus-hub.
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
+ with:
+ path: tools-src
+ persist-credentials: false
+
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
+ with:
+ ref: corpus-hub
+ path: registry-src
+
+ - name: Open re-pin pull requests
+ env:
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ # schedule: the 04:41 cron is the daily class, the Monday cron the weekly one.
+ CLASSES: ${{ github.event_name == 'workflow_dispatch' && inputs.repin_classes || (github.event.schedule == '41 4 * * *' && 'daily' || 'weekly') }}
+ INCLUDE_PINNED: ${{ inputs.include_pinned }}
+ MAX_PRS: ${{ inputs.max_prs }}
+ run: |
+ set -euo pipefail
+ args=(repin
+ --registry registry-src/tools/xerj-code/hub
+ --backlog registry-src/tools/xerj-code/hub/backlog/backlog-100.json
+ --repo-root registry-src --base corpus-hub
+ --classes "$CLASSES" --max-prs "${MAX_PRS:-25}" --apply)
+ [ "${INCLUDE_PINNED:-}" = "true" ] && args+=(--include-pinned)
+ python3 tools-src/tools/hub-packs/hub_packs.py "${args[@]}"
diff --git a/tools/hub-packs/ed25519.sh b/tools/hub-packs/ed25519.sh
new file mode 100755
index 000000000..f6f4cfdb7
--- /dev/null
+++ b/tools/hub-packs/ed25519.sh
@@ -0,0 +1,52 @@
+#!/usr/bin/env bash
+# Ed25519 checks for the hub pipeline, with nothing but `openssl` and `xxd` (both on
+# every GitHub runner), so CI can prove a signature without building a verifier.
+#
+# ed25519.sh derive <seed-file> print the public key (64 hex) of a seed
+# ed25519.sh verify <pub-hex> <file> <sig> exit 0 iff <sig> signs <file> under <pub>
+#
+# Formats are those of xerj-autoindex's harvest/sign.rs: a seed is 32 bytes as 64 hex
+# characters; a public key likewise; a detached signature is the 64 raw bytes as 128 hex
+# characters (what `hub build-pack` writes beside the archive, and what the catalogue's
+# `.sig` holds). Whitespace around any of them is ignored.
+#
+# Why this exists: pack-publish.yml proves in the publishing run that its signing secret
+# still matches the COMMITTED public key, so a rotated secret fails there instead of
+# shipping a pack no client can verify. hub-packs.yml needs the same proof against the
+# key clients embed (HUB_PUBKEY_HEX), and against the packs and catalogue it produces.
+set -euo pipefail
+
+die() { echo "ed25519.sh: $*" >&2; exit 2; }
+
+# DER prefixes for a raw Ed25519 key (RFC 8410): PKCS#8 private (+32-byte seed) and
+# SubjectPublicKeyInfo public (+32-byte key).
+PKCS8_PREFIX=302e020100300506032b657004220420
+SPKI_PREFIX=302a300506032b6570032100
+
+hex_only() { tr -d '[:space:]' | tr 'A-F' 'a-f'; }
+
+case "${1:-}" in
+ derive)
+ [ $# -eq 2 ] || die "usage: derive <seed-file>"
+ seed=$(hex_only < "$2")
+ [[ $seed =~ ^[0-9a-f]{64}$ ]] || die "the seed must be 64 hex characters"
+ tmp=$(mktemp); trap 'rm -f "$tmp"' EXIT
+ printf '%s%s' "$PKCS8_PREFIX" "$seed" | xxd -r -p > "$tmp"
+ openssl pkey -inform DER -in "$tmp" -pubout -outform DER | tail -c 32 | xxd -p -c 64
+ ;;
+ verify)
+ [ $# -eq 4 ] || die "usage: verify <pub-hex> <file> <sig-file>"
+ pub=$(printf '%s' "$2" | hex_only)
+ [[ $pub =~ ^[0-9a-f]{64}$ ]] || die "the public key must be 64 hex characters"
+ [ -f "$3" ] || die "no such file: $3"
+ sig=$(hex_only < "$4")
+ [[ $sig =~ ^[0-9a-f]{128}$ ]] || die "the signature must be 128 hex characters: $4"
+ dir=$(mktemp -d); trap 'rm -rf "$dir"' EXIT
+ printf '%s%s' "$SPKI_PREFIX" "$pub" | xxd -r -p > "$dir/pub.der"
+ printf '%s' "$sig" | xxd -r -p > "$dir/sig.bin"
+ openssl pkeyutl -verify -pubin -inkey "$dir/pub.der" -keyform DER -rawin \
+ -in "$3" -sigfile "$dir/sig.bin" >/dev/null
+ echo "signature verifies: $3"
+ ;;
+ *) die "usage: ed25519.sh derive <seed-file> | verify <pub-hex> <file> <sig-file>" ;;
+esac
diff --git a/tools/hub-packs/hub_packs.py b/tools/hub-packs/hub_packs.py
new file mode 100644
index 000000000..17f46285d
--- /dev/null
+++ b/tools/hub-packs/hub_packs.py
@@ -0,0 +1,761 @@
+#!/usr/bin/env python3
+"""Planning and re-pinning for the Corpus Hub v2 pack pipeline.
+
+Drives `.github/workflows/hub-packs.yml` (plan §8, docs/CORPUS_HUB_V2_IMPLEMENTATION.md).
+Stdlib only, so the workflow needs no `pip install` and the tests run anywhere.
+
+Two jobs, both pure functions over the registry first and thin I/O second:
+
+ plan Which live corpora need a pack built? A corpus is DUE when no published
+ release `pack-<slug>-<pin8>` exists for its current pin (pin8 = the first
+ 8 hex of the manifest's FIRST repo sha, the pin the catalogue carries).
+ Deciding from release state rather than from "which manifests changed in
+ this push" is deliberate: a dropped, cancelled or failed run costs
+ nothing, because the next run sees the same unreleased pin and builds it.
+
+ repin For corpora whose upstream moved: `git ls-remote <url> HEAD` per repo,
+ and if the default-branch head differs from the manifest's `sha`, open a
+ PULL REQUEST that moves the pin. A human merges; the packs follow on
+ merge (the `plan` above sees the new, unreleased pin).
+
+Registry facts this relies on (tools/xerj-code/hub/):
+ * `<slug>.json` is `{"corpus": slug, "cloned_at": ..., "repos": [{"repo", "url",
+ "sha", "review": {...}, ...}]}`; the catalogue pin is `repos[0].sha`.
+ * `backlog/backlog-100.json` rows carry `status` (live|candidate|...), `lane`
+ (A = git manifest, B = harvested pack recipe) and `refresh`
+ (pinned|weekly|daily). Only live lane-A rows have a manifest this pipeline
+ can build.
+"""
+
+from __future__ import annotations
+
+import argparse
+import dataclasses
+import hashlib
+import json
+import os
+import pathlib
+import re
+import subprocess
+import sys
+from datetime import datetime, timezone
+from typing import Callable, Iterable, Optional
+
+SHA_RE = re.compile(r"^[0-9a-f]{40}$")
+# Same rule as `valid_slug` in xerj-hub: a slug is joined into filesystem paths
+# and release tags, so it must be a plain lower-case name.
+SLUG_RE = re.compile(r"^[a-z0-9]([a-z0-9._-]*[a-z0-9])?$")
+
+# `refresh` class -> catalogue `refresh_cadence_days` (plan §1: "7 for code, 1 for
+# feeds"). `pinned` is code at a release tag: weekly cadence for the freshness
+# warning, but never auto-re-pinned (see REPIN_CLASSES).
+CADENCE_DAYS = {"daily": 1, "weekly": 7, "pinned": 7}
+
+# The refresh classes the scheduled re-pin job may propose a new pin for.
+# `pinned` is NOT among them: PROGRAM-100.md §3 says a pinned corpus is code at a
+# release tag whose "pin is the promise", and comparing a release tag with the
+# default-branch head would differ for every one of ~500 corpora every week.
+# `--include-pinned` is the deliberate override.
+REPIN_CLASSES = ("weekly", "daily")
+
+BRANCH_PREFIX = "hub-repin/"
+BOT_NAME = "xerj-org"
+BOT_EMAIL = "[email protected]"
+
+
+class RegistryError(Exception):
+ """A manifest or backlog row this pipeline cannot use."""
+
+
+# ── registry ────────────────────────────────────────────────────────────────
+
+
[email protected](frozen=True)
+class Repo:
+ name: str
+ url: str
+ sha: str
+
+
[email protected](frozen=True)
+class Corpus:
+ slug: str
+ path: pathlib.Path # the manifest file
+ refresh: str # pinned | weekly | daily
+ repos: tuple[Repo, ...]
+
+ @property
+ def pin_sha(self) -> str:
+ """The catalogue's pin: the first repo's sha (xerj-hub catalogue.rs)."""
+ return self.repos[0].sha
+
+ @property
+ def pin8(self) -> str:
+ return self.pin_sha[:8]
+
+ @property
+ def cadence_days(self) -> int:
+ return CADENCE_DAYS.get(self.refresh, 7)
+
+
+def load_manifest(path: pathlib.Path, refresh: str = "pinned") -> Corpus:
+ """Parse one registry manifest, refusing anything the pack builder would."""
+ try:
+ data = json.loads(path.read_text())
+ except (OSError, json.JSONDecodeError) as e:
+ raise RegistryError(f"{path.name}: unreadable ({e})") from e
+ slug = data.get("corpus")
+ if slug != path.stem or not isinstance(slug, str) or not SLUG_RE.match(slug):
+ raise RegistryError(f"{path.name}: corpus {slug!r} must equal the file name")
+ repos = []
+ for i, r in enumerate(data.get("repos") or []):
+ sha = r.get("sha", "")
+ if not SHA_RE.match(sha):
+ raise RegistryError(f"{path.name}: repos[{i}].sha is not a 40-hex commit")
+ if not r.get("url") or not r.get("repo"):
+ raise RegistryError(f"{path.name}: repos[{i}] lacks repo/url")
+ repos.append(Repo(r["repo"], r["url"], sha))
+ if not repos:
+ raise RegistryError(f"{path.name}: no repos")
+ return Corpus(slug, path, refresh, tuple(repos))
+
+
+def load_live(
+ registry: pathlib.Path, backlog: pathlib.Path
+) -> tuple[list[Corpus], list[str]]:
+ """Live lane-A corpora that have a usable manifest, plus warnings for the
+ ones that are live but cannot be built (so a bad manifest is loud, not silent)."""
+ rows = json.loads(backlog.read_text()).get("corpora", [])
+ corpora: list[Corpus] = []
+ warnings: list[str] = []
+ for row in rows:
+ if row.get("status") != "live" or row.get("lane") != "A":
+ continue
+ slug = row.get("slug", "")
+ manifest = registry / f"{slug}.json"
+ if not manifest.is_file():
+ warnings.append(f"{slug}: live in the backlog but {manifest.name} is missing")
+ continue
+ try:
+ corpora.append(load_manifest(manifest, row.get("refresh", "pinned")))
+ except RegistryError as e:
+ warnings.append(str(e))
+ corpora.sort(key=lambda c: c.slug)
+ return corpora, warnings
+
+
+# ── plan: which packs need building ─────────────────────────────────────────
+
+
+def pack_tag(slug: str, pin8: str) -> str:
+ return f"pack-{slug}-{pin8}"
+
+
+def released_tag(tags: Iterable[str], slug: str, pin8: str) -> Optional[str]:
+ """The published release tag for this pin, or None. When the publish step had
+ to retag past a burned tag (GitHub's immutable releases never free one), the
+ newest `-rN` wins."""
+ base = pack_tag(slug, pin8)
+ rx = re.compile(re.escape(base) + r"(?:-r(\d+))?")
+ best: Optional[int] = None
+ for t in tags:
+ m = rx.fullmatch(t)
+ if m:
+ n = int(m.group(1) or 1)
+ best = n if best is None else max(best, n)
+ if best is None:
+ return None
+ return base if best == 1 else f"{base}-r{best}"
+
+
+def is_released(tags: Iterable[str], slug: str, pin8: str) -> bool:
+ """A published release exists for this pin (its tag, or a `-rN` retag)."""
+ return released_tag(tags, slug, pin8) is not None
+
+
+def plan(
+ corpora: list[Corpus],
+ published_tags: Iterable[str],
+ slugs: Optional[set[str]] = None,
+ force: bool = False,
+ max_builds: int = 40,
+) -> dict:
+ """The build matrix. `slugs` restricts to named corpora; `force` rebuilds a
+ pin that is already released (the publish step then takes a `-rN` tag)."""
+ tags = list(published_tags)
+ due = []
+ for c in corpora:
+ if slugs is not None and c.slug not in slugs:
+ continue
+ if not force and is_released(tags, c.slug, c.pin8):
+ continue
+ due.append(
+ {
+ "slug": c.slug,
+ "pin8": c.pin8,
+ "tag": pack_tag(c.slug, c.pin8),
+ "cadence_days": c.cadence_days,
+ }
+ )
+ chosen = due[:max_builds]
+ return {
+ "include": chosen,
+ "count": len(chosen),
+ "due": len(due),
+ "capped": len(due) > len(chosen),
+ }
+
+
+# ── repin: has upstream moved? ──────────────────────────────────────────────
+
+
[email protected](frozen=True)
+class Move:
+ repo: str
+ url: str
+ old: str
+ new: str
+
+
+class Proposal:
+ slug: str
+ path: str # repo-relative manifest path
+ moves: list[Move]
+ new_text: str
+ pin_date: str
+ proposal_id: str # 8 hex, identifies THIS set of new shas
+ branch: str
+ title: str
+ body: str
+
+ def to_json(self) -> dict:
+ return dataclasses.asdict(self)
+
+
+GitHeadFn = Callable[[str], Optional[str]]
+
+
+def git_head_of(url: str, allow_protocols: str = "https") -> Optional[str]:
+ """`git ls-remote <url> HEAD`: the default-branch head, or None when the
+ remote is unreachable or advertises no HEAD.
+
+ The protocol allowlist is the point: a manifest URL is reviewed, but
+ `ext::<command>` would run it, so git is told to speak `https` only (the
+ tests widen it to `file`). Never prompts for credentials."""
+ env = dict(os.environ)
+ env["GIT_ALLOW_PROTOCOL"] = allow_protocols
+ env["GIT_TERMINAL_PROMPT"] = "0"
+ scheme = url.split("://", 1)[0] if "://" in url else ""
+ if scheme not in allow_protocols.split(":"):
+ return None
+ try:
+ out = subprocess.run(
+ ["git", "ls-remote", url, "HEAD"],
+ capture_output=True,
+ text=True,
+ timeout=90,
+ env=env,
+ check=False,
+ )
+ except (OSError, subprocess.TimeoutExpired):
+ return None
+ if out.returncode != 0:
+ return None
+ for line in out.stdout.splitlines():
+ sha, _, ref = line.partition("\t")
+ if ref.strip() == "HEAD" and SHA_RE.match(sha):
+ return sha
+ return None
+
+
+def _repo_span(text: str, name: str) -> tuple[int, int]:
+ """The [start, end) of the JSON object text for repo `name` — from its
+ `"repo": "<name>"` key to the next `"repo":` key (or the end). Scoping the
+ sha replacement to it is what keeps two repos pinned at the same commit apart."""
+ m = re.search(r'"repo"\s*:\s*"' + re.escape(name) + r'"', text)
+ if not m:
+ raise RegistryError(f"repo {name!r} not found in the manifest text")
+ nxt = re.search(r'"repo"\s*:', text[m.end() :])
+ return m.start(), (m.end() + nxt.start() if nxt else len(text))
+
+
+def rewrite_manifest(text: str, moves: list[Move], pin_date: str) -> str:
+ """Move the pins and stamp the top-level `pin_date`, changing NOTHING else —
+ the manifest is hand-formatted, so a JSON round-trip would reformat the whole
+ file and bury the one-line change in diff noise."""
+ for mv in moves:
+ start, end = _repo_span(text, mv.repo)
+ span = text[start:end]
+ rx = re.compile(r'("sha"\s*:\s*")' + re.escape(mv.old) + r'(")')
+ if len(rx.findall(span)) != 1:
+ raise RegistryError(
+ f"repo {mv.repo!r}: expected exactly one sha {mv.old[:8]}… to replace"
+ )
+ text = text[:start] + rx.sub(lambda m: m.group(1) + mv.new + m.group(2), span) + text[end:]
+
+ stamp = f'"pin_date":"{pin_date}"'
+ head = re.match(r'^(\{\s*"corpus"\s*:\s*"[^"]*"\s*,)', text)
+ existing = re.search(r'"pin_date"\s*:\s*"[^"]*"', text)
+ repos_at = text.find('"repos"')
+ if existing and (repos_at < 0 or existing.start() < repos_at):
+ text = text[: existing.start()] + stamp + text[existing.end() :]
+ elif head:
+ text = head.group(1) + stamp + "," + text[head.end() :]
+ else:
+ raise RegistryError("manifest does not start with {\"corpus\":...; cannot place pin_date")
+ return text
+
+
+def _compare_url(url: str, old: str, new: str) -> Optional[str]:
+ m = re.match(r"^https://github\.com/([^/]+)/([^/]+?)(?:\.git)?/?$", url)
+ return f"https://github.com/{m.group(1)}/{m.group(2)}/compare/{old[:12]}...{new[:12]}" if m else None
+
+
+def title_for(c: Corpus, moves: list[Move]) -> str:
+ first = moves[0]
+ if len(c.repos) == 1:
+ return f"hub: re-pin {c.slug} to {first.new[:8]}"
+ more = f" (+{len(moves) - 1} more)" if len(moves) > 1 else ""
+ return f"hub: re-pin {c.slug}: {first.repo} to {first.new[:8]}{more}"
+
+
+def render_body(c: Corpus, moves: list[Move], pin_date: str) -> str:
+ rows = []
+ for mv in moves:
+ cmp_url = _compare_url(mv.url, mv.old, mv.new)
+ link = f"[compare]({cmp_url})" if cmp_url else "(no compare link: not a github.com URL)"
+ rows.append(f"| `{mv.repo}` | {mv.url} | `{mv.old[:12]}` | `{mv.new[:12]}` | {link} |")
+ first_moved = next((m for m in moves if m.repo == c.repos[0].name), None)
+ catalogue_note = (
+ f"The catalogue pin (the first repo's sha) moves to `{first_moved.new[:8]}`: merging "
+ f"this builds and publishes `pack-{c.slug}-{first_moved.new[:8]}`, and clients see the "
+ "new pin on their next `xerj hub sync`."
+ if first_moved
+ else "The catalogue pin (the FIRST repo's sha) does not change, so existing clients "
+ "will not see a new pin from this PR alone; the pack content would be rebuilt only "
+ "under a `-rN` release tag."
+ )
+ return "\n".join(
+ [
+ f"The upstream default branch of `{c.slug}` moved since the manifest was pinned "
+ f"(refresh class `{c.refresh}`). This PR was opened by the scheduled "
+ "`hub packs` re-pin job; **a human decides whether to merge it.**",
+ "",
+ "| repo | url | pinned | upstream HEAD | |",
+ "|---|---|---|---|---|",
+ *rows,
+ "",
+ catalogue_note,
+ "",
+ "Before merging:",
+ "",
+ "- [ ] Re-open each repo's licence file **at the new sha** and confirm the `review` "
+ "block still holds (Gate G4). The block is carried over unchanged; its `at` date is "
+ "the old review, not this one.",
+ "- [ ] `files` / `bytes` are NOT recomputed by this PR; they describe the old checkout.",
+ f"- [ ] `pin_date` is stamped `{pin_date}` (the day the pin moved).",
+ "",
+ "If upstream rewrote history (the old sha no longer resolves), withdraw the corpus "
+ "instead of re-pinning it (PROGRAM-100.md §3).",
+ ]
+ )
+
+
+def find_proposals(
+ corpora: list[Corpus],
+ classes: Iterable[str],
+ head_of: GitHeadFn,
+ today: str,
+ only: Optional[set[str]] = None,
+) -> tuple[list[Proposal], list[str]]:
+ """Corpora in `classes` whose upstream HEAD differs from the pinned sha."""
+ classes = set(classes)
+ proposals: list[Proposal] = []
+ notes: list[str] = []
+ for c in corpora:
+ if c.refresh not in classes or (only is not None and c.slug not in only):
+ continue
+ moves: list[Move] = []
+ for r in c.repos:
+ head = head_of(r.url)
+ if head is None:
+ notes.append(f"{c.slug}/{r.name}: cannot read HEAD of {r.url}; skipped")
+ elif head != r.sha:
+ moves.append(Move(r.name, r.url, r.sha, head))
+ if not moves:
+ continue
+ try:
+ new_text = rewrite_manifest(c.path.read_text(), moves, today)
+ # The rewrite must be exactly the intended change, nothing more.
+ _assert_only_pins_changed(c.path.read_text(), new_text, moves, today)
+ except RegistryError as e:
+ notes.append(f"{c.slug}: {e}; skipped")
+ continue
+ pid = hashlib.sha256("".join(m.new for m in moves).encode()).hexdigest()[:8]
+ proposals.append(
+ Proposal(
+ slug=c.slug,
+ path=c.path.name,
+ moves=moves,
+ new_text=new_text,
+ pin_date=today,
+ proposal_id=pid,
+ branch=f"{BRANCH_PREFIX}{c.slug}-{pid}",
+ title=title_for(c, moves),
+ body=render_body(c, moves, today),
+ )
+ )
+ return proposals, notes
+
+
+def _assert_only_pins_changed(old: str, new: str, moves: list[Move], today: str) -> None:
+ """Belt and braces: parse both texts and require that the ONLY differences are
+ the moved shas and `pin_date`."""
+ a, b = json.loads(old), json.loads(new)
+ expect = {m.repo: m.new for m in moves}
+ for ra, rb in zip(a["repos"], b["repos"]):
+ want = expect.get(ra["repo"], ra["sha"])
+ if rb["sha"] != want:
+ raise RegistryError(f"rewrite produced the wrong sha for {ra['repo']}")
+ ra2, rb2 = dict(ra, sha=""), dict(rb, sha="")
+ if ra2 != rb2:
+ raise RegistryError(f"rewrite changed more than the sha of {ra['repo']}")
+ if len(a["repos"]) != len(b["repos"]):
+ raise RegistryError("rewrite changed the number of repos")
+ a.pop("repos"), b.pop("repos")
+ b_pin = b.pop("pin_date", None)
+ a.pop("pin_date", None)
+ if b_pin != today or a != b:
+ raise RegistryError("rewrite changed more than the pins and pin_date")
+
+
+# ── repin: opening the pull requests ────────────────────────────────────────
+
+
+def _run(cmd: list[str], cwd: Optional[pathlib.Path] = None, check: bool = True) -> subprocess.CompletedProcess:
+ return subprocess.run(cmd, cwd=cwd, capture_output=True, text=True, check=check)
+
+
+def _gh_json(gh: str, args: list[str], cwd: pathlib.Path):
+ out = _run([gh, *args], cwd=cwd)
+ return json.loads(out.stdout or "null")
+
+
+def _open_pr(
+ p: Proposal, repo_root: pathlib.Path, rel: str, base: str, gh: str, remote: str
+) -> str:
+ """Branch from the base, commit the one-file change, push, open the PR."""
+ _run(["git", "checkout", "-q", "-B", p.branch, f"{remote}/{base}"], cwd=repo_root)
+ (repo_root / rel).write_text(p.new_text)
+ _run(["git", "add", rel], cwd=repo_root)
+ _run(
+ [
+ "git",
+ "-c",
+ f"user.name={BOT_NAME}",
+ "-c",
+ f"user.email={BOT_EMAIL}",
+ "commit",
+ "-q",
+ "-m",
+ p.title,
+ "-m",
+ "Opened by the scheduled hub packs re-pin job; see the pull request.",
+ ],
+ cwd=repo_root,
+ )
+ # The branch name embeds the proposal id, so it is ours alone: force is safe.
+ _run(["git", "push", "-q", "--force", remote, p.branch], cwd=repo_root)
+ return _run(
+ [gh, "pr", "create", "--base", base, "--head", p.branch, "--title", p.title, "--body", p.body],
+ cwd=repo_root,
+ ).stdout.strip()
+
+
+def apply_proposals(
+ proposals: list[Proposal],
+ repo_root: pathlib.Path,
+ registry_rel: str,
+ base: str,
+ max_prs: int,
+ gh: str = "gh",
+ remote: str = "origin",
+) -> tuple[list[str], int]:
+ """Open one PR per proposal, at most `max_prs` NEW ones. Idempotent: a
+ proposal whose branch already has a PR (open, merged or closed) is left alone,
+ so a declined re-pin is not re-opened every week, and skipping it does not use
+ up the cap. Opening a PR for a newer proposal closes the older open ones for
+ the same corpus as superseded. One failing proposal does not stop the rest.
+ Returns (one log line per decision, number of failures)."""
+ log: list[str] = []
+ failures = 0
+ opened = 0
+ for p in proposals:
+ try:
+ existing = _gh_json(
+ gh, ["pr", "list", "--head", p.branch, "--state", "all", "--json", "number,state"], repo_root
+ )
+ if existing:
+ log.append(
+ f"{p.slug}: already proposed as PR #{existing[0]['number']} "
+ f"({existing[0]['state']}); skipped"
+ )
+ continue
+ if opened >= max_prs:
+ log.append(f"{p.slug}: over the {max_prs}-PR cap for this run; the next run continues")
+ continue
+ url = _open_pr(p, repo_root, f"{registry_rel}/{p.path}", base, gh, remote)
+ opened += 1
+ log.append(f"{p.slug}: opened {url}")
+
+ open_prs = _gh_json(
+ gh, ["pr", "list", "--state", "open", "--limit", "200", "--json", "number,headRefName"], repo_root
+ ) or []
+ mine = f"{BRANCH_PREFIX}{p.slug}-"
+ for other in open_prs:
+ head = other["headRefName"]
+ if head.startswith(mine) and head != p.branch:
+ _run(
+ [gh, "pr", "close", str(other["number"]), "--delete-branch", "--comment", f"Superseded by {url}"],
+ cwd=repo_root,
+ check=False,
+ )
+ log.append(f"{p.slug}: closed superseded PR #{other['number']}")
+ except subprocess.CalledProcessError as e:
+ failures += 1
+ detail = " ".join((e.stderr or "").split())[:300]
+ log.append(f"{p.slug}: FAILED ({' '.join(map(str, e.cmd[:3]))}: {detail})")
+ # Leave the checkout where it started, whatever happened above.
+ _run(["git", "checkout", "-q", "--detach", f"{remote}/{base}"], cwd=repo_root, check=False)
+ return log, failures
+
+
+# ── catalogue: which packs to download, and whether the result is sane ──────
+
+CATALOGUE_FORMAT_VERSION = 1
+CATALOGUE_MAX_BYTES = 2 * 1024 * 1024 # plan §4: the real registry's catalogue is under 2 MB
+
+
+def fetch_list(corpora: list[Corpus], published_tags: Iterable[str]) -> list[tuple[str, str, str]]:
+ """`(slug, pin8, release tag)` for every live corpus whose CURRENT pin has a
+ published pack. A corpus without one (not built yet, or the build failed) is
+ simply absent: the catalogue lists corpora that have a pack."""
+ tags = list(published_tags)
+ out = []
+ for c in corpora:
+ tag = released_tag(tags, c.slug, c.pin8)
+ if tag:
+ out.append((c.slug, c.pin8, tag))
+ return out
+
+
+def check_catalogue(
+ raw: bytes,
+ corpora: list[Corpus],
+ repo: str,
+ previous: Optional[bytes] = None,
+) -> list[str]:
+ """Everything that must hold before a freshly built catalogue replaces the live
+ one; the list of violations (empty = fine).
+
+ Beyond shape, two guards the signature cannot give: every entry's pin must be
+ the manifest's pin and its URL must point at that pin's pack release, and —
+ when the live catalogue is given — a corpus that is listed there and still live
+ must not vanish. A catalogue is a complete snapshot, so a half-failed build
+ would otherwise silently delist corpora; a stale catalogue is the lesser harm."""
+ errors: list[str] = []
+ if len(raw) >= CATALOGUE_MAX_BYTES:
+ errors.append(f"the catalogue is {len(raw)} bytes, over the {CATALOGUE_MAX_BYTES}-byte budget")
+ try:
+ cat = json.loads(raw)
+ except json.JSONDecodeError as e:
+ return [*errors, f"not valid JSON: {e}"]
+ if cat.get("format_version") != CATALOGUE_FORMAT_VERSION:
+ errors.append(f"format_version is {cat.get('format_version')!r}, expected {CATALOGUE_FORMAT_VERSION}")
+ entries = cat.get("corpora")
+ if not isinstance(entries, list) or not entries:
+ return [*errors, "no corpora"]
+
+ live = {c.slug: c for c in corpora}
+ listed: set[str] = set()
+ for e in entries:
+ slug = e.get("slug", "")
+ c = live.get(slug)
+ if c is None:
+ errors.append(f"{slug or '?'}: not a live lane-A corpus in the registry")
+ continue
+ if 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}")
+ 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") + "$"
+ )
+ if not re.match(want, url):
+ errors.append(f"{slug}: pack_url {url!r} is not the release asset of pin {c.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", ""))):
+ errors.append(f"{slug}: pack_sha256 is not 64 hex")
+ size = e.get("pack_bytes")
+ if not isinstance(size, int) or isinstance(size, bool) or size <= 0:
+ errors.append(f"{slug}: pack_bytes is not a positive integer")
+
+ if previous is not None:
+ try:
+ before = {x.get("slug") for x in json.loads(previous).get("corpora", [])}
+ except (json.JSONDecodeError, AttributeError):
+ before = set()
+ for slug in sorted((before & set(live)) - listed):
+ errors.append(f"{slug}: in the live catalogue and still live, but missing from the new one")
+ return errors
+
+
+# ── command line ────────────────────────────────────────────────────────────
+
+
+def _today() -> str:
+ return datetime.now(timezone.utc).date().isoformat()
+
+
+def _split(value: str) -> list[str]:
+ return [s for s in re.split(r"[,\s]+", value or "") if s]
+
+
+def cmd_plan(a: argparse.Namespace) -> int:
+ corpora, warnings = load_live(pathlib.Path(a.registry), pathlib.Path(a.backlog))
+ for w in warnings:
+ print(f"::warning::{w}", file=sys.stderr)
+ tags = pathlib.Path(a.published_tags).read_text().split() if a.published_tags else []
+ slugs = set(_split(a.slugs)) if a.slugs and a.slugs != "all" else None
+ if slugs:
+ unknown = slugs - {c.slug for c in corpora}
+ for s in sorted(unknown):
+ print(f"::warning::{s}: not a live lane-A corpus with a manifest; ignored", file=sys.stderr)
+ result = plan(corpora, tags, slugs, a.force, a.max_builds)
+ print(
+ f"plan: {result['due']} due, {result['count']} scheduled"
+ + (" (capped; the next run continues)" if result["capped"] else ""),
+ file=sys.stderr,
+ )
+ print(json.dumps(result, separators=(",", ":")))
+ return 0
+
+
+def cmd_fetch_list(a: argparse.Namespace) -> int:
+ corpora, warnings = load_live(pathlib.Path(a.registry), pathlib.Path(a.backlog))
+ for w in warnings:
+ print(f"::warning::{w}", file=sys.stderr)
+ 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:
+ print(f"{slug}\t{pin8}\t{tag}")
+ return 0
+
+
+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)
+ if a.allow_drops:
+ errors = [e for e in errors if "missing from the new one" not in e]
+ for e in errors:
+ print(f"::error title=catalogue::{e}", file=sys.stderr)
+ if errors:
+ print(f"check-catalogue: {len(errors)} problem(s); the catalogue is NOT fit to publish", file=sys.stderr)
+ return 1
+ n = len(json.loads(raw)["corpora"])
+ print(f"check-catalogue: {n} corpora, {len(raw)} bytes, consistent with the registry", file=sys.stderr)
+ return 0
+
+
+def cmd_repin(a: argparse.Namespace) -> int:
+ registry = pathlib.Path(a.registry)
+ corpora, warnings = load_live(registry, pathlib.Path(a.backlog))
+ for w in warnings:
+ print(f"::warning::{w}", file=sys.stderr)
+ classes = _split(a.classes) or list(REPIN_CLASSES)
+ if a.include_pinned and "pinned" not in classes:
+ classes.append("pinned")
+ allow = "file:https" if a.allow_file_urls else "https"
+ proposals, notes = find_proposals(
+ corpora, classes, lambda u: git_head_of(u, allow), a.today or _today(),
+ set(_split(a.slugs)) if a.slugs else None,
+ )
+ for n in notes:
+ print(f"::warning::{n}", file=sys.stderr)
+ print(f"repin: classes={','.join(classes)}; {len(proposals)} corpus(es) moved", file=sys.stderr)
+ if a.out:
+ pathlib.Path(a.out).write_text(json.dumps([p.to_json() for p in proposals], indent=1))
+ if not a.apply:
+ for p in proposals:
+ print(f"would open: {p.title} [{p.branch}]")
+ return 0
+ root = pathlib.Path(a.repo_root).resolve()
+ log, failures = apply_proposals(
+ proposals, root, str(registry.resolve().relative_to(root)), a.base, a.max_prs, a.gh
+ )
+ for line in log:
+ print(line)
+ if failures:
+ print(f"::error::{failures} re-pin PR(s) could not be opened", file=sys.stderr)
+ return 1 if failures else 0
+
+
+def main(argv: Optional[list[str]] = None) -> int:
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ sub = ap.add_subparsers(dest="cmd", required=True)
+
+ p = sub.add_parser("plan", help="print the build matrix as JSON")
+ p.add_argument("--registry", required=True)
+ p.add_argument("--backlog", required=True)
+ p.add_argument("--published-tags", help="file with one published release tag per line")
+ p.add_argument("--slugs", default="", help="comma list, or 'all' (default: everything due)")
+ p.add_argument("--force", action="store_true", help="rebuild pins that already have a release")
+ p.add_argument("--max-builds", type=int, default=40)
+ p.set_defaults(fn=cmd_plan)
+
+ f = sub.add_parser("fetch-list", help="slug<TAB>pin8<TAB>tag of each live corpus's published pack")
+ f.add_argument("--registry", required=True)
+ f.add_argument("--backlog", required=True)
+ f.add_argument("--published-tags", required=True)
+ f.set_defaults(fn=cmd_fetch_list)
+
+ k = sub.add_parser("check-catalogue", help="refuse a catalogue that disagrees with the registry")
+ k.add_argument("--registry", required=True)
+ k.add_argument("--backlog", required=True)
+ k.add_argument("--catalogue", required=True)
+ k.add_argument("--previous", help="the live catalogue, to refuse delisting a live corpus")
+ k.add_argument("--repo", required=True, help="owner/name of the repository that hosts the releases")
+ k.add_argument("--allow-drops", action="store_true", help="accept delisting corpora that are still live")
+ k.set_defaults(fn=cmd_check_catalogue)
+
+ r = sub.add_parser("repin", help="propose pin moves for corpora whose upstream moved")
+ r.add_argument("--registry", required=True)
+ r.add_argument("--backlog", required=True)
+ r.add_argument("--classes", default=",".join(REPIN_CLASSES))
+ r.add_argument("--include-pinned", action="store_true", help="also re-pin the `pinned` class")
+ r.add_argument("--slugs", default="")
+ r.add_argument("--today", default="")
+ r.add_argument("--out", help="write the proposals as JSON")
+ r.add_argument("--apply", action="store_true", help="open the PRs (default: print what would be opened)")
+ r.add_argument("--repo-root", default=".")
+ r.add_argument("--base", default="corpus-hub")
+ r.add_argument("--max-prs", type=int, default=25)
+ r.add_argument("--gh", default="gh")
+ r.add_argument("--allow-file-urls", action="store_true", help=argparse.SUPPRESS)
+ r.set_defaults(fn=cmd_repin)
+
+ a = ap.parse_args(argv)
+ return a.fn(a)
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tools/hub-packs/test_hub_packs.py b/tools/hub-packs/test_hub_packs.py
new file mode 100644
index 000000000..d40a072fa
--- /dev/null
+++ b/tools/hub-packs/test_hub_packs.py
@@ -0,0 +1,701 @@
+#!/usr/bin/env python3
+"""Tests for hub_packs.py — the planning and re-pin logic behind
+.github/workflows/hub-packs.yml.
+
+Stdlib `unittest`, no network: the "upstream" repositories are local ones, spoken
+to over `file://` (the one place the production code's https-only protocol
+allowlist is widened, on purpose), and `gh` is a stub that records its calls.
+
+ python3 tools/hub-packs/test_hub_packs.py
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import pathlib
+import subprocess
+import sys
+import tempfile
+import textwrap
+import unittest
+
+sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
+import hub_packs as hp # noqa: E402
+
+SHA_A = "a" * 40
+SHA_B = "b" * 40
+SHA_C = "c" * 40
+
+
+def manifest_text(slug: str, repos: list[tuple[str, str, str]], extra: str = "") -> str:
+ """A manifest in the registry's own hand-formatted style (one repo per line)."""
+ body = ",\n".join(
+ f' {{"repo":"{n}","url":"{u}","licence":"MIT","sha":"{s}","files":3,"bytes":99,'
+ f'"review":{{"spdx":"MIT","use":"adapt-with-attribution","by":"xerj-org","at":"2026-08-12"}}}}'
+ for n, u, s in repos
+ )
+ return f'{{"corpus":"{slug}",{extra}"cloned_at":"2026-08-06T20:24:00Z","repos":[\n{body}\n]}}\n'
+
+
+def write_registry(root: pathlib.Path, rows: list[dict], manifests: dict[str, str]) -> tuple[pathlib.Path, pathlib.Path]:
+ reg = root / "tools" / "xerj-code" / "hub"
+ (reg / "backlog").mkdir(parents=True, exist_ok=True)
+ backlog = reg / "backlog" / "backlog-100.json"
+ backlog.write_text(json.dumps({"corpora": rows}))
+ for slug, text in manifests.items():
+ (reg / f"{slug}.json").write_text(text)
+ return reg, backlog
+
+
+def row(slug: str, status="live", lane="A", refresh="pinned") -> dict:
+ return {"slug": slug, "status": status, "lane": lane, "refresh": refresh, "cat": "DB"}
+
+
+def git(*args: str, cwd: pathlib.Path, env=None) -> str:
+ out = subprocess.run(
+ ["git", *args], cwd=cwd, capture_output=True, text=True, check=True,
+ env={**os.environ, **(env or {})},
+ )
+ return out.stdout.strip()
+
+
+GIT_ID = ["-c", "user.name=t", "-c", "[email protected]"]
+
+
+def make_upstream(root: pathlib.Path, name: str, commits: int = 2) -> tuple[pathlib.Path, list[str]]:
+ """A local repository with `commits` commits; returns (path, [shas oldest first])."""
+ path = root / name
+ path.mkdir(parents=True)
+ git("init", "-q", "-b", "main", cwd=path)
+ shas = []
+ for i in range(commits):
+ (path / "f.txt").write_text(f"v{i}\n")
+ git("add", "f.txt", cwd=path)
+ git(*GIT_ID, "commit", "-q", "-m", f"c{i}", cwd=path)
+ shas.append(git("rev-parse", "HEAD", cwd=path))
+ return path, shas
+
+
+class RegistryTests(unittest.TestCase):
+ def test_load_live_keeps_only_live_lane_a_corpora_that_have_a_manifest(self):
+ with tempfile.TemporaryDirectory() as t:
+ reg, backlog = write_registry(
+ pathlib.Path(t),
+ [
+ row("alpha"),
+ row("beta", status="candidate"),
+ row("gamma", lane="B"),
+ row("delta"), # live, but its manifest is missing
+ row("eps", refresh="weekly"),
+ ],
+ {
+ "alpha": manifest_text("alpha", [("alpha", "https://example.test/a", SHA_A)]),
+ "beta": manifest_text("beta", [("beta", "https://example.test/b", SHA_B)]),
+ "gamma": manifest_text("gamma", [("gamma", "https://example.test/g", SHA_B)]),
+ "eps": manifest_text("eps", [("eps", "https://example.test/e", SHA_C)]),
+ },
+ )
+ corpora, warnings = hp.load_live(reg, backlog)
+ self.assertEqual([c.slug for c in corpora], ["alpha", "eps"])
+ self.assertEqual([c.refresh for c in corpora], ["pinned", "weekly"])
+ self.assertEqual(corpora[0].pin8, "aaaaaaaa")
+ self.assertEqual(len(warnings), 1)
+ self.assertIn("delta", warnings[0])
+
+ def test_the_catalogue_pin_is_the_first_repos_sha(self):
+ with tempfile.TemporaryDirectory() as t:
+ reg, backlog = write_registry(
+ pathlib.Path(t),
+ [row("multi")],
+ {"multi": manifest_text("multi", [("one", "https://x.test/1", SHA_A), ("two", "https://x.test/2", SHA_B)])},
+ )
+ (c,), _ = hp.load_live(reg, backlog)
+ self.assertEqual(c.pin_sha, SHA_A)
+
+ def test_a_malformed_live_manifest_is_a_warning_not_a_crash(self):
+ with tempfile.TemporaryDirectory() as t:
+ reg, backlog = write_registry(
+ pathlib.Path(t),
+ [row("good"), row("shortsha"), row("renamed")],
+ {
+ "good": manifest_text("good", [("good", "https://x.test/g", SHA_A)]),
+ "shortsha": manifest_text("shortsha", [("r", "https://x.test/r", "abc123")]),
+ "renamed": manifest_text("other", [("r", "https://x.test/r", SHA_A)]),
+ },
+ )
+ corpora, warnings = hp.load_live(reg, backlog)
+ self.assertEqual([c.slug for c in corpora], ["good"])
+ self.assertEqual(len(warnings), 2)
+
+
+class PlanTests(unittest.TestCase):
+ def corpora(self, t: str, slugs: list[tuple[str, str, str]]):
+ rows = [row(s, refresh=r) for s, _, r in slugs]
+ mans = {s: manifest_text(s, [(s, f"https://x.test/{s}", sha)]) for s, sha, _ in slugs}
+ reg, backlog = write_registry(pathlib.Path(t), rows, mans)
+ return hp.load_live(reg, backlog)[0]
+
+ def test_a_pin_without_a_release_is_due_and_a_released_one_is_not(self):
+ with tempfile.TemporaryDirectory() as t:
+ cs = self.corpora(t, [("alpha", SHA_A, "pinned"), ("beta", SHA_B, "pinned")])
+ plan = hp.plan(cs, ["pack-alpha-aaaaaaaa"])
+ self.assertEqual([m["slug"] for m in plan["include"]], ["beta"])
+ self.assertEqual(plan["include"][0]["tag"], "pack-beta-bbbbbbbb")
+ self.assertEqual((plan["count"], plan["due"], plan["capped"]), (1, 1, False))
+
+ def test_a_retagged_release_counts_as_released(self):
+ # Immutable releases burn a tag; the publish step falls back to -rN.
+ with tempfile.TemporaryDirectory() as t:
+ cs = self.corpora(t, [("alpha", SHA_A, "pinned")])
+ self.assertEqual(hp.plan(cs, ["pack-alpha-aaaaaaaa-r2"])["count"], 0)
+ self.assertEqual(hp.plan(cs, ["pack-alpha-aaaaaaaa-rc"])["count"], 1, "-rc is not -rN")
+ self.assertEqual(hp.plan(cs, ["pack-alpha-aaaaaaaa9"])["count"], 1, "a longer pin8 is another pin")
+
+ def test_only_the_current_pin_matters(self):
+ # Released for the OLD pin; the manifest moved on: due again.
+ with tempfile.TemporaryDirectory() as t:
+ cs = self.corpora(t, [("alpha", SHA_B, "pinned")])
+ self.assertEqual(hp.plan(cs, ["pack-alpha-aaaaaaaa"])["count"], 1)
+
+ def test_slugs_restrict_and_force_rebuilds_a_released_pin(self):
+ with tempfile.TemporaryDirectory() as t:
+ cs = self.corpora(t, [("alpha", SHA_A, "pinned"), ("beta", SHA_B, "pinned")])
+ tags = ["pack-alpha-aaaaaaaa", "pack-beta-bbbbbbbb"]
+ self.assertEqual(hp.plan(cs, tags)["count"], 0)
+ forced = hp.plan(cs, tags, slugs={"alpha"}, force=True)
+ self.assertEqual([m["slug"] for m in forced["include"]], ["alpha"])
+
+ def test_the_cap_limits_a_run_and_says_so(self):
+ with tempfile.TemporaryDirectory() as t:
+ cs = self.corpora(t, [(f"c{i}", SHA_A, "pinned") for i in range(5)])
+ plan = hp.plan(cs, [], max_builds=2)
+ self.assertEqual((plan["count"], plan["due"], plan["capped"]), (2, 5, True))
+ self.assertEqual([m["slug"] for m in plan["include"]], ["c0", "c1"])
+
+ def test_cadence_follows_the_refresh_class(self):
+ with tempfile.TemporaryDirectory() as t:
+ cs = self.corpora(t, [("a", SHA_A, "daily"), ("b", SHA_A, "weekly"), ("c", SHA_A, "pinned")])
+ got = {m["slug"]: m["cadence_days"] for m in hp.plan(cs, [])["include"]}
+ self.assertEqual(got, {"a": 1, "b": 7, "c": 7})
+
+
+class RewriteTests(unittest.TestCase):
+ def test_only_the_sha_and_pin_date_change(self):
+ old = manifest_text("quinn", [("quinn", "https://x.test/q", SHA_A)])
+ new = hp.rewrite_manifest(old, [hp.Move("quinn", "https://x.test/q", SHA_A, SHA_B)], "2026-10-14")
+ self.assertEqual(
+ new,
+ old.replace(SHA_A, SHA_B).replace('{"corpus":"quinn",', '{"corpus":"quinn","pin_date":"2026-10-14",'),
+ "a textual one-line change, not a reformat",
+ )
+ a, b = json.loads(old), json.loads(new)
+ self.assertEqual(b["pin_date"], "2026-10-14")
+ self.assertEqual(b["repos"][0]["sha"], SHA_B)
+ self.assertEqual(b["repos"][0]["review"], a["repos"][0]["review"], "the licence review is carried over")
+
+ def test_an_existing_pin_date_is_replaced_not_duplicated(self):
+ old = manifest_text("quinn", [("quinn", "https://x.test/q", SHA_A)], extra='"pin_date":"2026-01-01",')
+ new = hp.rewrite_manifest(old, [hp.Move("quinn", "https://x.test/q", SHA_A, SHA_B)], "2026-10-14")
+ self.assertEqual(new.count("pin_date"), 1)
+ self.assertEqual(json.loads(new)["pin_date"], "2026-10-14")
+
+ def test_two_repos_at_the_same_commit_move_independently(self):
+ old = manifest_text("pair", [("one", "https://x.test/1", SHA_A), ("two", "https://x.test/2", SHA_A)])
+ new = hp.rewrite_manifest(old, [hp.Move("two", "https://x.test/2", SHA_A, SHA_B)], "2026-10-14")
+ shas = [r["sha"] for r in json.loads(new)["repos"]]
+ self.assertEqual(shas, [SHA_A, SHA_B], "the repo that did not move keeps its pin")
+
+ def test_both_repos_can_move_in_one_rewrite(self):
+ old = manifest_text("pair", [("one", "https://x.test/1", SHA_A), ("two", "https://x.test/2", SHA_B)])
+ new = hp.rewrite_manifest(
+ old,
+ [hp.Move("one", "https://x.test/1", SHA_A, SHA_C), hp.Move("two", "https://x.test/2", SHA_B, SHA_A)],
+ "2026-10-14",
+ )
+ self.assertEqual([r["sha"] for r in json.loads(new)["repos"]], [SHA_C, SHA_A])
+
+ def test_a_sha_that_is_not_there_is_refused(self):
+ old = manifest_text("quinn", [("quinn", "https://x.test/q", SHA_A)])
+ with self.assertRaises(hp.RegistryError):
+ hp.rewrite_manifest(old, [hp.Move("quinn", "u", SHA_B, SHA_C)], "2026-10-14")
+ with self.assertRaises(hp.RegistryError):
+ hp.rewrite_manifest(old, [hp.Move("nope", "u", SHA_A, SHA_C)], "2026-10-14")
+
+ def test_a_manifest_that_does_not_open_with_corpus_cannot_take_a_pin_date(self):
+ old = '{"repos":[{"repo":"q","url":"u","sha":"%s"}],"corpus":"q"}' % SHA_A
+ with self.assertRaises(hp.RegistryError):
+ hp.rewrite_manifest(old, [hp.Move("q", "u", SHA_A, SHA_B)], "2026-10-14")
+
+ def test_the_rewrite_check_catches_a_change_beyond_the_pins(self):
+ old = manifest_text("quinn", [("quinn", "https://x.test/q", SHA_A)])
+ sneaky = old.replace(SHA_A, SHA_B).replace('"files":3', '"files":4').replace(
+ '{"corpus":"quinn",', '{"corpus":"quinn","pin_date":"2026-10-14",'
+ )
+ with self.assertRaises(hp.RegistryError):
+ hp._assert_only_pins_changed(old, sneaky, [hp.Move("quinn", "u", SHA_A, SHA_B)], "2026-10-14")
+
+
+class RepinTests(unittest.TestCase):
+ def setUp(self):
+ self._tmp = tempfile.TemporaryDirectory()
+ self.root = pathlib.Path(self._tmp.name)
+
+ def tearDown(self):
+ self._tmp.cleanup()
+
+ def corpora(self, spec: list[tuple[str, str, str, str]]):
+ """(slug, refresh, url, sha) -> loaded corpora."""
+ rows = [row(s, refresh=r) for s, r, _, _ in spec]
+ mans = {s: manifest_text(s, [(s, u, sha)]) for s, _, u, sha in spec}
+ reg, backlog = write_registry(self.root, rows, mans)
+ return hp.load_live(reg, backlog)[0]
+
+ def test_pinned_corpora_are_never_proposed_unless_asked(self):
+ cs = self.corpora([("rel", "pinned", "https://x.test/rel", SHA_A), ("feed", "weekly", "https://x.test/feed", SHA_A)])
+ heads = {"https://x.test/rel": SHA_B, "https://x.test/feed": SHA_B}
+ props, _ = hp.find_proposals(cs, hp.REPIN_CLASSES, heads.get, "2026-10-14")
+ self.assertEqual([p.slug for p in props], ["feed"], "the pin is the promise for release-tag corpora")
+ props, _ = hp.find_proposals(cs, ["pinned", "weekly"], heads.get, "2026-10-14")
+ self.assertEqual([p.slug for p in props], ["feed", "rel"])
+
+ def test_an_unmoved_head_proposes_nothing(self):
+ cs = self.corpora([("feed", "weekly", "https://x.test/feed", SHA_A)])
+ props, notes = hp.find_proposals(cs, hp.REPIN_CLASSES, lambda u: SHA_A, "2026-10-14")
+ self.assertEqual((props, notes), ([], []))
+
+ def test_an_unreachable_remote_is_a_note_and_never_a_proposal(self):
+ cs = self.corpora([("feed", "weekly", "https://x.test/feed", SHA_A)])
+ props, notes = hp.find_proposals(cs, hp.REPIN_CLASSES, lambda u: None, "2026-10-14")
+ self.assertEqual(props, [])
+ self.assertIn("cannot read HEAD", notes[0])
+
+ def test_a_proposal_names_itself_by_what_it_would_pin(self):
+ cs = self.corpora([("feed", "weekly", "https://github.com/o/r", SHA_A)])
+ (p,), _ = hp.find_proposals(cs, hp.REPIN_CLASSES, lambda u: SHA_B, "2026-10-14")
+ (q,), _ = hp.find_proposals(cs, hp.REPIN_CLASSES, lambda u: SHA_C, "2026-10-14")
+ self.assertRegex(p.branch, r"^hub-repin/feed-[0-9a-f]{8}$")
+ self.assertNotEqual(p.branch, q.branch, "a newer upstream head is a new proposal")
+ self.assertEqual(p.title, "hub: re-pin feed to bbbbbbbb")
+ self.assertIn("compare/aaaaaaaaaaaa...bbbbbbbbbbbb", p.body)
+ self.assertIn("pack-feed-bbbbbbbb", p.body)
+ self.assertIn("licence file **at the new sha**", p.body)
+
+ def test_a_move_that_leaves_the_catalogue_pin_alone_says_so(self):
+ reg, backlog = write_registry(
+ self.root,
+ [row("multi", refresh="weekly")],
+ {"multi": manifest_text("multi", [("one", "https://x.test/1", SHA_A), ("two", "https://x.test/2", SHA_B)])},
+ )
+ cs, _ = hp.load_live(reg, backlog)
+ heads = {"https://x.test/1": SHA_A, "https://x.test/2": SHA_C}
+ (p,), _ = hp.find_proposals(cs, hp.REPIN_CLASSES, heads.get, "2026-10-14")
+ self.assertEqual(p.title, "hub: re-pin multi: two to cccccccc")
+ self.assertIn("does not change", p.body)
+ self.assertEqual([r["sha"] for r in json.loads(p.new_text)["repos"]], [SHA_A, SHA_C])
+
+ def test_ls_remote_reads_the_default_branch_head_of_a_real_repository(self):
+ up, shas = make_upstream(self.root, "up")
+ url = f"file://{up}"
+ self.assertEqual(hp.git_head_of(url, "file:https"), shas[-1])
+ cs = self.corpora([("feed", "weekly", url, shas[0])])
+ (p,), notes = hp.find_proposals(cs, hp.REPIN_CLASSES, lambda u: hp.git_head_of(u, "file:https"), "2026-10-14")
+ self.assertEqual(notes, [])
+ self.assertEqual(p.moves, [hp.Move("feed", url, shas[0], shas[1])])
+ # ...and once re-pinned there is nothing left to propose.
+ cs2 = self.corpora([("feed", "weekly", url, shas[1])])
+ self.assertEqual(hp.find_proposals(cs2, hp.REPIN_CLASSES, lambda u: hp.git_head_of(u, "file:https"), "2026-10-14")[0], [])
+
+ def test_only_https_is_spoken_by_default(self):
+ up, _ = make_upstream(self.root, "up")
+ marker = self.root / "pwned"
+ self.assertIsNone(hp.git_head_of(f"file://{up}"), "file:// needs the test-only widening")
+ self.assertIsNone(hp.git_head_of(f"ext::sh -c touch% {marker}"), "ext:: would run a command")
+ self.assertIsNone(hp.git_head_of("git://example.test/r"))
+ self.assertIsNone(hp.git_head_of(f"--upload-pack=touch {marker}"))
+ self.assertFalse(marker.exists())
+
+ def test_the_protocol_allowlist_also_holds_inside_git_itself(self):
+ # Defence in depth: even if the scheme gate above were bypassed, the
+ # environment `git_head_of` hands git must refuse an `ext::` transport.
+ marker = self.root / "pwned-by-ext"
+ out = subprocess.run(
+ ["git", "ls-remote", f"ext::sh -c touch% {marker}", "HEAD"],
+ capture_output=True, text=True, timeout=30,
+ env={**os.environ, "GIT_ALLOW_PROTOCOL": "https", "GIT_TERMINAL_PROMPT": "0"},
+ )
+ self.assertNotEqual(out.returncode, 0)
+ self.assertFalse(marker.exists(), "GIT_ALLOW_PROTOCOL=https stops an ext:: URL from running anything")
+
+ def test_a_dead_remote_is_none_not_an_exception(self):
+ self.assertIsNone(hp.git_head_of(f"file://{self.root}/nowhere", "file:https"))
+
+
+GH_STUB = textwrap.dedent(
+ """\
+ #!{python}
+ # A stand-in for `gh`: records every call, keeps a tiny PR table in a JSON file.
+ import json, sys
+ STATE = {state!r}
+ st = json.load(open(STATE))
+ st["calls"].append(sys.argv[1:])
+ a = sys.argv[1:]
+ def save(): json.dump(st, open(STATE, "w"))
+ if a[:2] == ["pr", "list"]:
+ if "--head" in a:
+ head = a[a.index("--head") + 1]
+ print(json.dumps([p for p in st["prs"] if p["headRefName"] == head]))
+ else:
+ print(json.dumps([p for p in st["prs"] if p["state"] == "OPEN"]))
+ elif a[:2] == ["pr", "create"]:
+ head = a[a.index("--head") + 1]
+ if head in st.get("fail_create", []):
+ save(); print("create refused", file=sys.stderr); sys.exit(1)
+ n = st["next"]; st["next"] += 1
+ st["prs"].append({{"number": n, "state": "OPEN", "headRefName": head}})
+ print(f"https://github.com/o/r/pull/{{n}}")
+ elif a[:2] == ["pr", "close"]:
+ for p in st["prs"]:
+ if p["number"] == int(a[2]): p["state"] = "CLOSED"
+ save()
+ """
+)
+
+
+class ApplyTests(unittest.TestCase):
+ """The real git against a local bare "origin"; only `gh` is a stub."""
+
+ def setUp(self):
+ self._tmp = tempfile.TemporaryDirectory()
+ self.root = pathlib.Path(self._tmp.name)
+ origin = self.root / "origin.git"
+ git("init", "-q", "--bare", "-b", "corpus-hub", str(origin), cwd=self.root)
+ self.work = self.root / "work"
+ git("clone", "-q", str(origin), str(self.work), cwd=self.root)
+ git("checkout", "-q", "-b", "corpus-hub", cwd=self.work)
+ self.reg = self.work / "tools" / "xerj-code" / "hub"
+ self.reg.mkdir(parents=True)
+ self.slugs = ["feed", "other"]
+ for s in self.slugs:
+ (self.reg / f"{s}.json").write_text(manifest_text(s, [(s, f"https://github.com/o/{s}", SHA_A)]))
+ git("add", "-A", cwd=self.work)
+ git(*GIT_ID, "commit", "-q", "-m", "registry", cwd=self.work)
+ git("push", "-q", "origin", "corpus-hub", cwd=self.work)
+ self.origin = origin
+ self.state = self.root / "gh-state.json"
+ self.state.write_text(json.dumps({"calls": [], "prs": [], "next": 100}))
+ self.gh = self.root / "gh"
+ self.gh.write_text(GH_STUB.format(python=sys.executable, state=str(self.state)))
+ self.gh.chmod(0o755)
+
+ def tearDown(self):
+ self._tmp.cleanup()
+
+ def proposals(self, slugs=None, new=SHA_B):
+ corpora, _ = hp.load_live(
+ self.reg,
+ self._backlog([row(s, refresh="weekly") for s in (slugs or self.slugs)]),
+ )
+ return hp.find_proposals(corpora, hp.REPIN_CLASSES, lambda u: new, "2026-10-14")[0]
+
+ def _backlog(self, rows):
+ path = self.reg / "backlog" / "backlog-100.json"
+ path.parent.mkdir(exist_ok=True)
+ path.write_text(json.dumps({"corpora": rows}))
+ return path
+
+ def apply(self, props, max_prs=25):
+ return hp.apply_proposals(props, self.work, "tools/xerj-code/hub", "corpus-hub", max_prs, gh=str(self.gh))
+
+ def gh_state(self):
+ return json.loads(self.state.read_text())
+
+ def test_it_opens_a_pr_whose_commit_changes_exactly_one_manifest(self):
+ (p,) = self.proposals(["feed"])
+ log, failures = self.apply([p])
+
+ self.assertEqual(failures, 0)
+ self.assertEqual(log, ["feed: opened https://github.com/o/r/pull/100"])
+ tip = git("rev-parse", p.branch, cwd=self.origin)
+ self.assertEqual(
+ git("diff", "--name-only", "corpus-hub", p.branch, cwd=self.origin).splitlines(),
+ ["tools/xerj-code/hub/feed.json"],
+ )
+ self.assertEqual(git("show", f"{p.branch}:tools/xerj-code/hub/feed.json", cwd=self.origin) + "\n", p.new_text)
+ self.assertEqual(git("log", "-1", "--format=%an <%ae>", tip, cwd=self.origin), "xerj-org <[email protected]>")
+ self.assertEqual(git("log", "-1", "--format=%s", tip, cwd=self.origin), "hub: re-pin feed to bbbbbbbb")
+ # The checkout is left where the job found it: detached at the base.
+ self.assertEqual(git("rev-parse", "HEAD", cwd=self.work), git("rev-parse", "origin/corpus-hub", cwd=self.work))
+ create = [c for c in self.gh_state()["calls"] if c[:2] == ["pr", "create"]][0]
+ self.assertEqual(create[create.index("--base") + 1], "corpus-hub")
+
+ def test_a_second_run_with_the_same_upstream_opens_nothing(self):
+ (p,) = self.proposals(["feed"])
+ self.apply([p])
+ before = len(self.gh_state()["calls"])
+
+ log, failures = self.apply(self.proposals(["feed"]))
+
+ self.assertEqual(failures, 0)
+ self.assertIn("already proposed as PR #100", log[0])
+ creates = [c for c in self.gh_state()["calls"][before:] if c[:2] == ["pr", "create"]]
+ self.assertEqual(creates, [], "idempotent: no duplicate PR")
+
+ def test_a_declined_proposal_is_not_reopened(self):
+ (p,) = self.proposals(["feed"])
+ self.apply([p])
+ st = self.gh_state()
+ st["prs"][0]["state"] = "CLOSED" # a human closed it unmerged
+ self.state.write_text(json.dumps(st))
+
+ log, _ = self.apply(self.proposals(["feed"]))
+
+ self.assertIn("already proposed", log[0])
+ self.assertEqual([p for p in self.gh_state()["prs"] if p["state"] == "OPEN"], [])
+
+ def test_the_cap_counts_new_prs_only(self):
+ first, second = self.proposals()
+ self.apply([first]) # `feed` is already proposed
+
+ log, _ = self.apply([first, second], max_prs=1)
+
+ self.assertIn("already proposed", log[0])
+ self.assertIn("opened", log[1], "skipping an existing proposal does not spend the cap")
+ log, _ = self.apply(self.proposals(new=SHA_C), max_prs=1)
+ self.assertEqual(sum("opened" in l for l in log), 1)
+ self.assertTrue(any("over the 1-PR cap" in l for l in log))
+
+ def test_a_newer_proposal_supersedes_the_open_older_one(self):
+ (old,) = self.proposals(["feed"], new=SHA_B)
+ self.apply([old])
+ (new,) = self.proposals(["feed"], new=SHA_C)
+
+ log, _ = self.apply([new])
+
+ self.assertNotEqual(old.branch, new.branch)
+ self.assertTrue(any("closed superseded PR #100" in l for l in log), log)
+ open_heads = [p["headRefName"] for p in self.gh_state()["prs"] if p["state"] == "OPEN"]
+ self.assertEqual(open_heads, [new.branch])
+
+ def test_one_failure_does_not_stop_the_rest(self):
+ first, second = self.proposals()
+ st = self.gh_state()
+ st["fail_create"] = [first.branch]
+ self.state.write_text(json.dumps(st))
+
+ log, failures = self.apply([first, second])
+
+ self.assertEqual(failures, 1)
+ self.assertIn("FAILED", log[0])
+ self.assertIn("opened", log[1], "the next corpus still gets its PR")
+ self.assertEqual(git("rev-parse", "HEAD", cwd=self.work), git("rev-parse", "origin/corpus-hub", cwd=self.work))
+
+
+class CatalogueTests(unittest.TestCase):
+ REPO = "xerj-org/xerj"
+
+ def setUp(self):
+ self._tmp = tempfile.TemporaryDirectory()
+ self.root = pathlib.Path(self._tmp.name)
+ rows = [row("alpha"), row("beta")]
+ mans = {
+ "alpha": manifest_text("alpha", [("alpha", "https://x.test/a", SHA_A)]),
+ "beta": manifest_text("beta", [("beta", "https://x.test/b", SHA_B)]),
+ }
+ 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 entry(self, slug: str, sha: str, retag: str = "", **over) -> dict:
+ pin8 = sha[:8]
+ url = (
+ f"https://github.com/{self.REPO}/releases/download/pack-{slug}-{pin8}{retag}/"
+ f"{slug}-{pin8}.hubpack.tar.zst"
+ )
+ e = {
+ "slug": slug,
+ "pin_sha": sha,
+ "pack_url": url,
+ "sig_url": url + ".sig",
+ "pack_sha256": "ab" * 32,
+ "pack_bytes": 12345,
+ }
+ e.update(over)
+ return e
+
+ def cat(self, *entries: dict, version: int = 1) -> bytes:
+ return json.dumps({"format_version": version, "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)
+
+ def test_fetch_list_names_the_newest_retag_of_each_current_pin(self):
+ tags = ["pack-alpha-aaaaaaaa", "pack-alpha-aaaaaaaa-r2", "pack-alpha-aaaaaaaa-r10", "pack-beta-00000000"]
+ # beta's release is for an OLD pin, so beta has no pack for its current one.
+ self.assertEqual(hp.fetch_list(self.corpora, tags), [("alpha", "aaaaaaaa", "pack-alpha-aaaaaaaa-r10")])
+ self.assertEqual(hp.fetch_list(self.corpora, ["pack-alpha-aaaaaaaa"])[0][2], "pack-alpha-aaaaaaaa")
+
+ def test_a_consistent_catalogue_passes(self):
+ raw = self.cat(self.entry("alpha", SHA_A), self.entry("beta", SHA_B, retag="-r2"))
+ self.assertEqual(self.check(raw), [])
+
+ def test_every_kind_of_inconsistency_is_reported(self):
+ bad = self.cat(
+ self.entry("alpha", SHA_C), # not the manifest's pin
+ self.entry("beta", SHA_B, pack_url="https://evil.test/beta.zst"),
+ self.entry("ghost", SHA_A), # not live
+ )
+ errors = self.check(bad)
+ joined = "\n".join(errors)
+ self.assertIn("alpha: pin_sha cccccccccccc is not the manifest's aaaaaaaa", joined)
+ self.assertIn("beta: pack_url 'https://evil.test/beta.zst' is not the release asset of pin bbbbbbbb", joined)
+ self.assertIn("beta: sig_url is not pack_url + '.sig'", joined)
+ self.assertIn("ghost: not a live lane-A corpus", joined)
+
+ def test_a_pack_url_from_another_repository_or_pin_is_refused(self):
+ other_repo = self.entry("alpha", SHA_A).copy()
+ other_repo["pack_url"] = other_repo["pack_url"].replace(self.REPO, "someone/else")
+ other_repo["sig_url"] = other_repo["pack_url"] + ".sig"
+ self.assertTrue(any("pack_url" in e for e in self.check(self.cat(other_repo))))
+ wrong_pin = self.entry("alpha", SHA_A, pack_url=self.entry("alpha", SHA_B)["pack_url"])
+ wrong_pin["sig_url"] = wrong_pin["pack_url"] + ".sig"
+ self.assertTrue(any("pack_url" in e for e in self.check(self.cat(wrong_pin))))
+
+ def test_hash_and_size_fields_must_be_plausible(self):
+ errors = self.check(
+ self.cat(self.entry("alpha", SHA_A, pack_sha256="xyz", pack_bytes=0), self.entry("beta", SHA_B, pack_bytes=True))
+ )
+ joined = "\n".join(errors)
+ self.assertIn("alpha: pack_sha256 is not 64 hex", joined)
+ self.assertIn("alpha: pack_bytes is not a positive integer", joined)
+ self.assertIn("beta: pack_bytes is not a positive integer", joined, "a JSON true is not a size")
+
+ def test_shape_failures_stop_early(self):
+ self.assertIn("no corpora", self.check(self.cat())[-1])
+ self.assertTrue(any("format_version" in e for e in self.check(self.cat(self.entry("alpha", SHA_A), version=2))))
+ self.assertTrue(any("not valid JSON" in e for e in self.check(b"{nope")))
+ big = self.cat(self.entry("alpha", SHA_A, pad="x" * hp.CATALOGUE_MAX_BYTES))
+ self.assertTrue(any("budget" in e for e in self.check(big)))
+
+ def test_a_corpus_listed_twice_is_refused(self):
+ errors = self.check(self.cat(self.entry("alpha", SHA_A), self.entry("alpha", SHA_A)))
+ self.assertIn("alpha: listed twice", errors)
+
+ def test_delisting_a_corpus_that_is_still_live_is_refused(self):
+ live = self.cat(self.entry("alpha", SHA_A), self.entry("beta", SHA_B))
+ shrunk = self.cat(self.entry("alpha", SHA_A))
+ errors = self.check(shrunk, previous=live)
+ self.assertEqual(errors, ["beta: in the live catalogue and still live, but missing from the new one"])
+ self.assertEqual(self.check(live, previous=live), [])
+
+ def test_a_corpus_that_is_no_longer_live_may_leave_the_catalogue(self):
+ previous = self.cat(self.entry("alpha", SHA_A), self.entry("retired", SHA_C))
+ raw = self.cat(self.entry("alpha", SHA_A))
+ self.assertEqual(self.check(raw, previous=previous), [], "`retired` is not live in the registry")
+
+ def test_command_line_exit_codes(self):
+ cat_path = self.root / "catalogue.json"
+ live_path = self.root / "live.json"
+ live_path.write_bytes(self.cat(self.entry("alpha", SHA_A), self.entry("beta", SHA_B)))
+
+ def run(*extra: str):
+ return subprocess.run(
+ [sys.executable, hp.__file__, "check-catalogue", "--registry", str(self.reg), "--backlog",
+ str(self.backlog), "--catalogue", str(cat_path), "--repo", self.REPO, *extra],
+ capture_output=True, text=True,
+ )
+
+ cat_path.write_bytes(self.cat(self.entry("alpha", SHA_A), self.entry("beta", SHA_B)))
+ ok = run("--previous", str(live_path))
+ self.assertEqual(ok.returncode, 0, ok.stderr)
+ self.assertIn("2 corpora", ok.stderr)
+
+ cat_path.write_bytes(self.cat(self.entry("alpha", SHA_A)))
+ refused = run("--previous", str(live_path))
+ self.assertEqual(refused.returncode, 1)
+ self.assertIn("::error title=catalogue::beta", refused.stderr)
+ self.assertIn("NOT fit to publish", refused.stderr)
+ self.assertEqual(run("--previous", str(live_path), "--allow-drops").returncode, 0, "the explicit override")
+
+ def test_fetch_list_command_prints_tab_separated_rows(self):
+ tags = self.root / "tags.txt"
+ tags.write_text("pack-alpha-aaaaaaaa-r2\n")
+ out = subprocess.run(
+ [sys.executable, hp.__file__, "fetch-list", "--registry", str(self.reg), "--backlog", str(self.backlog),
+ "--published-tags", str(tags)],
+ capture_output=True, text=True,
+ )
+ self.assertEqual(out.returncode, 0, out.stderr)
+ self.assertEqual(out.stdout, "alpha\taaaaaaaa\tpack-alpha-aaaaaaaa-r2\n")
+ self.assertIn("1 of 2 live corpora", out.stderr)
+
+
+class CommandLineTests(unittest.TestCase):
+ def run_cli(self, *argv: str) -> tuple[int, str, str]:
+ out = subprocess.run(
+ [sys.executable, str(pathlib.Path(hp.__file__)), *argv], capture_output=True, text=True
+ )
+ return out.returncode, out.stdout, out.stderr
+
+ def test_plan_prints_the_matrix_json_the_workflow_feeds_to_fromjson(self):
+ with tempfile.TemporaryDirectory() as t:
+ reg, backlog = write_registry(
+ pathlib.Path(t),
+ [row("alpha"), row("beta")],
+ {
+ "alpha": manifest_text("alpha", [("alpha", "https://x.test/a", SHA_A)]),
+ "beta": manifest_text("beta", [("beta", "https://x.test/b", SHA_B)]),
+ },
+ )
+ tags = pathlib.Path(t) / "tags.txt"
+ tags.write_text("pack-alpha-aaaaaaaa\nrust-v1.0.0\n")
+ rc, out, err = self.run_cli(
+ "plan", "--registry", str(reg), "--backlog", str(backlog), "--published-tags", str(tags)
+ )
+ self.assertEqual(rc, 0, err)
+ plan = json.loads(out)
+ self.assertEqual([m["slug"] for m in plan["include"]], ["beta"])
+ self.assertEqual(plan["count"], 1)
+ self.assertIn("plan: 1 due, 1 scheduled", err)
+
+ def test_plan_with_nothing_due_still_emits_valid_json(self):
+ with tempfile.TemporaryDirectory() as t:
+ reg, backlog = write_registry(pathlib.Path(t), [], {})
+ rc, out, _ = self.run_cli("plan", "--registry", str(reg), "--backlog", str(backlog))
+ self.assertEqual(rc, 0)
+ self.assertEqual(json.loads(out), {"include": [], "count": 0, "due": 0, "capped": False})
+
+ def test_plan_warns_about_a_requested_slug_that_is_not_live(self):
+ with tempfile.TemporaryDirectory() as t:
+ reg, backlog = write_registry(
+ pathlib.Path(t), [row("alpha")], {"alpha": manifest_text("alpha", [("alpha", "https://x.test/a", SHA_A)])}
+ )
+ rc, out, err = self.run_cli(
+ "plan", "--registry", str(reg), "--backlog", str(backlog), "--slugs", "alpha,ghost"
+ )
+ self.assertEqual(rc, 0)
+ self.assertIn("::warning::ghost", err)
+ self.assertEqual(json.loads(out)["count"], 1)
+
+ def test_repin_dry_run_lists_what_it_would_open_and_touches_nothing(self):
+ with tempfile.TemporaryDirectory() as t:
+ root = pathlib.Path(t)
+ up, shas = make_upstream(root, "up")
+ url = f"file://{up}"
+ reg, backlog = write_registry(
+ root, [row("feed", refresh="daily")], {"feed": manifest_text("feed", [("feed", url, shas[0])])}
+ )
+ before = (reg / "feed.json").read_text()
+ rc, out, err = self.run_cli(
+ "repin", "--registry", str(reg), "--backlog", str(backlog), "--classes", "daily",
+ "--allow-file-urls", "--today", "2026-10-14",
+ )
+ self.assertEqual(rc, 0, err)
+ self.assertIn(f"would open: hub: re-pin feed to {shas[1][:8]}", out)
+ self.assertEqual((reg / "feed.json").read_text(), before, "dry run leaves the manifest alone")
+
+
+if __name__ == "__main__":
+ unittest.main(verbosity=2)