The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(pm): preserve pinned binary inputs in R2
ethernetc8a968250544
diff --git a/.github/actions/setup-pm/action.yml b/.github/actions/setup-pm/action.ymlindex 2dda0343ac1..169cae3ea87 100644--- a/.github/actions/setup-pm/action.yml+++ b/.github/actions/setup-pm/action.yml@@ -4,6 +4,9 @@ inputs:toolchain:description: python (Python and uv), node (Node and npm), or all.default: python+ archive-inputs:+ description: Use protected R2 credentials to preserve and retrieve the selected toolchain before installation.+ default: 'false'extras:description: 'JSON extras: omit for tools; [] installs core; dev selects an isolated test environment plus the test dependency group.'default: ''@@ -90,6 +93,17 @@ runs:path: ${{ steps.prepare.outputs.store }}key: setup-pm-tools-v1-${{ steps.prepare.outputs.target }}-${{ inputs.toolchain }}-${{ hashFiles('pm/lock.json') }}-${{ inputs.cache-suffix }}+ - name: Preserve and retrieve the pinned toolchain+ if: inputs.archive-inputs == 'true'+ shell: bash+ env:+ _PM_ACTION: ${{ github.action_path }}+ _PM_BOOTSTRAP: ${{ steps.prepare.outputs.bootstrap-python }}+ _PM_TOOLCHAIN: ${{ inputs.toolchain }}+ run: |+ "$_PM_BOOTSTRAP" -S "$_PM_ACTION/../../../scripts/ci/setup_toolchain.py" archive-inputs \+ --toolchain "$_PM_TOOLCHAIN" --home "$HERMES_HOME"+- name: Install and verify tools through PMid: installshell: bashdiff --git a/.github/workflows/archive-inputs.yml b/.github/workflows/archive-inputs.ymlnew file mode 100644index 00000000000..3e69a582255--- /dev/null+++ b/.github/workflows/archive-inputs.yml@@ -0,0 +1,42 @@+name: Archive pinned PM inputs++on:+ push:+ branches: [main]+ paths:+ - 'pm/lock.json'+ - 'pm/artifact-mirror.json'+ - 'scripts/termux/runtime_libs.json'+ - 'scripts/ci/archive_inputs.py'+ - '.github/workflows/archive-inputs.yml'+ workflow_call:+ inputs:+ sha:+ description: 'The admitted commit whose pins are archived.'+ required: true+ type: string+ workflow_dispatch:++permissions:+ contents: read++jobs:+ archive-inputs:+ name: Preserve every pinned HTTP input+ if: github.event_name != 'pull_request' && github.event_name != 'pull_request_target'+ runs-on: ubuntu-24.04+ environment: release-signing+ timeout-minutes: 60+ env:+ CLOUDFLARE_R2_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_R2_ACCOUNT_ID }}+ CLOUDFLARE_R2_ACCESS_KEY_ID: ${{ secrets.CLOUDFLARE_R2_ACCESS_KEY_ID }}+ CLOUDFLARE_R2_SECRET_ACCESS_KEY: ${{ secrets.CLOUDFLARE_R2_SECRET_ACCESS_KEY }}+ CLOUDFLARE_R2_BUCKET: ${{ vars.CLOUDFLARE_R2_BUCKET }}+ steps:+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2+ with:+ ref: ${{ inputs.sha || github.sha }}+ persist-credentials: false+ # Runner Python is intentional: the toolchain's upstream may be gone.+ - name: Verify and archive every pinned input+ run: python3 -m scripts.ci.archive_inputsdiff --git a/.github/workflows/desktop-bundled-release.yml b/.github/workflows/desktop-bundled-release.ymlindex 4af7fb7f110..219db1243a1 100644--- a/.github/workflows/desktop-bundled-release.yml+++ b/.github/workflows/desktop-bundled-release.yml@@ -241,10 +241,19 @@ jobs:# ── Windows builders (REAL) ───────────────────────────────────────────────# Windows assembly and publication depend on these native Windows legs.+ archive-inputs:+ name: Archive every pinned input+ if: inputs.release-phase == '' || inputs.release-phase == 'candidate'+ needs: [validate]+ uses: ./.github/workflows/archive-inputs.yml+ with:+ sha: ${{ needs.validate.outputs.sha }}+ secrets: inherit+build-win32:name: bundled ${{ matrix.target.label }}if: inputs.termux_only != true && (inputs.release-phase == '' || inputs.release-phase == 'candidate')- needs: validate+ needs: [validate, archive-inputs]runs-on: ${{ matrix.target.runner }}environment: release-signingtimeout-minutes: 900@@ -305,6 +314,7 @@ jobs:uses: ./.github/actions/setup-pmwith:toolchain: all+ archive-inputs: true# The payload tools cache does not include uv's built wheels.cache-python: true@@ -365,6 +375,10 @@ jobs:restore-keys: |pm-store-v2-${{ matrix.target.label }}-+ - name: Retrieve pinned payload inputs from R2+ shell: bash+ run: python -m scripts.ci.archive_inputs --target '${{ matrix.target.label }}' --store apps/desktop/build/agent-payload/tools+- name: Resolve electron's default download cache pathshell: bashrun: |@@ -539,7 +553,7 @@ jobs:build-darwin:name: bundled ${{ matrix.target.label }}if: inputs.termux_only != true && (inputs.release-phase == '' || inputs.release-phase == 'candidate')- needs: validate+ needs: [validate, archive-inputs]runs-on: ${{ matrix.target.runner }}environment: release-signingtimeout-minutes: 360@@ -586,6 +600,7 @@ jobs:uses: ./.github/actions/setup-pmwith:toolchain: all+ archive-inputs: true# The payload tools cache does not include uv's built wheels.cache-python: true@@ -617,6 +632,10 @@ jobs:restore-keys: |pm-store-v2-${{ matrix.target.label }}-+ - name: Retrieve pinned payload inputs from R2+ shell: bash+ run: python -m scripts.ci.archive_inputs --target '${{ matrix.target.label }}' --store apps/desktop/build/agent-payload/tools+- name: Resolve electron's default download cache pathshell: bashrun: |@@ -874,6 +893,7 @@ jobs:uses: ./.github/actions/setup-pmwith:toolchain: all+ archive-inputs: truecache-python: false- name: Install the locked Windows bundle tooling@@ -1040,6 +1060,7 @@ jobs:uses: ./.github/actions/setup-pmwith:toolchain: all+ archive-inputs: truecache-python: false- name: Install the locked Windows bundle tooling@@ -1225,7 +1246,7 @@ jobs:termux-deb:name: Build + publish the termux .deb (aarch64)- needs: [validate]+ needs: [validate, archive-inputs]if: inputs.upload_release == true || inputs.release-phase == 'candidate' || inputs.build_commit != ''runs-on: ubuntu-24.04-armenvironment: release-signing@@ -1255,6 +1276,7 @@ jobs:uses: ./.github/actions/setup-pmwith:toolchain: python+ archive-inputs: truecache-python: false- name: Derive the channel from the tag@@ -1299,6 +1321,10 @@ jobs:restore-keys: |termux-payload-+ - name: Preserve and retrieve pinned inputs+ shell: bash+ run: python -m scripts.ci.archive_inputs --target linux-arm64-bionic --payload termux-build/payload --store "$HERMES_RUNTIME_DIR"+- name: Build CPython into the payloadshell: bashrun: bash scripts/termux/build_cpython.sh termux-build/payloaddiff --git a/.github/workflows/termux-verify.yml b/.github/workflows/termux-verify.ymlindex ef52260173c..7a55cddd9a8 100644--- a/.github/workflows/termux-verify.yml+++ b/.github/workflows/termux-verify.yml@@ -53,6 +53,7 @@ jobs:tests/test_termux_python_linkage.py tests/test_termux_retag_wheel.py \tests/test_termux_build_wheels.py \tests/test_termux_wheelhouse_cache.py tests/test_termux_runtime_libs.py \+ tests/scripts/test_archive_inputs.py \tests/test_termux_launchers.py tests/test_pm_bionic.py \tests/pm/test_stage_only.py tests/pm/test_deb_safety.py tests/test_stage_apt_repo.py \tests/test_run_tests_shell.py@@ -82,8 +83,15 @@ jobs:native-runtime:name: Verify bionic runtime tools+ if: github.event_name != 'pull_request' && github.event_name != 'pull_request_target'runs-on: ubuntu-24.04-arm+ environment: release-signingtimeout-minutes: 45+ env:+ CLOUDFLARE_R2_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_R2_ACCOUNT_ID }}+ CLOUDFLARE_R2_ACCESS_KEY_ID: ${{ secrets.CLOUDFLARE_R2_ACCESS_KEY_ID }}+ CLOUDFLARE_R2_SECRET_ACCESS_KEY: ${{ secrets.CLOUDFLARE_R2_SECRET_ACCESS_KEY }}+ CLOUDFLARE_R2_BUCKET: ${{ vars.CLOUDFLARE_R2_BUCKET }}steps:- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2with:@@ -93,7 +101,10 @@ jobs:persist-credentials: false- uses: ./.github/actions/setup-pmwith:+ archive-inputs: truecache-python: false+ - name: Preserve and retrieve pinned inputs+ run: python -m scripts.ci.archive_inputs --target linux-arm64-bionic --payload termux-build/payload --store "$HERMES_RUNTIME_DIR"- name: Stage the pinned bionic runtimesrun: |bash scripts/termux/build_cpython.sh termux-build/payloaddiff --git a/docs/shared-bundle-builds.md b/docs/shared-bundle-builds.mdindex be0b50273f8..40177b8f850 100644--- a/docs/shared-bundle-builds.md+++ b/docs/shared-bundle-builds.md@@ -91,6 +91,40 @@ Cross-target staging verifies the published entry before deleting its archives.Failed or paused installs keep downloads for retry. Cleanup leaves unrelatedarchives and resumable partials alone. A later repair may download again.+## Pinned binary inputs++`python -m scripts.ci.archive_inputs` preserves every HTTPS artifact in+`pm/lock.json`, across all targets, plus the Termux runtime-library and license+pins. `pm/artifact-mirror.json` owns the public mirror location. Object keys+are `upstream/sha256/HASH`, independent of filenames and release tags.++CI requests R2 first. Only 404 permits an upstream download. It verifies the+existing SHA256 before an immutable `If-None-Match: *` upload, then downloads+and verifies the stored object. Corrupt bytes, denied access, and failed+uploads stop the build. Concurrent writers may reuse identical bytes but+cannot replace an existing object.++The all-target workflow runs on pin changes on main, manual dispatch, and as+an admitted release prerequisite. It uses runner Python before the pinned+toolchain is available. Protected build jobs opt into the same R2-first step+through `setup-pm`'s `archive-inputs` input. Target payload steps seed the+actual PM store's disposable fetch entries with `--target` and `--store`;+Termux also passes `--payload` for runtime libraries. Cache hits do not skip+preservation. Untrusted PR jobs receive no publication credentials.++Installed PM clients, bootstrap installers, and Nix pin consumers use the+primary URL followed by the public mirror if the download is unavailable.+The pinned hash remains binding; no credentials or uploads are needed by+clients. PM keeps per-source resume state and reports attempted URLs.+For Termux files already removed upstream, the CI publisher can recover the+exact bytes from the community Internet Archive after an upstream 404/410.+It never repins to the latest package.++The archive must have no expiration lifecycle rule. Release pruning does+not cover its prefix. This covers PM binary pins and Termux runtime inputs,+not unpinned apt packages, OCI images, language-package registries, or native+Electron/SDK archives independently downloaded by their build tools.+## Verification boundaryTests execute shared snapshot/manifest helpers on real git fixtures, stagediff --git a/nix/npm-pinned.nix b/nix/npm-pinned.nixindex cca054b09db..020cc089ab6 100644--- a/nix/npm-pinned.nix+++ b/nix/npm-pinned.nix@@ -9,6 +9,7 @@ let# url + sha256, so nix consumes it as pure data — no version or url# knowledge lives on the nix side.lock = builtins.fromJSON (builtins.readFile ../pm/lock.json);+ mirror = builtins.fromJSON (builtins.readFile ../pm/artifact-mirror.json);pin = lock.packages.npm;instdenv.mkDerivation {@@ -16,7 +17,7 @@ stdenv.mkDerivation {version = pin.version;src = fetchurl {- url = pin.artifacts.any.url;+ urls = [ pin.artifacts.any.url "${mirror.origin}/${mirror.prefix}${pin.artifacts.any.sha256}" ];sha256 = pin.artifacts.any.sha256;};diff --git a/nix/pm-packages.nix b/nix/pm-packages.nixindex 7bf2abb8a1a..597c5d5706b 100644--- a/nix/pm-packages.nix+++ b/nix/pm-packages.nix@@ -13,6 +13,7 @@# Packages with no artifact for this system are simply absent.letlock = builtins.fromJSON (builtins.readFile ../pm/lock.json);+ mirror = builtins.fromJSON (builtins.readFile ../pm/artifact-mirror.json);target =let@@ -39,7 +40,7 @@ letversion = pin.version;srcs = map (artifact: fetchurl {- url = artifact.url;+ urls = [ artifact.url "${mirror.origin}/${mirror.prefix}${artifact.sha256}" ];sha256 = artifact.sha256;}) artifacts;diff --git a/pm/artifact-mirror.json b/pm/artifact-mirror.jsonnew file mode 100644index 00000000000..d5a2b74ece5--- /dev/null+++ b/pm/artifact-mirror.json@@ -0,0 +1,4 @@+{+ "origin": "https://hermes-assets.nousresearch.com",+ "prefix": "upstream/sha256/"+}diff --git a/pm/artifact_mirror.py b/pm/artifact_mirror.pynew file mode 100644index 00000000000..dda78b6572a--- /dev/null+++ b/pm/artifact_mirror.py@@ -0,0 +1,28 @@+"""Public, content-addressed copies of reviewed binary inputs."""+from __future__ import annotations++import json+from pathlib import Path+import re++from pm.downloader import Source++_LAYOUT = json.loads(Path(__file__).with_name("artifact-mirror.json").read_text(encoding="utf-8"))+KEY_PREFIX = _LAYOUT["prefix"]+PUBLIC_PREFIX = _LAYOUT["origin"] + "/" + KEY_PREFIX+++def object_key(sha256: str) -> str:+ if not isinstance(sha256, str) or not re.fullmatch(r"[a-f0-9]{64}", sha256):+ raise ValueError("A pinned input requires a full lowercase SHA256")+ return KEY_PREFIX + sha256+++def mirror_url(sha256: str) -> str:+ object_key(sha256)+ return PUBLIC_PREFIX + sha256+++def pinned_source(url: str, dest: Path, sha256: str) -> Source:+ archive = mirror_url(sha256)+ return Source(url, dest, sha256, fallbacks=() if url == archive else (archive,))diff --git a/pm/downloader.py b/pm/downloader.pyindex be60862f3ca..880d589c412 100644--- a/pm/downloader.py+++ b/pm/downloader.py@@ -105,11 +105,25 @@ class DownloadPaused(DownloadError):"""pause() was called mid-download; partials were left intact."""+class DownloadTransportError(DownloadError):+ """An exhausted network request, with its original status and URL."""++ def __init__(self, url: str, cause: Exception):+ self.url = url+ self.status = cause.code if isinstance(cause, urllib.error.HTTPError) else None+ self.fallback_allowed = (+ self.status in (401, 403, 404, 410) or is_transient(cause)+ )+ reason = f"{cause}; the host refused access" if self.status in (401, 403) else str(cause)+ super().__init__(f"download failed from {url}: {reason}")++@dataclass(frozen=True)class Source:url: strdest: Pathsha256: str = "" # "" = no integrity check (model catalog policy)+ fallbacks: tuple[str, ...] = ()_Ranges = list[tuple[int, int]]@@ -197,7 +211,7 @@ class Download:partials_dir: Optional[Path] = None,pause_event: Optional[threading.Event] = None,):- self.sources = [Source(s.url, Path(s.dest), s.sha256) for s in sources]+ self.sources = [Source(s.url, Path(s.dest), s.sha256, tuple(s.fallbacks)) for s in sources]self.resume = resumeself.connections = max(1, int(connections))if partials_dir:@@ -220,9 +234,11 @@ class Download:self._check_pause()self.partials_dir.mkdir(parents=True, exist_ok=True)for source in self.sources:- if not (source.url.startswith("https://")- or source.url.startswith(_LOOPBACK)):- raise ValueError(f"refusing non-https url: {source.url}")+ if source.fallbacks and not re.fullmatch(r"[a-f0-9]{64}", source.sha256):+ raise ValueError("mirror fallback requires a full lowercase SHA256")+ for url in (source.url, *source.fallbacks):+ if not (url.startswith("https://") or url.startswith(_LOOPBACK)):+ raise ValueError(f"refusing non-https url: {url}")# Probe the whole plan before reporting a denominator. A missing# Content-Length keeps the bar indeterminate until that file ends.@@ -231,28 +247,36 @@ class Download:totals: dict[str, int] = {}unknown: set[str] = set()coverage: dict[str, _Ranges] = {}+ selected: list[Source] = []+ failures: dict[str, list[DownloadTransportError]] = {}for source in self.sources:self._check_pause()key = str(source.dest)- cached = _existing_dest_ok(source)- if cached:+ failures[key] = []+ if _existing_dest_ok(source):remote = _Remote(source.dest.stat().st_size, False)covered = [(0, remote.total)]else:- remote = self._probe(source.url)+ source, remote = self._try_sources(source, lambda candidate: self._probe(candidate.url), failures[key])covered = []with partial_lock(self.partials_dir, self._key(source.url), wait=False) as acquired:if acquired and remote.ranged:covered = self._partial_ranges(source, remote)if not remote.total:unknown.add(key)+ selected.append(source)totals[key] = remote.totalcoverage[key] = coveredprogress_lock = threading.Lock()- def report(key: str, written: _Ranges) -> None:+ def report(key: str, written: _Ranges, total: int, *, complete: bool = False) -> None:with progress_lock:+ totals[key] = total+ if total or complete:+ unknown.discard(key)+ else:+ unknown.add(key)# The last key identifies the source reporting this tick.coverage.pop(key, None)coverage[key] = list(written)@@ -260,48 +284,67 @@ class Download:done = sum(b - a for rows in coverage.values() for a, b in rows)progress(done, 0 if unknown else sum(totals.values()), dict(coverage))- for source in self.sources:- with partial_lock(self.partials_dir, self._key(source.url), cancelled=self._paused.is_set) as acquired:- if not acquired:- raise DownloadPaused(source.url)- self._check_pause()- key = str(source.dest)- if _existing_dest_ok(source):- size = source.dest.stat().st_size- else:- # Recheck identity after waiting for another process's partial.- remote = self._probe(source.url)- totals[key] = remote.total- if remote.total:- unknown.discard(key)- else:- unknown.add(key)- report(key, self._partial_ranges(source, remote) if remote.ranged else [])-- def tick(written: _Ranges) -> None:- report(key, written)-- def fetch() -> int:- self._check_pause()- if remote.total and remote.ranged and (source.sha256 or remote.etag):- return self._fetch_ranged(source, remote, tick)- return self._fetch_single(source, remote, tick)-- configured_connections = self.connections- try:- size = retry_network(fetch, wait=self._wait_retry)- except http.client.IncompleteRead as exc:- raise DownloadError(f"download incomplete: {exc}") from exc- finally:- self.connections = configured_connections- partial_key = self._key(source.url)- self._finalize(source, self.partials_dir / f"{partial_key}.part",- self.partials_dir / f"{partial_key}.ranges")- totals[key] = size- unknown.discard(key)- report(key, [(0, size)])+ for source in selected:+ key = str(source.dest)++ def tick(written: _Ranges, total: int) -> None:+ report(key, written, total)++ _, size = self._try_sources(source, lambda candidate: self._transfer(candidate, tick), failures[key])+ report(key, [(0, size)], size, complete=True)return [source.dest for source in self.sources]+ def _try_sources(self, source: Source, operation, failures: list[DownloadTransportError]):+ urls = tuple(dict.fromkeys((source.url, *source.fallbacks)))+ for index, url in enumerate(urls):+ self._check_pause()+ candidate = Source(url, source.dest, source.sha256, urls[index + 1:])+ try:+ return candidate, operation(candidate)+ except DownloadTransportError as exc:+ failures.append(exc)+ if not exc.fallback_allowed or index == len(urls) - 1:+ if len(failures) == 1:+ raise+ raise DownloadError("\n".join(str(error) for error in failures)) from exc+ logging.getLogger(__name__).warning("%s; trying pinned mirror %s", exc, urls[index + 1])++ def _transfer(self, source: Source, tick) -> int:+ from pm.download_state import partial_lock++ with partial_lock(self.partials_dir, self._key(source.url), cancelled=self._paused.is_set) as acquired:+ if not acquired:+ raise DownloadPaused(source.url)+ self._check_pause()+ if _existing_dest_ok(source):+ return source.dest.stat().st_size+ # Recheck identity after waiting for another process's partial.+ remote = self._probe(source.url)+ tick(self._partial_ranges(source, remote) if remote.ranged else [], remote.total)++ def report(written: _Ranges) -> None:+ tick(written, remote.total)++ def fetch() -> int:+ self._check_pause()+ if remote.total and remote.ranged and (source.sha256 or remote.etag):+ return self._fetch_ranged(source, remote, report)+ return self._fetch_single(source, remote, report)++ configured_connections = self.connections+ try:+ size = retry_network(fetch, wait=self._wait_retry)+ except (OSError, http.client.HTTPException) as exc:+ if isinstance(exc, urllib.error.URLError) or is_transient(exc):+ raise DownloadTransportError(source.url, exc) from exc+ raise+ finally:+ self.connections = configured_connections+ partial_key = self._key(source.url)+ self._finalize(source, self.partials_dir / f"{partial_key}.part",+ self.partials_dir / f"{partial_key}.ranges")+ return size+# ── internals ─────────────────────────────────────────────def _check_pause(self) -> None:@@ -331,10 +374,8 @@ class Download:return _Remote(int(response.headers.get("Content-Length") or 0), False, etag)try:return retry_network(request, wait=self._wait_retry)- except urllib.error.HTTPError as exc:- if exc.code in (401, 403):- raise DownloadError("the host refused the download; check source access and URL") from exc- raise+ except (OSError, http.client.HTTPException) as exc:+ raise DownloadTransportError(url, exc) from excexcept DownloadError:raiseexcept ValueError:diff --git a/pm/store.py b/pm/store.pyindex 8fd8639097d..402d401f521 100644--- a/pm/store.py+++ b/pm/store.py@@ -284,7 +284,8 @@ class Store:Completed archives enter the cache even if a later source pauses.The downloader owns partial bytes outside this disposable scratch."""- from pm.downloader import Download, DownloadPaused, Source+ from pm.downloader import Download, DownloadPaused+ from pm.artifact_mirror import pinned_sourcesources = []for artifact in artifacts:@@ -300,7 +301,7 @@ class Store:if entry.exists():shutil.rmtree(entry)destination = scratch / entry_name / url.rsplit("/", 1)[-1]- sources.append(Source(url, destination, digest))+ sources.append(pinned_source(url, destination, digest))urls = {str(source.dest): source.url for source in sources}diff --git a/pyproject.toml b/pyproject.tomlindex 9f4b17a7fc3..07d18c95157 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -673,7 +673,7 @@ plugins = ["**/plugin.yaml", "**/plugin.yml"]# pm/lock.json is the runtime pin table (uv/python/tool versions + sha256s).# Without it a sealed wheel installs the pm package but has no pins to# realize — the pm store would be empty.-pm = ["lock.json"]+pm = ["lock.json", "artifact-mirror.json"][tool.pytest.ini_options]testpaths = ["tests"]diff --git a/scripts/ci/archive_inputs.py b/scripts/ci/archive_inputs.pynew file mode 100644index 00000000000..2578f34848b--- /dev/null+++ b/scripts/ci/archive_inputs.py@@ -0,0 +1,201 @@+"""Archive pinned binary inputs in R2 and seed existing CI consumers."""+from __future__ import annotations++import argparse+from dataclasses import dataclass+import json+from pathlib import Path, PurePosixPath+import re+import shutil+import sys+import tempfile+from urllib.parse import quote, urlsplit++# The runner invokes this before setup-pm has installed the checkout.+if __package__ in (None, ""):+ sys.path.insert(0, str(Path(__file__).resolve().parents[2]))++from pm.artifact_mirror import object_key+from pm.downloader import Download, DownloadError, DownloadTransportError, Source+from pm.lock import SCHEMA+from pm.store import ALL_TARGETS, Store+from scripts.releases import r2++TERMUX_TARGET = "linux-arm64-bionic"+++@dataclass(frozen=True)+class InputPin:+ name: str+ url: str+ sha256: str+ kind: str++ def __post_init__(self):+ if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9+_.@-]*", self.name):+ raise ValueError(f"Invalid input name: {self.name!r}")+ object_key(self.sha256)+ parsed = urlsplit(self.url)+ loopback = parsed.scheme == "http" and parsed.hostname in ("127.0.0.1", "localhost", "::1")+ if (parsed.scheme != "https" and not loopback) or not parsed.netloc or parsed.username or parsed.password:+ raise ValueError(f"{self.name}: pinned input needs an HTTPS URL")+ if self.kind not in ("library", "license", "tool"):+ raise ValueError(f"Invalid input kind: {self.kind}")+++def historical_url(url: str) -> str | None:+ parsed = urlsplit(url)+ prefix = "/apt/termux-main/pool/main/"+ if parsed.scheme != "https" or parsed.netloc != "packages.termux.dev" or not parsed.path.startswith(prefix):+ return None+ parts = parsed.path[len(prefix):].split("/")+ if len(parts) != 3 or any(not part or part in (".", "..") for part in parts):+ return None+ group, package, filename = (quote(part, safe="") for part in parts)+ return f"https://archive.org/download/termux_pkgs_archive_{group}/{package}/{filename}"+++def _pin(name: str, row: dict, kind: str) -> InputPin:+ if not isinstance(row, dict) or not isinstance(row.get("url"), str):+ raise ValueError(f"{name}: invalid pinned input row")+ return InputPin(name, row["url"], row.get("sha256"), kind)+++def pinned_inputs(repo: Path, *, target: str | None = None, packages: set[str] | None = None) -> list[InputPin]:+ """All pin references, including shared bytes needed at different paths."""+ if target is not None and target not in ALL_TARGETS:+ raise ValueError(f"Unknown target: {target}")+ lock = json.loads((repo / "pm/lock.json").read_text(encoding="utf-8-sig"))+ if not isinstance(lock, dict) or lock.get("schema") != SCHEMA or not isinstance(lock.get("packages"), dict):+ raise ValueError("Invalid PM lockfile")+ if packages is not None and packages - lock["packages"].keys():+ raise ValueError(f"Unknown pinned packages: {sorted(packages - lock['packages'].keys())}")+ pins = []+ for name, package in lock["packages"].items():+ if packages is not None and name not in packages:+ continue+ artifacts = package["artifacts"]+ if target is not None:+ key = target if target in artifacts else "any"+ artifacts = {key: artifacts[key]} if key in artifacts else {}+ for row_target, rows in artifacts.items():+ for row in rows if isinstance(rows, list) else [rows]:+ label = f"{name}@{row_target}"+ if isinstance(row, dict) and isinstance(row.get("url"), str) and row["url"].startswith("docker://"):+ continue # OCI digests belong to the container registry, not HTTP archives.+ pins.append(_pin(label, row, "tool"))+ if packages is None and target in (None, TERMUX_TARGET):+ table = json.loads((repo / "scripts/termux/runtime_libs.json").read_text(encoding="utf-8"))+ pins.extend(_pin(name, row, "library") for name, row in table["libs"].items())+ if table.get("licenses") is not None:+ pins.append(_pin("termux-licenses", table["licenses"], "license"))+ if not pins:+ raise ValueError("No pinned HTTP inputs selected")+ return pins+++@dataclass(frozen=True)+class Archive:+ creds: dict[str, str]+ base: str+ bucket: str++ def fetch(self, pin: InputPin, destination: Path) -> str:+ """Only R2 404 permits upstream download; every result is read back."""+ key = object_key(pin.sha256)+ url = f"{self.base}/{self.bucket}/{r2.encode_key_path(key)}"+ try:+ head = r2.signed_request("HEAD", url, creds=self.creds, now=r2.amz_timestamp())+ except r2.R2RequestError as exc:+ if exc.status != 404:+ raise+ head = None+ destination.parent.mkdir(parents=True, exist_ok=True)+ with tempfile.TemporaryDirectory(prefix=".input-archive-", dir=destination.parent) as temporary:+ work = Path(temporary)+ local = work / "input"+ origin = "R2"+ if head is None:+ origin = _download_upstream(pin, local)+ size = local.stat().st_size+ r2.put_object(self.creds, self.base, self.bucket, key, str(local), r2.amz_timestamp(),+ "application/octet-stream", conditions={"If-None-Match": "*"})+ else:+ length = head.header("content-length")+ if length is None:+ raise ValueError(f"R2 did not report the input size: {url}")+ size = int(length)+ verified = work / "verified"+ r2.download_object(self.creds, self.base, self.bucket, key, verified, r2.amz_timestamp(),+ expected_size=size, expected_sha256=pin.sha256)+ verified.replace(destination)+ return origin+++def _download_upstream(pin: InputPin, local: Path) -> str:+ try:+ Download([Source(pin.url, local, pin.sha256)], partials_dir=local.parent / "partials").run()+ return "upstream"+ except DownloadTransportError as exc:+ backup = historical_url(pin.url)+ if exc.status not in (404, 410) or backup is None:+ raise+ try:+ Download([Source(backup, local, pin.sha256)], partials_dir=local.parent / "partials").run()+ except DownloadError as failure:+ raise DownloadError(f"{exc}\n{failure}") from failure+ return "historical archive"+++def stage_inputs(pins: list[InputPin], *, archive: Archive, store: Store | None = None, payload: Path | None = None) -> int:+ """Archive each digest once; optionally seed the actual stagers' inputs."""+ from scripts.termux.stage_runtime_libs import download_path++ groups: dict[str, list[InputPin]] = {}+ for pin in pins:+ groups.setdefault(pin.sha256, []).append(pin)+ with tempfile.TemporaryDirectory(prefix="hermes-inputs-") as temporary:+ local = Path(temporary) / "input"+ for digest, references in groups.items():+ origin = archive.fetch(references[0], local)+ for pin in references:+ if pin.kind != "tool" and payload is not None:+ dest = download_path(payload, pin.name)+ dest.parent.mkdir(parents=True, exist_ok=True)+ shutil.copyfile(local, dest)+ if store is not None and any(pin.kind == "tool" for pin in references):+ tool = next(pin for pin in references if pin.kind == "tool")+ filename = PurePosixPath(urlsplit(tool.url).path).name+ if not filename or filename in (".", "..") or "\\" in filename:+ raise ValueError(f"Invalid archive filename: {tool.url}")+ with store.install_lock(), store.scratch() as scratch:+ staged = scratch / "archive"+ staged.mkdir()+ shutil.copyfile(local, staged / filename)+ entry = store.entry(f"fetch-{digest}")+ if entry.exists():+ shutil.rmtree(entry)+ store.publish(staged, entry.name)+ local.unlink()+ print(f" {references[0].name}: {origin} -> {object_key(digest)}", flush=True)+ return len(groups)+++def main(argv=None) -> int:+ from pm import paths++ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--target", choices=ALL_TARGETS)+ parser.add_argument("--payload", type=Path, help="seed Termux runtime-library downloads")+ parser.add_argument("--store", type=Path, help="seed this PM store's disposable input cache")+ args = parser.parse_args(argv)+ pins = pinned_inputs(paths.repo_root(), target=args.target)+ count = stage_inputs(pins, archive=Archive(*r2.credentials()),+ store=Store(args.store.resolve()) if args.store else None,+ payload=args.payload.resolve() if args.payload else None)+ print(f"Verified {count} unique pinned inputs in R2.", flush=True)+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/scripts/ci/setup_toolchain.py b/scripts/ci/setup_toolchain.pyindex bf98fb8652f..34f1b4cd403 100644--- a/scripts/ci/setup_toolchain.py+++ b/scripts/ci/setup_toolchain.py@@ -97,6 +97,16 @@ def python3_alias(python: Path) -> None:shutil.copy2(python, alias)+def archive_inputs(args) -> None:+ from pm.paths import repo_root+ from pm.store import Store+ from scripts.ci.archive_inputs import Archive, pinned_inputs, stage_inputs+ from scripts.releases import r2++ pins = pinned_inputs(repo_root(), target=current_target(), packages=set(packages(args.toolchain)))+ stage_inputs(pins, archive=Archive(*r2.credentials()), store=Store(args.home.resolve() / "tools"))++def install(args) -> None:import subprocess@@ -203,7 +213,7 @@ def dependencies(args) -> None:def main() -> None:parser = argparse.ArgumentParser(description=__doc__)- phases = {"prepare": prepare, "install": install, "dependencies": dependencies}+ phases = {"prepare": prepare, "archive-inputs": archive_inputs, "install": install, "dependencies": dependencies}parser.add_argument("phase", choices=list(phases))parser.add_argument("--toolchain", choices=["python", "node", "all"], default="python")parser.add_argument("--home", type=Path, required=True)diff --git a/scripts/gen-bootstrap-pins.py b/scripts/gen-bootstrap-pins.pyindex ad19eff982b..d7bb931d550 100644--- a/scripts/gen-bootstrap-pins.py+++ b/scripts/gen-bootstrap-pins.py@@ -27,6 +27,10 @@ from pathlib import PathREPO_ROOT = Path(__file__).resolve().parents[1]PINS_PATH = REPO_ROOT / "pm" / "lock.json"+# Standalone installers cannot read the shared mirror layout before checkout.+sys.path.insert(0, str(REPO_ROOT))+from pm.artifact_mirror import mirror_url # noqa: E402+BEGIN_MARK = "# --- BEGIN GENERATED: bootstrap pins (scripts/gen-bootstrap-pins.py) ---"END_MARK = "# --- END GENERATED: bootstrap pins ---"@@ -88,6 +92,7 @@ def _sh_fragment(uv: dict) -> str:lines += [f" {target})",f' UV_PIN_URL="{entry["url"]}"',+ f' UV_PIN_MIRROR="{mirror_url(entry["sha256"])}"',f' UV_PIN_SHA256="{entry["sha256"]}"'," ;;",]@@ -117,6 +122,7 @@ def _ps1_fragment(uv: dict, git: dict) -> str:lines += [f' "{target}" = @{{',f' Url = "{entry["url"]}"',+ f' MirrorUrl = "{mirror_url(entry["sha256"])}"',f' Sha256 = "{entry["sha256"]}"'," }",]@@ -131,6 +137,7 @@ def _ps1_fragment(uv: dict, git: dict) -> str:lines += [f' "{target}" = @{{',f' Url = "{entry["url"]}"',+ f' MirrorUrl = "{mirror_url(entry["sha256"])}"',f' Sha256 = "{entry["sha256"]}"'," }",]diff --git a/scripts/install.ps1 b/scripts/install.ps1index 42fa6de6c4c..82d8ae8dd0d 100644--- a/scripts/install.ps1+++ b/scripts/install.ps1@@ -48,10 +48,12 @@ $script:UvPinVersion = "0.12.3"$script:UvPinFiles = @{"win32-x64" = @{Url = "https://github.com/astral-sh/uv/releases/download/0.12.3/uv-x86_64-pc-windows-msvc.zip"+ MirrorUrl = "https://hermes-assets.nousresearch.com/upstream/sha256/b23350c79e8ad0192b8124af13a0f17e8d4e4549524785e1aef389ae5a06990e"Sha256 = "b23350c79e8ad0192b8124af13a0f17e8d4e4549524785e1aef389ae5a06990e"}"win32-arm64" = @{Url = "https://github.com/astral-sh/uv/releases/download/0.12.3/uv-aarch64-pc-windows-msvc.zip"+ MirrorUrl = "https://hermes-assets.nousresearch.com/upstream/sha256/4343217d668727b8a8eb5cad92389a1d2eeead93c89940d1b955ba1bb15462eb"Sha256 = "4343217d668727b8a8eb5cad92389a1d2eeead93c89940d1b955ba1bb15462eb"}}@@ -60,10 +62,12 @@ $script:GitPinVersion = "2.53.0+3"$script:GitPinFiles = @{"win32-x64" = @{Url = "https://github.com/git-for-windows/git/releases/download/v2.53.0.windows.3/Git-2.53.0.3-64-bit.tar.bz2"+ MirrorUrl = "https://hermes-assets.nousresearch.com/upstream/sha256/1661f02e85a7901ad7920e2a358ee3772ed9066b00d8590bf2d9046ef10aa8b2"Sha256 = "1661f02e85a7901ad7920e2a358ee3772ed9066b00d8590bf2d9046ef10aa8b2"}"win32-arm64" = @{Url = "https://github.com/git-for-windows/git/releases/download/v2.53.0.windows.3/Git-2.53.0.3-arm64.tar.bz2"+ MirrorUrl = "https://hermes-assets.nousresearch.com/upstream/sha256/4015f05a68bd2bcf3cc6c426e8d44b65d670fbb879225bb7b7c347cfc3a2758a"Sha256 = "4015f05a68bd2bcf3cc6c426e8d44b65d670fbb879225bb7b7c347cfc3a2758a"}}@@ -336,6 +340,43 @@ function Get-WindowsArch {return 'x64'}+# Mirror bytes must match the same pin; corruption is never a cache miss.+function Invoke-VerifiedDownload {+ param(+ [Parameter(Mandatory = $true)][string]$Url,+ [Parameter(Mandatory = $true)][string]$Sha256,+ [Parameter(Mandatory = $true)][string]$OutFile,+ [string]$MirrorUrl = ""+ )+ $urls = @($Url)+ if ($MirrorUrl -and $MirrorUrl -ne $Url) { $urls += $MirrorUrl }+ $httpFailure = ""+ foreach ($candidate in $urls) {+ try {+ Invoke-WebRequest -Uri $candidate -OutFile $OutFile -UseBasicParsing+ } catch {+ $errorType = $_.Exception.GetType().FullName+ if ($_.Exception -is [System.Net.WebException]) {+ if ($_.Exception.Status -in @('TrustFailure', 'SecureChannelFailure')) { throw }+ } elseif ($errorType -ne 'Microsoft.PowerShell.Commands.HttpResponseException') {+ throw+ }+ $httpFailure = $_.Exception.Message+ continue+ }+ $digest = (Get-FileHash -Path $OutFile -Algorithm SHA256).Hash.ToLowerInvariant()+ if ($digest -eq $Sha256.ToLowerInvariant()) { return }+ Remove-Item -Path $OutFile -Force -ErrorAction SilentlyContinue+ # Wrong bytes = tampering or a corrupt mirror, not a routing problem.+ Fail "download digest mismatch for $candidate (expected $Sha256, got $digest)"+ }+ $tried = $urls -join " or "+ if ($httpFailure) {+ Fail "failed to download from $tried : $httpFailure"+ }+ Fail "failed to download from $tried"+}+# Provision uv for this host from the pinned pm/lock.json artifact. Stages# the EXACT artifact pm itself uses into the same store slot# (<store>\uv-<version>-<target>\), sha256-verified, so pm adopts the same@@ -356,13 +397,7 @@ function Get-Uv {try {New-Item -ItemType Directory -Force -Path $tmpDir | Out-Null$zipPath = Join-Path $tmpDir "uv.zip"- Invoke-WebRequest -Uri $pin.Url -OutFile $zipPath -UseBasicParsing- # Digest check BEFORE extraction — a mismatched archive is deleted,- # never unpacked.- $digest = (Get-FileHash -Path $zipPath -Algorithm SHA256).Hash.ToLowerInvariant()- if ($digest -ne $pin.Sha256.ToLowerInvariant()) {- Fail "uv digest mismatch (expected $($pin.Sha256), got $digest)"- }+ Invoke-VerifiedDownload -Url $pin.Url -MirrorUrl $pin.MirrorUrl -Sha256 $pin.Sha256 -OutFile $zipPath$extractDir = Join-Path $tmpDir "unpacked"Expand-Archive -Path $zipPath -DestinationPath $extractDir -Force# The zip carries uv.exe (+ uvx.exe) at the root or under one@@ -397,12 +432,7 @@ function Get-PinnedGit {try {New-Item -ItemType Directory -Force -Path $tmpDir | Out-Null$tarPath = Join-Path $tmpDir "git.tar.bz2"- Invoke-WebRequest -Uri $pin.Url -OutFile $tarPath -UseBasicParsing- # Digest check BEFORE extraction — the archive IS code.- $digest = (Get-FileHash -Path $tarPath -Algorithm SHA256).Hash.ToLowerInvariant()- if ($digest -ne $pin.Sha256.ToLowerInvariant()) {- Fail "git digest mismatch (expected $($pin.Sha256), got $digest)"- }+ Invoke-VerifiedDownload -Url $pin.Url -MirrorUrl $pin.MirrorUrl -Sha256 $pin.Sha256 -OutFile $tarPath$extractDir = Join-Path $tmpDir "unpacked"New-Item -ItemType Directory -Force -Path $extractDir | Out-Null# The pinned artifact is a git-for-windows tar.bz2 (the same one pmdiff --git a/scripts/install.sh b/scripts/install.shindex 737c5d9b6f7..bfa88626ade 100755--- a/scripts/install.sh+++ b/scripts/install.sh@@ -63,18 +63,22 @@ uv_bootstrap_pin() {case "$1" inlinux-x64)UV_PIN_URL="https://github.com/astral-sh/uv/releases/download/0.12.3/uv-x86_64-unknown-linux-gnu.tar.gz"+ UV_PIN_MIRROR="https://hermes-assets.nousresearch.com/upstream/sha256/600cf9a742aca00d292673b16b5acffaa7b8c269a364ad0c2e79498dcb1fe101"UV_PIN_SHA256="600cf9a742aca00d292673b16b5acffaa7b8c269a364ad0c2e79498dcb1fe101";;linux-arm64)UV_PIN_URL="https://github.com/astral-sh/uv/releases/download/0.12.3/uv-aarch64-unknown-linux-gnu.tar.gz"+ UV_PIN_MIRROR="https://hermes-assets.nousresearch.com/upstream/sha256/bb66cb52e7b1823aed1183630d8d8e5c958840d584a4c55ec10a4cfc168dcca2"UV_PIN_SHA256="bb66cb52e7b1823aed1183630d8d8e5c958840d584a4c55ec10a4cfc168dcca2";;darwin-x64)UV_PIN_URL="https://github.com/astral-sh/uv/releases/download/0.12.3/uv-x86_64-apple-darwin.tar.gz"+ UV_PIN_MIRROR="https://hermes-assets.nousresearch.com/upstream/sha256/4c9f52262a14da336e4a42ed24992d12d0c956acde87619e4611d321dffa602b"UV_PIN_SHA256="4c9f52262a14da336e4a42ed24992d12d0c956acde87619e4611d321dffa602b";;darwin-arm64)UV_PIN_URL="https://github.com/astral-sh/uv/releases/download/0.12.3/uv-aarch64-apple-darwin.tar.gz"+ UV_PIN_MIRROR="https://hermes-assets.nousresearch.com/upstream/sha256/546f7f8a6c70ff13a3a9d2bc958db3427298cebf3e0cb756f9177133b7068843"UV_PIN_SHA256="546f7f8a6c70ff13a3a9d2bc958db3427298cebf3e0cb756f9177133b7068843";;*)@@ -129,9 +133,22 @@ ensure_uv() {local _tmp_tmp="$(mktemp -d 2>/dev/null || echo "/tmp/hermes-uv-bootstrap.$$")"mkdir -p "$_tmp"- if ! curl -LsSf "$UV_PIN_URL" -o "$_tmp/uv.tar.gz"; then- rm -rf "$_tmp"- fail "failed to download pinned uv from $UV_PIN_URL"+ local _fetched_from="$UV_PIN_URL"+ # Only network availability failures permit trying identical mirrored bytes.+ if curl -LsSf "$UV_PIN_URL" -o "$_tmp/uv.tar.gz"; then+ :+ else+ local _curl_status=$?+ case "$_curl_status" in+ 5|6|7|18|22|28|52|55|56) ;;+ *) rm -rf "$_tmp"; fail "failed to download pinned uv from $UV_PIN_URL (curl $_curl_status)" ;;+ esac+ if [ -n "${UV_PIN_MIRROR:-}" ] && curl -LsSf "$UV_PIN_MIRROR" -o "$_tmp/uv.tar.gz"; then+ _fetched_from="$UV_PIN_MIRROR"+ else+ rm -rf "$_tmp"+ fail "failed to download pinned uv from $UV_PIN_URL or ${UV_PIN_MIRROR:-no mirror}"+ fifilocal _digestif command -v sha256sum >/dev/null 2>&1; then@@ -141,7 +158,7 @@ ensure_uv() {fiif [ "$_digest" != "$UV_PIN_SHA256" ]; thenrm -rf "$_tmp"- fail "uv download digest mismatch (expected $UV_PIN_SHA256, got $_digest)"+ fail "uv download digest mismatch from $_fetched_from (expected $UV_PIN_SHA256, got $_digest)"fiif ! tar -xzf "$_tmp/uv.tar.gz" -C "$_tmp"; thenrm -rf "$_tmp"diff --git a/scripts/termux/stage_runtime_libs.py b/scripts/termux/stage_runtime_libs.pyindex 37952a6a24a..542bc94aa1a 100644--- a/scripts/termux/stage_runtime_libs.py+++ b/scripts/termux/stage_runtime_libs.py@@ -38,7 +38,8 @@ HERE = Path(__file__).resolve().parentREPO_ROOT = HERE.parent.parentsys.path.insert(0, str(REPO_ROOT))-from pm.downloader import Download, Source # noqa: E402+from pm.downloader import Download # noqa: E402+from pm.artifact_mirror import pinned_source # noqa: E402from pm.package import DebPackage # noqa: E402PREFIX_REL = DebPackage.prefix_rel@@ -104,12 +105,22 @@ def _cache_valid(out: Path, manifest_path: Path, table: dict) -> bool:return True-def _ensure_extracted(work: Path, name: str, row: dict) -> Path:+def _work_dir(payload: Path) -> Path:+ return payload / ".work" / "runtime-libs"+++def download_path(payload: Path, name: str) -> Path:+ """The verified input consumed by this stager and the CI archive preflight."""+ return _work_dir(payload) / "dl" / f"{name}.deb"+++def _ensure_extracted(payload: Path, name: str, row: dict) -> Path:"""Extract fresh bytes from a digest-verified archive on every cache miss."""+ work = _work_dir(payload)extract = work / "extract" / name- scratch = work / "dl"+ archive = download_path(payload, name)+ scratch = archive.parentscratch.mkdir(parents=True, exist_ok=True)- archive = scratch / f"{name}.deb"archive_ok = Falseif archive.exists():try:@@ -118,7 +129,7 @@ def _ensure_extracted(work: Path, name: str, row: dict) -> Path:archive_ok = Falseif not archive_ok:try:- Download([Source(row["url"], archive, row["sha256"])],+ Download([pinned_source(row["url"], archive, row["sha256"])],partials_dir=scratch).run()except Exception as exc:raise StageError(f"{name} {row['version']}: download failed from {row['url']}: {exc}") from exc@@ -138,7 +149,6 @@ def stage(payload: Path, table: dict, licenses: dict | None = None) -> Path:payload = Path(payload).resolve()payload.mkdir(parents=True, exist_ok=True)out = payload / "runtime-libs" / "lib"- work = payload / ".work" / "runtime-libs"manifest_path = payload / "runtime-libs" / MANIFEST_NAMEidentity = {"libs": table, "licenses": licenses}@@ -154,7 +164,7 @@ def stage(payload: Path, table: dict, licenses: dict | None = None) -> Path:merged = 0for name, row in table.items():- extract = _ensure_extracted(work, name, row)+ extract = _ensure_extracted(payload, name, row)lib_dir = extract / PREFIX_REL / "lib"sos = sorted(lib_dir.glob("*.so*"))if not sos:@@ -185,7 +195,7 @@ def stage(payload: Path, table: dict, licenses: dict | None = None) -> Path:raise StageError("no shared objects staged")if licenses:- extract = _ensure_extracted(work, "termux-licenses", licenses)+ extract = _ensure_extracted(payload, "termux-licenses", licenses)shutil.copytree(extract / PREFIX_REL / "share/LICENSES", payload / "runtime-libs/share/LICENSES",dirs_exist_ok=True, symlinks=True,diff --git a/setup-hermes.sh b/setup-hermes.shindex 49afcc82aa6..135584d4852 100755--- a/setup-hermes.sh+++ b/setup-hermes.sh@@ -43,6 +43,14 @@ echo -e "${CYAN}→${NC} Checking for uv..."lock="$SCRIPT_DIR/pm/lock.json"[ -f "$lock" ] || { echo -e "${RED}✗${NC} pm/lock.json not found" >&2; exit 1; }+# Read the shared mirror location before Python is available.+mirror_origin="$(awk -F '"' '/^ "origin"/ { print $4; exit }' "$SCRIPT_DIR/pm/artifact-mirror.json")"+mirror_prefix="$(awk -F '"' '/^ "prefix"/ { print $4; exit }' "$SCRIPT_DIR/pm/artifact-mirror.json")"+mirror_url_for() { # $1 = lowercase sha256+ [ -n "$mirror_origin" ] && [ -n "$mirror_prefix" ] || return 1+ printf '%s/%s%s' "$mirror_origin" "$mirror_prefix" "$1"+}+case "$(uname -s)" inLinux) os=linux ;;Darwin) os=darwin ;;@@ -99,7 +107,18 @@ elsemkdir -p "$store"tmp="$(mktemp -d "$store/.bootstrap-XXXXXX")"; trap 'rm -rf "$tmp"' EXITarchive="$tmp/${url##*/}"- curl -fsSL -o "$archive" "$url"+ fetch_pinned() {+ if curl -fsSL -o "$2" "$1"; then return 0; else _curl_status=$?; fi+ case "$_curl_status" in 5|6|7|18|22|28|52|55|56) ;; *) return "$_curl_status" ;; esac+ local mirror; mirror="$(mirror_url_for "$sha")" || return 1+ curl -fsSL -o "$2" "$mirror" || return 1+ }+ if ! fetch_pinned "$url" "$archive"; then+ _tried="$url"+ if _m="$(mirror_url_for "$sha")"; then _tried="$_tried or $_m"; fi+ echo -e "${RED}✗${NC} failed to download pinned uv from $_tried" >&2+ exit 1+ figot="$( (sha256sum "$archive" 2>/dev/null || shasum -a 256 "$archive") | cut -d' ' -f1 | tr -d '\\')"[ "$got" = "$sha" ] || { echo -e "${RED}✗${NC} sha256 mismatch for uv (got $got, pinned $sha)" >&2; exit 1; }mkdir -p "$tmp/tree"diff --git a/tests/ci/test_termux_input_archive.py b/tests/ci/test_termux_input_archive.pynew file mode 100644index 00000000000..e9be5d6019a--- /dev/null+++ b/tests/ci/test_termux_input_archive.py@@ -0,0 +1,62 @@+"""CI runs archival before the exact tool and payload consumers."""+from pathlib import Path+import shlex++import yaml++ROOT = Path(__file__).resolve().parents[2]+R2_ENV = {"CLOUDFLARE_R2_ACCOUNT_ID", "CLOUDFLARE_R2_ACCESS_KEY_ID", "CLOUDFLARE_R2_SECRET_ACCESS_KEY", "CLOUDFLARE_R2_BUCKET"}+++def load(name):+ return yaml.load((ROOT / ".github/workflows" / name).read_text(encoding="utf-8"), Loader=yaml.BaseLoader)+++def test_termux_and_desktop_stagers_consume_archive_seeds():+ release = load("desktop-bundled-release.yml")+ for file, job_name in (("desktop-bundled-release.yml", "termux-deb"), ("termux-verify.yml", "native-runtime")):+ job = load(file)["jobs"][job_name]+ steps = job["steps"]+ index, step = next((i, s) for i, s in enumerate(steps) if "scripts.ci.archive_inputs" in s.get("run", ""))+ args = shlex.split(step["run"])+ assert args[args.index("--target") + 1] == "linux-arm64-bionic"+ assert args[args.index("--store") + 1] == "$HERMES_RUNTIME_DIR"+ assert args[args.index("--payload") + 1] == "termux-build/payload"+ assert "if" not in step and "continue-on-error" not in step+ assert R2_ENV <= (job.get("env", {}).keys() | step.get("env", {}).keys())+ first_stage = next(i for i, s in enumerate(steps) if "scripts/termux/build_cpython.sh" in s.get("run", ""))+ assert index < first_stage+ for name in ("build-win32", "build-darwin"):+ steps = release["jobs"][name]["steps"]+ index, step = next((i, s) for i, s in enumerate(steps) if "scripts.ci.archive_inputs" in s.get("run", ""))+ assert "--target '${{ matrix.target.label }}'" in step["run"]+ assert "--store apps/desktop/build/agent-payload/tools" in step["run"]+ assert index < next(i for i, s in enumerate(steps) if "scripts/bundles/desktop.py" in s.get("run", ""))+ setup = next(s for s in steps if s.get("uses") == "./.github/actions/setup-pm")+ assert setup["with"]["archive-inputs"] == "true"+++def test_archive_gate_uses_bootstrap_python_and_trusted_exact_revision():+ workflow = load("archive-inputs.yml")+ assert not {"pull_request", "pull_request_target"} & workflow["on"].keys()+ assert "workflow_dispatch" in workflow["on"] and "push" in workflow["on"]+ job = workflow["jobs"]["archive-inputs"]+ assert job["environment"] == "release-signing"+ assert R2_ENV <= job["env"].keys()+ assert not any(s.get("uses") == "./.github/actions/setup-pm" for s in job["steps"])+ assert job["steps"][-1]["run"] == "python3 -m scripts.ci.archive_inputs"+ checkout = job["steps"][0]+ assert checkout["with"]["ref"] == "${{ inputs.sha || github.sha }}"+ release = load("desktop-bundled-release.yml")["jobs"]+ caller = release["archive-inputs"]+ assert caller["needs"] == ["validate"]+ assert caller["with"]["sha"] == "${{ needs.validate.outputs.sha }}"+ for name in ("build-win32", "build-darwin", "termux-deb"):+ assert "archive-inputs" in release[name]["needs"]++ action = yaml.load((ROOT / ".github/actions/setup-pm/action.yml").read_text(encoding="utf-8"), Loader=yaml.BaseLoader)+ assert action["inputs"]["archive-inputs"]["default"] == "false"+ steps = action["runs"]["steps"]+ archive_index, archive = next((i, s) for i, s in enumerate(steps) if "setup_toolchain.py\" archive-inputs" in s.get("run", ""))+ assert archive["if"] == "inputs.archive-inputs == 'true'"+ assert archive_index < next(i for i, s in enumerate(steps) if s.get("id") == "install")diff --git a/tests/pm/test_artifact_mirror.py b/tests/pm/test_artifact_mirror.pynew file mode 100644index 00000000000..7984ed4bcb7--- /dev/null+++ b/tests/pm/test_artifact_mirror.py@@ -0,0 +1,55 @@+"""PM installation and cross-target staging consume the public pinned mirror."""+import hashlib+import importlib+import io+import zipfile++import pytest++from pm import paths+from pm.lock import Facts, Lockfile+from pm.package import Package+from pm.store import Store, current_target+from tests.pm._range_server import RangeHandler, dl_server, url # noqa: F401++[email protected]("mode", ["install", "stage", "library"])+def test_cold_consumers_recover_after_upstream_removal(tmp_path, dl_server, monkeypatch, mode):+ from pm import artifact_mirror++ engine = importlib.import_module("pm.ensure")+ data = io.BytesIO()+ with zipfile.ZipFile(data, "w") as archive:+ archive.writestr("tool.txt", b"pinned and preserved")+ body = data.getvalue()+ if mode == "library":+ from tests.test_termux_runtime_libs import _build_deb+ deb = tmp_path / "test.deb"+ _build_deb(deb, "libmirror.so", b"pinned and preserved")+ body = deb.read_bytes()+ digest = hashlib.sha256(body).hexdigest()+ monkeypatch.setattr(artifact_mirror, "PUBLIC_PREFIX", url(dl_server, "/archive/"))+ RangeHandler.payloads["/archive/" + digest] = body+ row = {"url": url(dl_server, "/removed.zip"), "sha256": digest}+ monkeypatch.setattr(paths, "partials_root", lambda: tmp_path / "partials")+ if mode == "library":+ from scripts.termux.stage_runtime_libs import stage+ result = stage(tmp_path / "payload", {"libmirror": {**row, "version": "1.0"}})+ assert (result / "libmirror.so").read_bytes().endswith(b"pinned and preserved")+ else:+ package = Package()+ package.name = "mirror-tool"+ store = Store(tmp_path / "store")+ facts = Facts(store.root / "facts.json")+ lock = Lockfile(tmp_path / "lock.json")+ lock.set_pin(package.name, "1.0", {"any": row})+ if mode == "install":+ engine._install(package, lock, facts, store, current_target())+ result = store.entry(facts.get(package.name)["entry"])+ else:+ monkeypatch.setattr(engine, "_lockfile", lambda: lock)+ monkeypatch.setattr(engine, "_store", lambda: store)+ monkeypatch.setattr(engine, "get_package", lambda _: package)+ result = engine.stage_only(package.name, "linux-arm64-bionic")+ assert (result / "tool.txt").read_bytes() == b"pinned and preserved"+ assert any(path == "/archive/" + digest for path, *_ in RangeHandler.ranges_seen)diff --git a/tests/pm/test_download_mirrors.py b/tests/pm/test_download_mirrors.pynew file mode 100644index 00000000000..107ba4f43bf--- /dev/null+++ b/tests/pm/test_download_mirrors.py@@ -0,0 +1,113 @@+"""Pinned downloads keep their identity when the upstream disappears."""+import hashlib++import pytest++from pm.downloader import Download, DownloadError, HashError, Source+from tests.pm._range_server import RangeHandler, dl_server, url # noqa: F401++[email protected]("phase", ["probe", "body"])+def test_fallback_retains_hash_destination_and_progress(tmp_path, dl_server, monkeypatch, phase):+ payload = b"the same pinned bytes" * 100+ RangeHandler.payloads = {"/primary": payload, "/mirror": payload, "/other": b"other"}+ requests = []+ original = RangeHandler.do_GET++ def respond(handler):+ requests.append(handler.path)+ if handler.path == "/primary" and (phase == "probe" or handler.headers.get("Range") != "bytes=0-0"):+ handler.send_error(404)+ else:+ original(handler)++ monkeypatch.setattr(RangeHandler, "do_GET", respond)+ digest = hashlib.sha256(payload).hexdigest()+ destination = tmp_path / "original-name.zip"+ sources = [Source(url(dl_server, "/primary"), destination, digest,+ fallbacks=(url(dl_server, "/mirror"),)),+ Source(url(dl_server, "/other"), tmp_path / "other")]+ ticks = []+ result = Download(sources, partials_dir=tmp_path / "partials", connections=1).run(+ progress=lambda done, total, ranges: ticks.append((done, total, ranges)))+ assert result == [source.dest for source in sources]+ assert destination.read_bytes() == payload+ expected = len(payload) + len(b"other")+ assert ticks[-1][:2] == (expected, expected)+ assert set(ticks[-1][2]) == {str(source.dest) for source in sources}+ assert requests.index("/primary") < requests.index("/mirror")+++def test_bad_hash_is_not_a_mirror_miss(tmp_path, dl_server):+ RangeHandler.payloads = {"/primary": b"changed upstream", "/mirror": b"pinned"}+ destination = tmp_path / "keep.zip"+ destination.write_bytes(b"previous destination")+ source = Source(url(dl_server, "/primary"), destination, hashlib.sha256(b"pinned").hexdigest(),+ fallbacks=(url(dl_server, "/mirror"),))+ with pytest.raises(HashError):+ Download([source], partials_dir=tmp_path / "partials").run()+ assert destination.read_bytes() == b"previous destination"+ assert all(path != "/mirror" for path, *_ in RangeHandler.ranges_seen)++[email protected]("mirror_status", [401, 403, 404])+def test_exhausted_mirrors_name_each_attempted_url(tmp_path, dl_server, monkeypatch, mirror_status):+ original = RangeHandler.do_GET++ def respond(handler):+ if handler.path == "/also-missing":+ handler.send_error(mirror_status)+ else:+ original(handler)++ monkeypatch.setattr(RangeHandler, "do_GET", respond)+ primary, mirror = (url(dl_server, path) for path in ("/missing", "/also-missing"))+ with pytest.raises(DownloadError) as failure:+ Download([Source(primary, tmp_path / "absent", "0" * 64, fallbacks=(mirror,))],+ partials_dir=tmp_path / "partials").run()+ assert primary in str(failure.value) and mirror in str(failure.value)+ assert "404" in str(failure.value) and str(mirror_status) in str(failure.value)+ assert not (tmp_path / "absent").exists()++[email protected]("failure", ["503", "tls", "disk", "pause"])+def test_only_availability_failures_can_use_a_mirror(tmp_path, dl_server, monkeypatch, failure):+ import ssl+ from pm import downloader, network++ payload = b"still pinned"+ RangeHandler.payloads = {"/primary": payload, "/mirror": payload}+ original = downloader._OPENER.open+ requests = []+ waits = []+ dl = Download([Source(url(dl_server, "/primary"), tmp_path / "tool",+ hashlib.sha256(payload).hexdigest(), fallbacks=(url(dl_server, "/mirror"),))],+ partials_dir=tmp_path / "partials")+ monkeypatch.setattr(dl, "_wait_retry", waits.append)++ def open_request(request, **kwargs):+ requests.append(request.full_url)+ if request.full_url.endswith("/primary"):+ if failure == "tls":+ raise ssl.SSLCertVerificationError("untrusted certificate")+ if failure == "disk":+ raise PermissionError("local path denied")+ if failure == "pause":+ dl.pause()+ if failure == "503":+ import urllib.error+ raise urllib.error.HTTPError(request.full_url, 503, "Unavailable", {}, None)+ return original(request, **kwargs)++ monkeypatch.setattr(downloader._OPENER, "open", open_request)+ if failure == "503":+ dl.run()+ assert (tmp_path / "tool").read_bytes() == payload+ assert requests.count(url(dl_server, "/primary")) == network._ATTEMPTS+ assert len(waits) == network._ATTEMPTS - 1+ else:+ with pytest.raises(downloader.DownloadError):+ dl.run()+ assert not (tmp_path / "tool").exists()+ assert not waits+ assert url(dl_server, "/mirror") not in requestsdiff --git a/tests/pm/test_download_retry_limits.py b/tests/pm/test_download_retry_limits.pyindex 009344e68dc..b7a39d3bf40 100644--- a/tests/pm/test_download_retry_limits.py+++ b/tests/pm/test_download_retry_limits.py@@ -2,13 +2,12 @@import hashlibimport threading-import urllib.errorfrom concurrent.futures import ThreadPoolExecutorimport pytestfrom pm import network-from pm.downloader import Download, DownloadError, DownloadPaused, HashError, Source+from pm.downloader import Download, DownloadPaused, DownloadTransportError, HashError, Sourcefrom tests.pm._range_server import RangeHandler, dl_server, url # noqa: F401@@ -40,12 +39,13 @@ def test_download_failure_never_publishes_partial_bytes(tmp_path, dl_server, monif failure == "disk":dest.mkdir()(dest / "occupied").write_bytes(b"keep")- expected_error = {"hash": HashError, "disk": OSError}.get(failure)- if expected_error is None:- expected_error = DownloadError if failure == "403" and phase == "probe" else urllib.error.HTTPError+ expected_error = {"hash": HashError, "disk": OSError}.get(failure, DownloadTransportError)- with pytest.raises(expected_error):+ with pytest.raises(expected_error) as error:dl.run()+ if failure.isdigit():+ assert error.value.status == int(failure)+ assert url(dl_server, "/tool") in str(error.value)if failure == "disk":assert (dest / "occupied").read_bytes() == b"keep"assert not requests and not waitsdiff --git a/tests/scripts/test_archive_inputs.py b/tests/scripts/test_archive_inputs.pynew file mode 100644index 00000000000..4ff73eb6360--- /dev/null+++ b/tests/scripts/test_archive_inputs.py@@ -0,0 +1,203 @@+"""CI archives exact pinned inputs and supplies the real staging consumers."""+import hashlib+import importlib+import json+from pathlib import Path+import threading+from concurrent.futures import ThreadPoolExecutor++import pytest++from pm.artifact_mirror import object_key+from pm.downloader import HashError+from scripts.ci import archive_inputs as inputs+from scripts.releases import r2+from tests.scripts.test_release_r2 import r2_server # noqa: F401+from tests.test_termux_runtime_libs import _Server, _build_deb+++def write_pins(repo, packages, libs=None):+ (repo / "pm").mkdir(parents=True, exist_ok=True)+ (repo / "pm/lock.json").write_text(json.dumps({"schema": 1, "packages": packages}), encoding="utf-8")+ (repo / "scripts/termux").mkdir(parents=True, exist_ok=True)+ (repo / "scripts/termux/runtime_libs.json").write_text(json.dumps(libs or {"libs": {}}), encoding="utf-8")+++def upstream(tmp_path):+ root = tmp_path / "upstream"+ root.mkdir()+ _build_deb(root / "lib.deb", "libarchive-proof.so", b"pinned library")+ server = _Server(root)+ try:+ yield server, root+ finally:+ server.stop()+++def test_target_selection_preserves_multi_archive_and_any_fallback(tmp_path):+ def row(name):+ return {"url": f"https://upstream.test/{name}.zip", "sha256": hashlib.sha256(name.encode()).hexdigest()}+ packages = {+ "engine": {"version": "1", "artifacts": {+ "win32-x64": [row("engine"), row("cudart")], "linux-x64": row("linux"),+ }},+ "portable": {"version": "1", "artifacts": {"any": row("portable")}},+ "container": {"version": "1", "artifacts": {"linux-arm64-bionic": {+ "url": "docker://termux/termux-docker@sha256:" + "a" * 64,+ }}},+ }+ lib = row("lib")+ write_pins(tmp_path, packages, {"libs": {"lib": lib}, "licenses": row("license")})+ win = inputs.pinned_inputs(tmp_path, target="win32-x64")+ assert {p.sha256 for p in win} == {row(n)["sha256"] for n in ("engine", "cudart", "portable")}+ bionic = inputs.pinned_inputs(tmp_path, target="linux-arm64-bionic")+ assert {p.sha256 for p in bionic} == {row(n)["sha256"] for n in ("portable", "lib", "license")}+ all_pins = inputs.pinned_inputs(tmp_path)+ assert {p.sha256 for p in all_pins} == {row(n)["sha256"] for n in ("engine", "cudart", "portable", "linux", "lib", "license")}++[email protected]("bad", [{}, {"url": "https://u/file.zip"}, {"url": "http://u/file.zip", "sha256": "a" * 64}, {"url": "https://u/file.zip", "sha256": " A "}])+def test_invalid_pins_fail_without_rewriting_authority(tmp_path, bad):+ write_pins(tmp_path, {"bad": {"version": "1", "artifacts": {"any": bad}}})+ before = (tmp_path / "pm/lock.json").read_bytes()+ with pytest.raises(ValueError):+ inputs.pinned_inputs(tmp_path)+ assert (tmp_path / "pm/lock.json").read_bytes() == before+++def test_real_cli_miss_hit_and_staging_use_the_same_archived_bytes(tmp_path, upstream, r2_server, monkeypatch):+ from pm import paths+ from pm.store import Store+ from scripts.termux.stage_runtime_libs import stage+ from tests.pm.test_stage_only import _FakePackage++ server, root = upstream+ body = (root / "lib.deb").read_bytes()+ digest = hashlib.sha256(body).hexdigest()+ row = {"url": server.url + "/lib.deb", "sha256": digest, "version": "1"}+ repo = tmp_path / "repo"+ write_pins(repo, {"stage-test": {"version": "1", "artifacts": {"linux-arm64-bionic": row}}}, {"libs": {"lib": row}})+ monkeypatch.setattr(paths, "repo_root", lambda: repo)+ monkeypatch.setattr(paths, "lockfile_path", lambda: repo / "pm/lock.json")+ assert inputs.main([]) == 0+ assert r2_server.store[object_key(digest)][0] == body+ puts = [r for r in r2_server.requests if r[0] == "PUT"]+ assert len(puts) == 1 and puts[0][2]["If-None-Match"] == "*"+ assert r2_server.requests[-1][0] == "GET"+ assert not (repo / ".archive-inputs").exists()+ (root / "lib.deb").unlink()+ r2_server.requests.clear()+ store = Store(tmp_path / "tools")+ payload = tmp_path / "payload"+ assert inputs.main(["--target", "linux-arm64-bionic", "--store", str(store.root), "--payload", str(payload)]) == 0+ assert not any(r[0] == "PUT" for r in r2_server.requests)+ assert (stage(payload, {"lib": row}) / "libarchive-proof.so").read_bytes().endswith(b"pinned library")+ engine = importlib.import_module("pm.ensure")+ monkeypatch.setattr(engine, "_store", lambda: store)+ monkeypatch.setattr(engine, "get_package", lambda _: _FakePackage())+ entry = engine.stage_only("stage-test", "linux-arm64-bionic")+ assert (entry / "bin/tool").read_bytes() == body+ assert not store.entry(f"fetch-{digest}").exists()+ assert r2.canary_doomed_keys([object_key(digest)], "99999999") == []++[email protected]("failure", ["upstream-hash", "r2-hash", "r2-permission", "readback"])+def test_corrupt_or_denied_archive_never_publishes_a_destination(tmp_path, upstream, r2_server, monkeypatch, failure):+ server, root = upstream+ body = (root / "lib.deb").read_bytes()+ digest = hashlib.sha256(body).hexdigest()+ pin = inputs.InputPin("lib", server.url + "/lib.deb", digest, "library")+ key = object_key(digest)+ if failure == "upstream-hash":+ (root / "lib.deb").write_bytes(b"corrupt")+ elif failure == "r2-hash":+ r2_server.store[key] = (b"corrupt", '"etag"')+ elif failure == "readback":+ original = r2.put_object+ def corrupt(*args, **kwargs):+ original(*args, **kwargs)+ r2_server.store[key] = (b"x" * len(body), '"etag"')+ monkeypatch.setattr(r2, "put_object", corrupt)+ else:+ original = r2.signed_request+ def deny(method, url, **kwargs):+ if method == "HEAD":+ raise r2.R2RequestError(method, url, 403)+ return original(method, url, **kwargs)+ monkeypatch.setattr(r2, "signed_request", deny)+ dest = tmp_path / "preserved"+ dest.write_bytes(b"old")+ with pytest.raises((HashError, ValueError, r2.R2RequestError)):+ inputs.Archive(*r2.credentials()).fetch(pin, dest)+ assert dest.read_bytes() == b"old"+ assert any(r[0] == "PUT" for r in r2_server.requests) == (failure == "readback")+++def test_racing_misses_verify_the_immutable_winner(tmp_path, upstream, r2_server, monkeypatch):+ server, root = upstream+ body = (root / "lib.deb").read_bytes()+ pin = inputs.InputPin("lib", server.url + "/lib.deb", hashlib.sha256(body).hexdigest(), "library")+ barrier = threading.Barrier(2)+ original = r2.signed_request+ def race(method, url, **kwargs):+ try:+ return original(method, url, **kwargs)+ except r2.R2RequestError as exc:+ if method == "HEAD" and exc.status == 404:+ barrier.wait(timeout=10)+ raise+ monkeypatch.setattr(r2, "signed_request", race)+ archive = inputs.Archive(*r2.credentials())+ paths = [tmp_path / f"race-{i}" for i in range(2)]+ with ThreadPoolExecutor(max_workers=2) as pool:+ assert list(pool.map(lambda p: archive.fetch(pin, p), paths)) == ["upstream", "upstream"]+ assert all(p.read_bytes() == body for p in paths)+++def test_historical_recovery_keeps_the_original_digest(tmp_path, upstream, r2_server, monkeypatch):+ server, root = upstream+ body = (root / "lib.deb").read_bytes()+ pin = inputs.InputPin("lib", server.url + "/gone.deb", hashlib.sha256(body).hexdigest(), "library")+ monkeypatch.setattr(inputs, "historical_url", lambda _: server.url + "/lib.deb")+ dest = tmp_path / "recovered"+ assert inputs.Archive(*r2.credentials()).fetch(pin, dest) == "historical archive"+ assert dest.read_bytes() == body+++def test_committed_inventory_matches_every_http_pin():+ repo = Path(__file__).resolve().parents[2]+ lock = json.loads((repo / "pm/lock.json").read_text(encoding="utf-8"))+ expected = set()+ for package in lock["packages"].values():+ for artifact in package.get("artifacts", {}).values():+ for row in artifact if isinstance(artifact, list) else [artifact]:+ if row["url"].startswith("https://"):+ expected.add(row["sha256"])+ table = json.loads((repo / "scripts/termux/runtime_libs.json").read_text(encoding="utf-8"))+ expected.update(row["sha256"] for row in table["libs"].values())+ expected.add(table["licenses"]["sha256"])+ assert {p.sha256 for p in inputs.pinned_inputs(repo)} == expected+++def test_ci_toolchain_seed_runs_before_the_tool_installer(tmp_path, upstream, r2_server, monkeypatch):+ from types import SimpleNamespace+ from scripts.ci import setup_toolchain+ from pm import paths+ from pm.store import Store, current_target++ server, root = upstream+ body = (root / "lib.deb").read_bytes()+ digest = hashlib.sha256(body).hexdigest()+ target = current_target()+ row = {"url": server.url + "/lib.deb", "sha256": digest}+ packages = {name: {"version": "1", "artifacts": {target: row}} for name in ("python", "uv")}+ repo = tmp_path / "repo"+ write_pins(repo, packages)+ monkeypatch.setattr(paths, "repo_root", lambda: repo)+ home = tmp_path / "ci-home"+ setup_toolchain.archive_inputs(SimpleNamespace(home=home, toolchain="python"))+ (root / "lib.deb").unlink()+ store = Store(home / "tools")+ with store.scratch() as scratch:+ assert store.fetch(row["url"], digest, scratch).read_bytes() == bodydiff --git a/tests/test_bootstrap_mirror.py b/tests/test_bootstrap_mirror.pynew file mode 100644index 00000000000..ca05616eb52--- /dev/null+++ b/tests/test_bootstrap_mirror.py@@ -0,0 +1,171 @@+"""Real bootstrap downloads preserve the pin across an upstream outage."""+import hashlib+import io+import json+import os+from pathlib import Path+import shutil+import subprocess+import tarfile+import threading+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer++import pytest++ROOT = Path(__file__).resolve().parents[1]+++def server():+ class Handler(BaseHTTPRequestHandler):+ def do_GET(self):+ self.server.requests.append(self.path)+ body = self.server.files.get(self.path)+ self.send_response(200 if body is not None else 404)+ self.send_header("Content-Length", str(len(body or b"")))+ self.end_headers()+ self.wfile.write(body or b"")++ def log_message(self, *_args):+ pass++ http = ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ http.files, http.requests = {}, []+ thread = threading.Thread(target=http.serve_forever, daemon=True)+ thread.start()+ try:+ yield http, f"http://127.0.0.1:{http.server_port}"+ finally:+ http.shutdown()+ http.server_close()+ thread.join(timeout=5)+++def fixture_bytes(server, mode, body):+ http, base = server+ if mode != "missing":+ http.files["/primary"] = b"bad bytes" if mode == "corrupt" else body+ http.files["/mirror"] = body+ return base + "/primary", base + "/mirror", hashlib.sha256(body).hexdigest()++[email protected]("windows")[email protected]("mode", ["primary", "missing", "corrupt", "both-missing"])+def test_windows_download_uses_only_verified_candidates(tmp_path, server, mode):+ body = b"exact archive bytes"+ primary, mirror, digest = fixture_bytes(server, mode, body)+ if mode == "both-missing":+ server[0].files.clear()+ destination = tmp_path / "out.zip"+ script = tmp_path / "driver.ps1"+ script.write_text(+ f". '{ROOT / 'scripts/install.ps1'}' -HermesHome '{tmp_path / 'home'}' -InstallDir '{tmp_path / 'repo'}'\n"+ f"Invoke-VerifiedDownload -Url '{primary}' -MirrorUrl '{mirror}' -Sha256 '{digest}' -OutFile '{destination}'\n",+ encoding="utf-8",+ )+ result = subprocess.run(["powershell", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", str(script)],+ capture_output=True, text=True, timeout=60)+ if mode in ("primary", "missing"):+ assert result.returncode == 0, result.stdout + result.stderr+ assert destination.read_bytes() == body+ else:+ assert result.returncode != 0+ assert primary in result.stdout + result.stderr+ if mode == "both-missing":+ assert mirror in result.stdout + result.stderr+ assert server[0].requests == (["/primary", "/mirror"] if mode in ("missing", "both-missing") else ["/primary"])++[email protected]("windows")[email protected]("name", ["uv", "git"])+def test_windows_bootstrap_rejects_corrupt_bytes_before_extract(tmp_path, server, name):+ primary, mirror, digest = fixture_bytes(server, "corrupt", b"expected archive")+ script = tmp_path / "caller.ps1"+ script.write_text(+ f". '{ROOT / 'scripts/install.ps1'}' -HermesHome '{tmp_path / 'home'}'\n"+ f"$env:HERMES_RUNTIME_DIR = '{tmp_path / 'tools'}'\n"+ "function Get-Command { param($Name) return $null }\n"+ "$target = 'win32-' + (Get-WindowsArch)\n"+ f"$pin = @{{Url='{primary}'; MirrorUrl='{mirror}'; Sha256='{digest}'}}\n"+ + ("$script:UvPinFiles[$target] = $pin\nGet-Uv\n" if name == "uv" else "$script:GitPinFiles[$target] = $pin\nGet-PinnedGit\n"),+ encoding="utf-8",+ )+ result = subprocess.run(["powershell", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", str(script)],+ capture_output=True, text=True, timeout=60)+ assert result.returncode != 0+ assert "digest mismatch" in result.stdout + result.stderr+ assert server[0].requests == ["/primary"]+ assert not (tmp_path / "tools").exists()+++def uv_archive():+ data = b"#!/bin/sh\n[ \"$1\" = --version ] && { printf 'fixture uv\\n'; exit 0; }; exit 73\n"+ buffer = io.BytesIO()+ with tarfile.open(fileobj=buffer, mode="w:gz") as archive:+ member = tarfile.TarInfo("uv/uv")+ member.mode, member.size = 0o755, len(data)+ archive.addfile(member, io.BytesIO(data))+ return buffer.getvalue()++[email protected]("posix")[email protected]("mode", ["primary", "missing", "corrupt", "both-missing"])+def test_posix_download_keeps_the_pinned_hash(tmp_path, server, mode):+ primary, mirror, digest = fixture_bytes(server, mode, uv_archive())+ if mode == "both-missing":+ server[0].files.clear()+ script = f"""+source '{ROOT / 'scripts/install.sh'}'+command() {{ if [ "$*" = '-v uv' ]; then return 1; fi; builtin command "$@"; }}+uv_bootstrap_pin() {{ UV_PIN_VERSION=fixture; UV_PIN_URL='{primary}'; UV_PIN_MIRROR='{mirror}'; UV_PIN_SHA256='{digest}'; }}+ensure_uv+"""+ env = {**os.environ, "HERMES_HOME": str(tmp_path / "home"), "HOME": str(tmp_path / "home"), "HERMES_RUNTIME_DIR": str(tmp_path / "tools")}+ result = subprocess.run(["bash", "-c", script], cwd=tmp_path, env=env, capture_output=True, text=True, timeout=60)+ assert (result.returncode == 0) == (mode in ("primary", "missing")), result.stdout + result.stderr+ if mode == "corrupt":+ assert "digest mismatch" in result.stderr+ if mode == "both-missing":+ assert primary in result.stderr and mirror in result.stderr+ assert server[0].requests == (["/primary", "/mirror"] if mode in ("missing", "both-missing") else ["/primary"])++[email protected]("windows")+def test_generated_windows_pins_match_the_shared_authority(tmp_path):+ from pm.artifact_mirror import mirror_url+ script = tmp_path / "pins.ps1"+ script.write_text(+ f". '{ROOT / 'scripts/install.ps1'}' -HermesHome '{tmp_path / 'home'}'\n"+ "@{uv=$script:UvPinFiles; git=$script:GitPinFiles} | ConvertTo-Json -Depth 5 -Compress\n",+ encoding="utf-8",+ )+ result = subprocess.run(["powershell", "-NoProfile", "-NonInteractive", "-File", str(script)], capture_output=True, text=True, timeout=30)+ assert result.returncode == 0, result.stderr+ emitted = json.loads(result.stdout)+ lock = json.loads((ROOT / "pm/lock.json").read_text(encoding="utf-8"))["packages"]+ for name, targets in emitted.items():+ assert targets+ for target, pin in targets.items():+ authority = lock[name]["artifacts"][target]+ assert (pin["Url"], pin["Sha256"], pin["MirrorUrl"]) == (authority["url"], authority["sha256"], mirror_url(authority["sha256"]))++[email protected]("posix")+def test_dev_setup_reaches_the_same_mirror_without_python(tmp_path, server):+ from pm.store import current_target+ body = uv_archive()+ digest = hashlib.sha256(body).hexdigest()+ http, base = server+ http.files["/archive/" + digest] = body+ repo = tmp_path / "repo"+ (repo / "pm").mkdir(parents=True)+ shutil.copyfile(ROOT / "setup-hermes.sh", repo / "setup-hermes.sh")+ (repo / "pm/artifact-mirror.json").write_text(json.dumps({"origin": base, "prefix": "archive/"}, indent=2), encoding="utf-8")+ (repo / "pm/lock.json").write_text(json.dumps({"packages": {+ "uv": {"version": "fixture", "artifacts": {current_target(): {"url": base + "/missing.tar.gz", "sha256": digest}}},+ "python": {"version": "3.14.7"},+ }}, indent=2, sort_keys=True), encoding="utf-8")+ env = {**os.environ, "HERMES_HOME": str(tmp_path / "home"), "HOME": str(tmp_path / "home"), "HERMES_RUNTIME_DIR": str(tmp_path / "tools")}+ result = subprocess.run(["bash", str(repo / "setup-hermes.sh")], cwd=repo, env=env, text=True, capture_output=True, timeout=60)+ assert result.returncode == 73, result.stdout + result.stderr # stop at the bootstrap interpreter boundary+ assert http.requests == ["/missing.tar.gz", "/archive/" + digest]diff --git a/tests/test_bootstrap_pins_fragment.py b/tests/test_bootstrap_pins_fragment.pyindex 0791e1c6260..a8da1c59313 100644--- a/tests/test_bootstrap_pins_fragment.py+++ b/tests/test_bootstrap_pins_fragment.py@@ -1,148 +1,13 @@-"""The bootstrap pin fragments must match pm/lock.json.--The installers (scripts/install.sh / scripts/install.ps1) are fetched-standalone (curl | sh, irm | iex) and bootstrap uv — and, on Windows, git —-BEFORE any checkout exists, so they cannot read pm/lock.json at run time.-scripts/gen-bootstrap-pins.py derives an inline fragment from the lockfile-and splices it between markers in each script. These tests enforce the-derive-don't-store contract: the stored bytes can never drift from-pm/lock.json (the same authority the pm package manager uses), and the-installers actually consume the pinned values instead of an unpinned-"latest" channel.--setup-hermes.sh is deliberately NOT a fragment carrier: it runs after a-checkout exists, so it reads the uv pin straight from pm/lock.json at run-time (the former pm.sh bootstrap).-"""--import json+"""Generated bootstrap pins must match the shared pin and mirror authorities."""import subprocessimport sysfrom pathlib import Path-REPO_ROOT = Path(__file__).resolve().parents[1]-GENERATOR = REPO_ROOT / "scripts" / "gen-bootstrap-pins.py"-SETUP_HERMES_SH = REPO_ROOT / "setup-hermes.sh"-INSTALL_SH = REPO_ROOT / "scripts" / "install.sh"-INSTALL_PS1 = REPO_ROOT / "scripts" / "install.ps1"-LOCK = REPO_ROOT / "pm" / "lock.json"--_SH_FILES = (INSTALL_SH,)-_POSIX_TARGETS = ("linux-x64", "linux-arm64", "darwin-x64", "darwin-arm64")-_WINDOWS_TARGETS = ("win32-x64", "win32-arm64")---def _packages() -> dict:- return json.loads(LOCK.read_text(encoding="utf-8-sig"))["packages"]-def test_fragments_match_the_pin_table():- """--check regenerates from pm/lock.json and fails on any drift."""+ root = Path(__file__).resolve().parents[1]result = subprocess.run(- [sys.executable, str(GENERATOR), "--check"],- capture_output=True,- text=True,- timeout=60,+ [sys.executable, str(root / "scripts/gen-bootstrap-pins.py"), "--check"],+ cwd=root, capture_output=True, text=True, timeout=60,)- assert result.returncode == 0, (- f"bootstrap fragments drifted from pm/lock.json:\n"- f"{result.stdout}{result.stderr}"- )---def test_installers_carry_the_pinned_uv_version():- """Both fragment-carrying installers hold the exact uv version pm/lock.json names."""- version = _packages()["uv"]["version"]- for path in _SH_FILES:- assert f'UV_PIN_VERSION="{version}"' in path.read_text(- encoding="utf-8"- ), path.name- ps1 = INSTALL_PS1.read_text(encoding="utf-8-sig")- assert f'$script:UvPinVersion = "{version}"' in ps1---def test_dev_setup_reads_the_pin_from_the_lockfile():- """setup-hermes.sh runs after a checkout exists, so it must NOT carry a- duplicated fragment: it reads the uv pin from pm/lock.json at run time."""- source = SETUP_HERMES_SH.read_text(encoding="utf-8")- assert "UV_PIN_VERSION" not in source- assert 'pm/lock.json' in source- assert "sha256" in source---def test_windows_installer_carries_the_pinned_uv_and_git():- """install.ps1's bootstrap uv and git are pm/lock.json's, not copies."""- ps1 = INSTALL_PS1.read_text(encoding="utf-8-sig")- uv = _packages()["uv"]- git = _packages()["git"]- assert f'$script:UvPinVersion = "{uv["version"]}"' in ps1- assert f'$script:GitPinVersion = "{git["version"]}"' in ps1- for target in _WINDOWS_TARGETS:- for name, entry in (("uv", uv), ("git", git)):- artifact = entry["artifacts"][target]- assert artifact["url"] in ps1, f"{name} {target} url"- assert artifact["sha256"] in ps1, f"{name} {target} sha256"---def test_windows_git_bootstrap_has_no_hand_written_version():- """A second git version authority must not come back.-- The drifted copy hard-coded a PortableGit tag + version string by hand- next to the download. Anything matching that shape means someone- re-introduced a version this test cannot keep honest — the version and- URL must come only from the generated fragment.- """- ps1 = INSTALL_PS1.read_text(encoding="utf-8-sig")- assert "$gitTag" not in ps1- assert "$gitVer" not in ps1- assert "releases/download/$gitTag" not in ps1---def test_digests_are_verified_before_any_archive_is_unpacked():- """An unverified download here is arbitrary code execution, so the- sha256 check must sit between the download and the extract/exec step."""- for path in _SH_FILES:- source = path.read_text(encoding="utf-8")- assert "digest mismatch" in source, path.name- # The digest computation appears before the tar extraction.- digest_at = source.index("sha256sum")- extract_at = source.index("tar -xzf")- assert digest_at < extract_at, f"{path.name}: verify before extract"-- ps1 = INSTALL_PS1.read_text(encoding="utf-8-sig")- # uv: digest check precedes Expand-Archive.- uv_hash = ps1.index("Get-FileHash -Path $zipPath")- uv_extract = ps1.index("Expand-Archive -Path $zipPath")- assert uv_hash < uv_extract, "uv: verify before extract"- assert "uv digest mismatch" in ps1- # git: digest check precedes the tar extraction.- git_hash = ps1.index("Get-FileHash -Path $tarPath")- git_extract = ps1.index("tar.exe -xf $tarPath")- assert git_hash < git_extract, "git: verify before extract"- assert "git digest mismatch" in ps1---def test_installers_stage_into_the_pm_store_slot():- """The installers must stage into the pm store slot- (<store>/<tool>-<version>-<target>/), not the astral ~/.local/bin- layout — so pm adopts the exact same bytes."""- for path in _SH_FILES:- source = path.read_text(encoding="utf-8")- assert f"uv-$UV_PIN_VERSION-$_target" in source, path.name- ps1 = INSTALL_PS1.read_text(encoding="utf-8-sig")- assert f'uv-$($script:UvPinVersion)-$target' in ps1- assert f'git-$($script:GitPinVersion)-$target' in ps1---def test_installers_do_not_fetch_unpinned_uv():- """The astral latest-channel installers must never come back.-- astral.sh/uv/install.sh and install.ps1 resolve "latest" at run time,- which defeats pins-as-repo-data: a hermes install could silently get a- uv nobody reviewed. The only astral.sh mentions allowed are the manual- -install docs URL (docs.astral.sh).- """- for path in _SH_FILES + (INSTALL_PS1,):- source = path.read_text(encoding="utf-8-sig")- assert "astral.sh/uv/install.sh" not in source, path.name- assert "astral.sh/uv/install.ps1" not in source, path.name+ assert result.returncode == 0, result.stdout + result.stderrdiff --git a/tests/test_packaging_build_guard.py b/tests/test_packaging_build_guard.pyindex b21db872321..c4bc3a80bfd 100644--- a/tests/test_packaging_build_guard.py+++ b/tests/test_packaging_build_guard.py@@ -114,5 +114,18 @@ def test_wheel_ships_pm_package_and_lock_json(tmp_path):with zipfile.ZipFile(artifacts[0]) as wheel:shipped = set(wheel.namelist())- missing = sorted({"pm/__init__.py", "pm/lock.json"} - shipped)+ missing = sorted({"pm/__init__.py", "pm/lock.json", "pm/artifact-mirror.json"} - shipped)assert not missing, f"wheel omits pm package files: {missing}"++ installed = tmp_path / "installed"+ with zipfile.ZipFile(artifacts[0]) as wheel:+ wheel.extractall(installed)+ check = subprocess.run(+ [sys.executable, "-I", "-S", "-c",+ "import sys; sys.path.insert(0, sys.argv[1]); "+ "from pm.artifact_mirror import mirror_url; print(mirror_url('0' * 64))", str(installed)],+ cwd=tmp_path, text=True, capture_output=True, timeout=30,+ )+ assert check.returncode == 0, check.stderr+ from pm.artifact_mirror import mirror_url+ assert check.stdout.strip() == mirror_url("0" * 64)