Skip to content

The agent that grows with you

feat(pm): repair retired termux pool pins from `pm update --termux`

ethernet4fbec9c4422b
diff --git a/pm/cli.py b/pm/cli.py
index a2a92d0a7e8..948b7689618 100644
--- a/pm/cli.py
+++ b/pm/cli.py
@@ -11,6 +11,7 @@ import sys
import time
from pathlib import Path
+from pm import termux_libs
from pm.ensure import _facts, _lockfile, _store, ensure, stage_only
from pm.operations import lock_project
from pm.package import InstallError
@@ -300,13 +301,21 @@ def _run_live(cmd: list[str], *, cwd, env, timeout: int = 3600) -> tuple[int, st
def cmd_update(args) -> int:
- """`hermes pm update [names...] [--check] [--target T] [--uv] [--npm]`.
+ """`hermes pm update [names...] [--check] [--target T] [--uv] [--npm] [--termux]`.
Resolve each package's latest via its own latest_versions() hook,
intersect across targets, and (real mode) re-pin the lockfile + install
the changed ones. --check is dry-run: hits upstream indexes, writes
nothing. --uv / --npm also refresh uv.lock (+sync venv) / package-lock.
+ --termux is its own repair pass: it repins only the pool archives the
+ rolling termux-main pool has retired under our pins.
"""
+ if args.termux:
+ ignored = [name for name, given in (("names", args.names), ("--target", args.target),
+ ("--uv", args.uv), ("--npm", args.npm)) if given]
+ if ignored:
+ print(f"::warning::--termux repairs the termux pool pins only; ignoring {', '.join(ignored)}")
+ return _termux_pass(check=args.check)
lockfile = _lockfile()
names = args.names or [n for n in lockfile.names() if not get_package(n).internal or n == "uv"]
if args.target and not args.check:
@@ -414,6 +423,37 @@ def cmd_update(args) -> int:
return 0
+def _termux_pass(*, check: bool) -> int:
+ """Repin the pool archives Termux has retired under our pins.
+
+ The bionic lock rows and the runtime-lib table have no shared version axis
+ to resolve (each pins what its own supplier ships), so this is a repair,
+ not an update: only rows whose archive is gone are touched.
+ """
+ table = termux_libs.load_table()
+ lockfile = _lockfile()
+ total = len(termux_libs.pins(table, lockfile))
+ stale = termux_libs.retired(table, lockfile, termux_libs.index())
+ if not stale:
+ print(f"termux pins: {total} rows still served by the pool")
+ return 0
+ unresolved = [entry for entry in stale if entry.replacement is None]
+ width = max(len(entry.pin.name) for entry in stale)
+ for entry in stale:
+ if entry.replacement is None:
+ print(f"{entry.pin.name:<{width}} {entry.pin.version}: the pool no longer carries it")
+ else:
+ print(f"{entry.pin.name:<{width}} {entry.pin.version} → {entry.replacement.version}")
+ if check:
+ return 1
+ applied = termux_libs.repair(table, lockfile, stale)
+ if applied:
+ termux_libs.save_table(table)
+ lockfile.save()
+ print(f"✓ {applied} termux pins repinned; restage the bionic payload to pick them up")
+ return 1 if unresolved else 0
+
+
@reuse_index_responses()
def _pin_artifacts(package, decision, current: dict) -> dict:
"""Retain unresolved targets and reuse hashes for unchanged artifact URLs."""
@@ -529,6 +569,9 @@ def main(argv=None) -> int:
p.add_argument("--target", help="resolve for a different target instead of this machine (e.g. win32-arm64)")
p.add_argument("--uv", action="store_true", help="also refresh uv.lock + venv (uv update + sync)")
p.add_argument("--npm", action="store_true", help="also refresh package-lock.json (npm update)")
+ p.add_argument("--termux", action="store_true",
+ help="repin the termux pool archives the pool has retired (the runtime-lib "
+ "table + the bionic lock rows); --check reports without writing")
p.set_defaults(func=cmd_update)
args = parser.parse_args(argv)
diff --git a/pm/termux_libs.py b/pm/termux_libs.py
new file mode 100644
index 00000000000..623a100d917
--- /dev/null
+++ b/pm/termux_libs.py
@@ -0,0 +1,220 @@
+"""Termux pool pins: the runtime-lib table and lock.json's bionic rows.
+
+``scripts/termux/stage_runtime_libs.py`` merges their .debs into one flat
+``lib/`` inside the sealed Termux payload, and ``scripts/ci/archive_inputs.py``
+mirrors the same bytes into R2. Both are chained to the pin table that lives
+beside this module.
+
+The pool is rolling: rebuilding a package DELETES the previous archive from
+``pool/main/``, so a pin rots silently until a payload build downloads it and
+gets a 404. The library set is the payload's recursive DT_NEEDED closure, so a
+pin may not simply track "newest" — a repin is a repair:
+
+ hermes pm update --termux --check # what the pool no longer serves
+ hermes pm update --termux # repin exactly those rows
+
+Nothing here resolves versions. "Move to the newest" is a different job with a
+different blast radius (a repin can land a rebuilt library under a moved
+soname), so an alive pin is left alone even when the pool has moved on.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Optional
+from urllib.parse import urlsplit
+
+from pm.store import hash_url
+from pm.update import _get_text
+
+POOL = "https://packages.termux.dev/apt/termux-main/"
+POOL_HOST = urlsplit(POOL).hostname
+INDEX_URL = f"{POOL}dists/stable/main/binary-aarch64/Packages"
+POOL_PATH_PREFIX = "/apt/termux-main/pool/main/"
+
+TABLE_NAME = "termux_runtime_libs.json"
+
+
+class PinMismatch(RuntimeError):
+ """The pool serves bytes the package index does not describe."""
+
+
+def table_path() -> Path:
+ return Path(__file__).resolve().parent / TABLE_NAME
+
+
+def load_table(path: Optional[Path] = None) -> dict:
+ return json.loads(Path(path or table_path()).read_text(encoding="utf-8-sig"))
+
+
+def save_table(table: dict, path: Optional[Path] = None) -> None:
+ Path(path or table_path()).write_text(
+ json.dumps(table, indent=2) + "\n", encoding="utf-8", newline="\n"
+ )
+
+
+# ---------------------------------------------------------------------------
+# The pool's own index (pure parse + one cached GET)
+# ---------------------------------------------------------------------------
+
+
+@dataclass(frozen=True)
+class PoolPackage:
+ name: str
+ version: str
+ url: str
+ sha256: str
+
+
+_FIELD = re.compile(r"^([A-Za-z][A-Za-z0-9-]*):[ ]?(.*)$")
+
+
+def parse_index(text: str) -> dict[str, PoolPackage]:
+ """Package -> the archive the pool currently serves.
+
+ RFC822-ish stanzas: one field per line, indented continuation lines
+ (long descriptions) ignored. A stanza without a filename or hash is not
+ installable evidence and is dropped.
+ """
+ pool: dict[str, PoolPackage] = {}
+ fields: dict[str, str] = {}
+ for line in [*text.splitlines(), ""]:
+ if not line.strip():
+ row = _package(fields)
+ if row is not None:
+ pool[row.name] = row
+ fields = {}
+ elif not line[0].isspace():
+ match = _FIELD.match(line)
+ if match:
+ fields[match.group(1)] = match.group(2).strip()
+ return pool
+
+
+def _package(fields: dict[str, str]) -> Optional[PoolPackage]:
+ name = fields.get("Package")
+ filename = fields.get("Filename")
+ sha256 = fields.get("SHA256")
+ if not name or not filename or not sha256:
+ return None
+ return PoolPackage(name, fields.get("Version", ""), POOL + filename, sha256)
+
+
+def index() -> dict[str, PoolPackage]:
+ return parse_index(_get_text(INDEX_URL))
+
+
+def package_of(url: str) -> Optional[str]:
+ """The pool package a pinned URL names, or None for any other source."""
+ parsed = urlsplit(url)
+ if parsed.scheme != "https" or parsed.netloc != POOL_HOST:
+ return None
+ if not parsed.path.startswith(POOL_PATH_PREFIX):
+ return None
+ parts = parsed.path[len(POOL_PATH_PREFIX):].split("/")
+ if len(parts) != 3 or not all(parts):
+ return None
+ return parts[1]
+
+
+def _filename(url: str) -> str:
+ return url.rsplit("/", 1)[-1]
+
+
+# ---------------------------------------------------------------------------
+# Pins, and which of them the pool has retired
+# ---------------------------------------------------------------------------
+
+
+@dataclass(frozen=True)
+class Pin:
+ scope: str # "library", "license", or "tool"
+ name: str
+ url: str
+ version: str
+
+
+@dataclass(frozen=True)
+class Retired:
+ pin: Pin
+ # None: the pool no longer carries the package at all — a rename or a
+ # drop, which needs a human, not a repin.
+ replacement: Optional[PoolPackage]
+
+
+def pins(table: dict, lockfile) -> list[Pin]:
+ """Every pinned URL the Termux pool serves, from both authorities.
+
+ The table owns the payload's libraries and its license package; the
+ lockfile owns the cross-target tools whose bionic arm is a pool .deb
+ (python, node, uv). Other lock sources — GitHub tarballs, OCI digests —
+ are not the pool's business.
+ """
+ out = [
+ Pin("library", name, row["url"], row.get("version", ""))
+ for name, row in (table.get("libs") or {}).items()
+ ]
+ licenses = table.get("licenses")
+ if licenses:
+ out.append(Pin("license", "termux-licenses", licenses["url"], licenses.get("version", "")))
+ for name in lockfile.names():
+ for target, rows in lockfile.pinned_artifacts(name).items():
+ for row in rows if isinstance(rows, list) else [rows]:
+ if isinstance(row, dict) and package_of(row.get("url", "")):
+ out.append(Pin("tool", f"{name}@{target}", row["url"], lockfile.version(name) or ""))
+ return out
+
+
+def retired(table: dict, lockfile, pool: dict[str, PoolPackage]) -> list[Retired]:
+ """Pins whose archive the pool has replaced (or dropped)."""
+ out = []
+ for pin in pins(table, lockfile):
+ entry = pool.get(package_of(pin.url) or "")
+ if entry is None or _filename(entry.url) != _filename(pin.url):
+ out.append(Retired(pin, entry))
+ return out
+
+
+def repair(table: dict, lockfile, stale: list[Retired], *, verify=None) -> int:
+ """Repin every retired row to the pool's current archive.
+
+ The index's SHA256 is not taken on faith: the replacement's bytes are
+ fetched and hashed first — the same evidence `pm lock` pins with. Rows
+ the pool no longer carries are left exactly as they are.
+ """
+ verify = verify or hash_url
+ applied = 0
+ for entry in stale:
+ if entry.replacement is None:
+ continue
+ served = verify(entry.replacement.url)
+ if served != entry.replacement.sha256:
+ raise PinMismatch(
+ f"{package_of(entry.pin.url)}: the pool serves {served}, "
+ f"the index declares {entry.replacement.sha256}"
+ )
+ _repoint(table, lockfile, entry)
+ applied += 1
+ return applied
+
+
+def _repoint(table: dict, lockfile, entry: Retired) -> None:
+ pin, replacement = entry.pin, entry.replacement
+ if pin.scope == "tool":
+ name, target = pin.name.split("@", 1)
+ artifacts = lockfile.pinned_artifacts(name)
+ rows = artifacts[target]
+ for row in rows if isinstance(rows, list) else [rows]:
+ if package_of(row.get("url", "")) == package_of(pin.url):
+ row["url"], row["sha256"] = replacement.url, replacement.sha256
+ lockfile.set_pin(name, lockfile.version(name), artifacts)
+ return
+ row = table["libs"][pin.name] if pin.scope == "library" else table["licenses"]
+ row["url"], row["sha256"], row["version"] = (
+ replacement.url,
+ replacement.sha256,
+ replacement.version,
+ )
diff --git a/scripts/termux/runtime_libs.json b/pm/termux_runtime_libs.json
similarity index 99%
rename from scripts/termux/runtime_libs.json
rename to pm/termux_runtime_libs.json
index c4ffd7e93d9..2ba79b76a7e 100644
--- a/scripts/termux/runtime_libs.json
+++ b/pm/termux_runtime_libs.json
@@ -1,5 +1,5 @@
{
- "_comment": "Pinned runtime libraries for Python, Node, uv, and ffmpeg. The ffmpeg set follows the real binaries' recursive DT_NEEDED dependencies; libc and Android system libraries remain platform-provided. Artifacts and hashes were verified from the Termux package pool.",
+ "_comment": "Pinned runtime libraries for Python, Node, uv, and ffmpeg. The ffmpeg set follows the real binaries' recursive DT_NEEDED dependencies; libc and Android system libraries remain platform-provided. Artifacts and hashes were verified from the Termux package pool. The pool deletes a package's previous archive when it rebuilds, so a pin can 404 without warning: `hermes pm update --termux --check` reports the retired rows and `--termux` repins them.",
"licenses": {
"sha256": "a3265cd1cf7d04754f2fb683eaf5b21918263792fd714457127900c1d6d9bcd9",
"url": "https://packages.termux.dev/apt/termux-main/pool/main/t/termux-licenses/termux-licenses_2.2_all.deb",
diff --git a/scripts/ci/archive_inputs.py b/scripts/ci/archive_inputs.py
index c07a6b680b8..89d4f4022c4 100644
--- a/scripts/ci/archive_inputs.py
+++ b/scripts/ci/archive_inputs.py
@@ -86,7 +86,7 @@ def pinned_inputs(repo: Path, *, target: str | None = None, packages: set[str] |
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-sig"))
+ table = json.loads((repo / "pm" / "termux_runtime_libs.json").read_text(encoding="utf-8-sig"))
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"))
diff --git a/scripts/termux/stage_runtime_libs.py b/scripts/termux/stage_runtime_libs.py
index 10de9b51d57..f5b2d377f6a 100644
--- a/scripts/termux/stage_runtime_libs.py
+++ b/scripts/termux/stage_runtime_libs.py
@@ -4,7 +4,7 @@
The sealed termux deb is self-contained by contract: the device's termux
tree may have NONE of the payload interpreters' runtime libs installed
(first real-device install: `import ctypes` dlopened libffi.so and died).
-The pin table (runtime_libs.json) is derived from the suppliers' own
+The pin table (pm/termux_runtime_libs.json) is derived from the suppliers' own
dependency metadata -- the termux-main python .deb's Depends line, uv's zstd,
nodejs's libc++/c-ares/libicu -- not from whichever lib happens to error
first.
@@ -41,6 +41,7 @@ sys.path.insert(0, str(REPO_ROOT))
from pm.downloader import Download # noqa: E402
from pm.artifact_mirror import pinned_source # noqa: E402
from pm.package import DebPackage # noqa: E402
+from pm.termux_libs import load_table # noqa: E402
PREFIX_REL = DebPackage.prefix_rel
MANIFEST_NAME = "manifest.json"
@@ -58,7 +59,7 @@ class _LibDeb(DebPackage):
self.deb_package = name
def fetch_url(self, version: str, target: str) -> str: # pragma: no cover
- raise NotImplementedError("pinned URLs live in runtime_libs.json")
+ raise NotImplementedError("pinned URLs live in pm/termux_runtime_libs.json")
def verify(self, entry: Path, target: str) -> str: # pragma: no cover
return ""
@@ -218,7 +219,7 @@ def main() -> int:
print("usage: stage_runtime_libs.py <payload-dir>", file=sys.stderr)
return 2
payload = Path(sys.argv[1]).resolve()
- table = json.loads((HERE / "runtime_libs.json").read_text(encoding="utf-8-sig"))
+ table = load_table()
try:
stage(payload, table["libs"], table.get("licenses"))
except Exception as exc: # noqa: BLE001 -- CLI boundary reports and exits
diff --git a/scripts/termux/wheelhouse_cache.py b/scripts/termux/wheelhouse_cache.py
index 952b3ff7f6e..bb2ba0c7910 100644
--- a/scripts/termux/wheelhouse_cache.py
+++ b/scripts/termux/wheelhouse_cache.py
@@ -10,8 +10,8 @@ from pathlib import Path
def build_identity(repo: Path, builder: str, platform_tag: str, python_abi: str) -> dict[str, str]:
files = (
- "uv.lock", "pyproject.toml", "pm/lock.json",
- "scripts/termux/runtime_libs.json", "scripts/termux/build_config.sh",
+ "uv.lock", "pyproject.toml", "pm/lock.json", "pm/termux_runtime_libs.json",
+ "scripts/termux/build_config.sh",
"scripts/termux/termux_build.sh", "scripts/termux/build_wheels.py",
"scripts/termux/retag_wheel.py", "scripts/termux/python_linkage.py",
"scripts/termux/wheelhouse_cache.py", "scripts/termux/build_environment.py",
diff --git a/tests/ci/test_termux_input_archive.py b/tests/ci/test_termux_input_archive.py
index fa47414a8a3..5c4ba1eae07 100644
--- a/tests/ci/test_termux_input_archive.py
+++ b/tests/ci/test_termux_input_archive.py
@@ -19,8 +19,7 @@ def test_archive_reader_accepts_bom_without_changing_pin_authority(tmp_path):
(tmp_path / "pm").mkdir()
(tmp_path / "pm/lock.json").write_bytes(b'\xef\xbb\xbf{"schema":1,"packages":{}}')
- table = tmp_path / "scripts/termux/runtime_libs.json"
- table.parent.mkdir(parents=True)
+ table = tmp_path / "pm/termux_runtime_libs.json"
row = {"url": "https://example.invalid/café.deb", "sha256": "a" * 64}
table.write_bytes(b"\xef\xbb\xbf" + json.dumps({"libs": {"lib": row}}, ensure_ascii=False).encode("utf-8"))
before = table.read_bytes()
diff --git a/tests/pm/test_source_update_launch.py b/tests/pm/test_source_update_launch.py
index 2519fbc7ba2..d03b4dc0890 100644
--- a/tests/pm/test_source_update_launch.py
+++ b/tests/pm/test_source_update_launch.py
@@ -151,7 +151,7 @@ def test_source_python_pin_update_survives_real_gc(source_launch, tmp_path, monk
monkeypatch.setattr(cli, "resolve_package", lambda *a, **k: Resolved("python", "A", "semver", "B"))
monkeypatch.setattr(cli, "_pin_artifacts", lambda *a: {})
monkeypatch.setattr(importlib.import_module("pm.ensure"), "sync_venv", pm.sync_venv)
- assert cli.cmd_update(SimpleNamespace(names=["python"], target=None, check=False, uv=False, npm=False)) == 0
+ assert cli.cmd_update(SimpleNamespace(names=["python"], target=None, check=False, uv=False, npm=False, termux=False)) == 0
assert Lockfile(paths.lockfile_path()).version("python") == "B"
assert pm.venv_is_current(project_root=root)
assert selected_venv(root) != previous
diff --git a/tests/pm/test_termux_libs.py b/tests/pm/test_termux_libs.py
new file mode 100644
index 00000000000..1c5359e6125
--- /dev/null
+++ b/tests/pm/test_termux_libs.py
@@ -0,0 +1,278 @@
+"""The termux pool pin authority: parse the index, retire, repin.
+
+No network and no payload: the index is text, the pool rows are data, and the
+one step that would touch bytes (hashing the replacement archive) is injected.
+
+`--termux` exists because the pool is rolling — rebuilding a package DELETES
+the previous archive — so the invariant every case here pins is *only retired
+rows move, and only to the archive the index describes*.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+from pathlib import Path
+
+import pytest
+
+from pm import cli, termux_libs
+from pm.lock import SCHEMA, Lockfile
+
+POOL = termux_libs.POOL
+ICONV = f"{POOL}pool/main/libi/libiconv/libiconv_1.19_aarch64.deb"
+ICONV_OLD = f"{POOL}pool/main/libi/libiconv/libiconv_1.18-1_aarch64.deb"
+GLIB = f"{POOL}pool/main/g/glib/glib_2.90.0_aarch64.deb"
+LICENSES = f"{POOL}pool/main/t/termux-licenses/termux-licenses_2.2_all.deb"
+UV_OLD = f"{POOL}pool/main/u/uv/uv_0.12.10_aarch64.deb"
+UV_NEW = f"{POOL}pool/main/u/uv/uv_0.12.15_aarch64.deb"
+
+INDEX = (
+ "Package: libiconv\n"
+ "Version: 1.19\n"
+ "Architecture: aarch64\n"
+ f"Filename: {ICONV[len(POOL):]}\n"
+ "Size: 562724\n"
+ f"SHA256: {'i' * 64}\n"
+ "Description: An implementation of iconv()\n"
+ " Depends: libc\n"
+ " This continuation line is not a stanza.\n"
+ "\n"
+ "Package: glib\n"
+ "Version: 2.90.0\n"
+ f"Filename: {GLIB[len(POOL):]}\n"
+ f"SHA256: {'g' * 64}\n"
+)
+
+
+def _lockfile(tmp_path: Path, packages: dict) -> Lockfile:
+ path = tmp_path / "lock.json"
+ path.write_text(json.dumps({"schema": SCHEMA, "packages": packages}), encoding="utf-8")
+ return Lockfile(path)
+
+
+def _uv(bionic_url: str) -> dict:
+ """uv's two axes: astral's tarball on the desktop, the pool's .deb on bionic."""
+ return {
+ "version": "0.12.3",
+ "artifacts": {
+ "darwin-x64": {"url": "https://github.com/astral-sh/uv/releases/download/0.12.3/uv.tar.gz",
+ "sha256": "d" * 64},
+ "linux-arm64-bionic": {"url": bionic_url, "sha256": "o" * 64},
+ },
+ }
+
+
+def _table(libiconv_url: str = ICONV_OLD) -> dict:
+ return {
+ "licenses": {"sha256": "l" * 64, "url": LICENSES, "version": "2.2"},
+ "libs": {
+ "glib": {"sha256": "g" * 64, "url": GLIB, "version": "2.90.0"},
+ "libiconv": {"sha256": "o" * 64, "url": libiconv_url, "version": "1.18-1"},
+ },
+ }
+
+
+def _pool(**rows: termux_libs.PoolPackage) -> dict:
+ """The pool the faked index reports, keyed by package."""
+ return {
+ "libiconv": termux_libs.PoolPackage("libiconv", "1.19", ICONV, "i" * 64),
+ "glib": termux_libs.PoolPackage("glib", "2.90.0", GLIB, "g" * 64),
+ "termux-licenses": termux_libs.PoolPackage("termux-licenses", "2.2", LICENSES, "l" * 64),
+ **rows,
+ }
+
+
+# ------------------------------------------------------------------ the index
+
+def test_parse_index_reads_stanzas_and_ignores_continuations():
+ pool = termux_libs.parse_index(INDEX)
+ assert set(pool) == {"libiconv", "glib"}
+ assert pool["libiconv"] == termux_libs.PoolPackage("libiconv", "1.19", ICONV, "i" * 64)
+ # The indented "Depends: libc" continuation must not become a field, and
+ # must not split the stanza it belongs to.
+ assert pool["glib"].sha256 == "g" * 64
+
+
+def test_parse_index_keeps_the_pool_epoch_and_drops_rows_without_a_hash():
+ text = (
+ f"Package: libvpx\nVersion: 1:1.17.0\nFilename: pool/main/libv/libvpx/libvpx_1:1.17.0_aarch64.deb\n"
+ f"SHA256: {'v' * 64}\n\n"
+ "Package: half\nVersion: 1.0\nFilename: pool/main/h/half/half_1.0_aarch64.deb\n\n"
+ )
+ pool = termux_libs.parse_index(text)
+ assert pool["libvpx"].version == "1:1.17.0"
+ assert pool["libvpx"].url.endswith("libvpx_1:1.17.0_aarch64.deb")
+ assert "half" not in pool
+
+
[email protected]("url, expected", [
+ (GLIB, "glib"),
+ (LICENSES, "termux-licenses"),
+ ("https://github.com/astral-sh/uv/releases/download/0.12.3/uv.tar.gz", None),
+ ("docker://termux/termux-docker@sha256:" + "a" * 64, None),
+ (f"{POOL}dists/stable/main/binary-aarch64/Packages", None),
+ (f"{POOL}pool/main/libi/libiconv/deeper/thing.deb", None),
+])
+def test_package_of_recognizes_only_pool_archives(url, expected):
+ assert termux_libs.package_of(url) == expected
+
+
+# ---------------------------------------------------------------------- pins
+
+def test_pins_span_the_table_and_the_pool_lock_rows(tmp_path):
+ lockfile = _lockfile(tmp_path, {"uv": _uv(UV_OLD)})
+ names = {(pin.scope, pin.name) for pin in termux_libs.pins(_table(), lockfile)}
+ assert names == {
+ ("library", "glib"),
+ ("library", "libiconv"),
+ ("license", "termux-licenses"),
+ ("tool", "uv@linux-arm64-bionic"),
+ }
+
+
+def test_pins_ignore_lock_sources_the_pool_does_not_serve(tmp_path):
+ """A GitHub tarball or an OCI digest is not the pool's to repair."""
+ lockfile = _lockfile(tmp_path, {
+ "uv": _uv(UV_OLD),
+ "chromium": {"version": "145", "artifacts": {"darwin-x64": {
+ "url": "https://cdn.playwright.dev/builds/cft/145.0.7632.6/mac-x64/chrome-mac-x64.zip",
+ "sha256": "c" * 64}}},
+ })
+ assert [pin.name for pin in termux_libs.pins({"libs": {}}, lockfile)] == ["uv@linux-arm64-bionic"]
+
+
+# ----------------------------------------------------------------- retirement
+
+def test_retirement_is_decided_by_the_filename_not_the_version_string(tmp_path):
+ """Termux version strings carry epochs and -N rebuild suffixes, and the
+ pin table's own version field can lag what the pool now reports. The
+ archive filename is the evidence that the pool still serves the pin."""
+ lockfile = _lockfile(tmp_path, {"uv": _uv(UV_OLD)})
+ table = _table(ICONV)
+ table["libs"]["libiconv"]["version"] = "1.18-1"
+ table["libs"]["glib"]["version"] = "2.90.0-1"
+ pool = _pool(uv=termux_libs.PoolPackage("uv", "0.12.10-1", UV_OLD, "o" * 64))
+ assert termux_libs.retired(table, lockfile, pool) == []
+
+
+def test_retired_reports_the_replacement_and_a_dropped_package(tmp_path):
+ lockfile = _lockfile(tmp_path, {"uv": _uv(f"{POOL}pool/main/u/uv/uv_0.12.9_aarch64.deb")})
+ table = _table()
+ table["libs"]["nolonger"] = {"sha256": "n" * 64, "version": "1",
+ "url": f"{POOL}pool/main/n/nolonger/nolonger_1_aarch64.deb"}
+ pool = _pool(uv=termux_libs.PoolPackage("uv", "0.12.15", UV_NEW, "u" * 64))
+ stale = {entry.pin.name: entry for entry in termux_libs.retired(table, lockfile, pool)}
+ assert set(stale) == {"libiconv", "uv@linux-arm64-bionic", "nolonger"}
+ assert stale["libiconv"].replacement.url == ICONV
+ assert stale["uv@linux-arm64-bionic"].replacement.url == UV_NEW
+ assert stale["nolonger"].replacement is None # dropped, not renamed
+
+
+# --------------------------------------------------------------------- repair
+
+def test_repair_repoints_only_retired_rows(tmp_path):
+ lockfile = _lockfile(tmp_path, {"uv": _uv(UV_OLD)})
+ table = _table()
+ served = {ICONV: "i" * 64, UV_NEW: "u" * 64}
+ stale = termux_libs.retired(table, lockfile, _pool(uv=termux_libs.PoolPackage("uv", "0.12.15", UV_NEW, "u" * 64)))
+
+ assert termux_libs.repair(table, lockfile, stale, verify=served.__getitem__) == 2
+ assert table["libs"]["libiconv"] == {"sha256": "i" * 64, "url": ICONV, "version": "1.19"}
+ assert table["libs"]["glib"] == {"sha256": "g" * 64, "url": GLIB, "version": "2.90.0"}
+ assert table["licenses"] == {"sha256": "l" * 64, "url": LICENSES, "version": "2.2"}
+ row = lockfile.artifacts("uv", "linux-arm64-bionic")[0]
+ assert (row["url"], row["sha256"]) == (UV_NEW, "u" * 64)
+ # uv's desktop axis is a different supplier and stays exactly as pinned.
+ assert lockfile.artifacts("uv", "darwin-x64")[0]["url"].startswith("https://github.com/")
+
+
+def test_repair_refuses_bytes_the_index_does_not_describe(tmp_path):
+ lockfile = _lockfile(tmp_path, {"uv": _uv(UV_OLD)})
+ table = _table()
+ before = json.dumps(table, sort_keys=True)
+ stale = termux_libs.retired(table, lockfile, _pool(uv=termux_libs.PoolPackage("uv", "0.12.15", UV_NEW, "u" * 64)))
+
+ with pytest.raises(termux_libs.PinMismatch):
+ termux_libs.repair(table, lockfile, stale, verify=lambda url: "z" * 64)
+ assert json.dumps(table, sort_keys=True) == before
+ assert lockfile.artifacts("uv", "linux-arm64-bionic")[0]["url"] == UV_OLD
+
+
+# ---------------------------------------------------------------- the command
+
+def deployment(tmp_path, monkeypatch):
+ """A retired library and a retired bionic tool row, with the pool faked."""
+ table_path = tmp_path / "termux_runtime_libs.json"
+ termux_libs.save_table(_table(), table_path)
+ lockfile = _lockfile(tmp_path, {"uv": _uv(UV_OLD)})
+ monkeypatch.setattr(termux_libs, "table_path", lambda: table_path)
+ monkeypatch.setattr(cli, "_lockfile", lambda: lockfile)
+ monkeypatch.setattr(termux_libs, "index",
+ lambda: _pool(uv=termux_libs.PoolPackage("uv", "0.12.15", UV_NEW, "u" * 64)))
+ # The only bytes the run touches: the replacements, served with the hash
+ # the index declares for them.
+ monkeypatch.setattr(termux_libs, "hash_url", {ICONV: "i" * 64, UV_NEW: "u" * 64}.__getitem__)
+ return table_path, lockfile
+
+
+def _args(**over):
+ base = dict(names=[], check=False, target=None, uv=False, npm=False, termux=True)
+ base.update(over)
+ return argparse.Namespace(**base)
+
+
+def test_termux_pass_check_reports_without_writing(capsys, deployment):
+ table_path, _ = deployment
+ before = table_path.read_bytes()
+ assert cli._termux_pass(check=True) == 1
+ out = capsys.readouterr().out
+ assert "libiconv" in out and "1.19" in out
+ assert "uv@linux-arm64-bionic" in out and "0.12.15" in out
+ assert table_path.read_bytes() == before
+
+
+def test_termux_pass_repins_the_retired_rows_and_saves(deployment):
+ table_path, lockfile = deployment
+ assert cli._termux_pass(check=False) == 0
+ written = json.loads(table_path.read_text(encoding="utf-8"))
+ assert written["libs"]["libiconv"] == {"sha256": "i" * 64, "url": ICONV, "version": "1.19"}
+ assert written["libs"]["glib"] == _table()["libs"]["glib"]
+ assert lockfile.artifacts("uv", "linux-arm64-bionic")[0]["url"] == UV_NEW
+
+
+def test_termux_pass_reports_a_dropped_package_as_a_failure(tmp_path, monkeypatch, capsys):
+ table_path = tmp_path / "termux_runtime_libs.json"
+ row = {"sha256": "n" * 64, "version": "1", "url": f"{POOL}pool/main/g/gone/gone_1_aarch64.deb"}
+ termux_libs.save_table({"libs": {"gone": row}}, table_path)
+ monkeypatch.setattr(termux_libs, "table_path", lambda: table_path)
+ monkeypatch.setattr(cli, "_lockfile", lambda: _lockfile(tmp_path, {}))
+ monkeypatch.setattr(termux_libs, "index", lambda: {})
+ assert cli._termux_pass(check=False) == 1
+ assert "no longer carries it" in capsys.readouterr().out
+ assert json.loads(table_path.read_text(encoding="utf-8"))["libs"]["gone"] == row
+
+
+def test_update_command_routes_termux_to_its_own_pass(monkeypatch, capsys):
+ """--termux is a repair pass, so the resolve/install path must not run."""
+ seen = []
+
+ def fake_pass(*, check):
+ seen.append(check)
+ return 0
+
+ monkeypatch.setattr(cli, "_termux_pass", fake_pass)
+ monkeypatch.setattr(cli, "resolve_package", lambda *a, **k: pytest.fail("resolved a package"))
+ assert cli.cmd_update(_args(check=True, names=["node"])) == 0
+ assert seen == [True]
+ assert "ignoring names" in capsys.readouterr().out
+
+
+def test_save_table_round_trips_with_lf_and_keeps_row_order(tmp_path):
+ path = tmp_path / "table.json"
+ table = _table()
+ termux_libs.save_table(table, path)
+ assert b"\r\n" not in path.read_bytes()
+ assert termux_libs.load_table(path) == table
+ assert list(termux_libs.load_table(path)) == ["licenses", "libs"]
diff --git a/tests/pm/test_update_artifact_refresh.py b/tests/pm/test_update_artifact_refresh.py
index 96c1b13980f..556e28b6275 100644
--- a/tests/pm/test_update_artifact_refresh.py
+++ b/tests/pm/test_update_artifact_refresh.py
@@ -66,7 +66,7 @@ def test_same_minor_refresh_updates_real_bytes_and_preserves_unresolved_targets(
engine = importlib.import_module("pm.ensure")
monkeypatch.setattr(engine, "sync_venv", lambda **kwargs: syncs.append(kwargs))
before = lock.path.read_bytes()
- args = Namespace(names=["rolling-tool"], target=None, check=True, uv=False, npm=False)
+ args = Namespace(names=["rolling-tool"], target=None, check=True, uv=False, npm=False, termux=False)
assert cli.cmd_update(args) == 1
assert lock.path.read_bytes() == before and not requests and not syncs
assert not store.exists()
diff --git a/tests/pm/test_update_dependency_legs.py b/tests/pm/test_update_dependency_legs.py
index 378511bbc68..2ccc99c9ae7 100644
--- a/tests/pm/test_update_dependency_legs.py
+++ b/tests/pm/test_update_dependency_legs.py
@@ -77,7 +77,7 @@ def test_uv_refresh_uses_real_installed_tool_and_only_the_owned_project(tmp_path
syncs = []
ensure = importlib.import_module('pm.ensure')
monkeypatch.setattr(ensure, 'sync_venv', lambda **kw: syncs.append(kw))
- args = Namespace(names=['manual-fixture'], target=None, check=True, uv=True, npm=False)
+ args = Namespace(names=['manual-fixture'], target=None, check=True, uv=True, npm=False, termux=False)
assert cli.cmd_update(args) == 0
assert not (repo / 'uv.lock').exists()
assert not syncs
@@ -161,7 +161,7 @@ def test_npm_refresh_uses_its_installed_entry_and_owned_project(monkeypatch, cap
monkeypatch.setenv('npm_config_cache', str(root / 'ambient-cache'))
before = dict(os.environ)
before_lock = lock.path.read_bytes()
- args = Namespace(names=['manual-fixture'], target=None, check=True, uv=False, npm=True)
+ args = Namespace(names=['manual-fixture'], target=None, check=True, uv=False, npm=True, termux=False)
assert cli.cmd_update(args) == 0
assert not (repo / 'package-lock.json').exists()
args.check = False
diff --git a/tests/pm/test_update_failure_status.py b/tests/pm/test_update_failure_status.py
index ecf3ee5e7a1..b0466358c9b 100644
--- a/tests/pm/test_update_failure_status.py
+++ b/tests/pm/test_update_failure_status.py
@@ -54,7 +54,7 @@ def test_failed_resolution_stops_every_apply_path(tmp_path, monkeypatch, capsys,
packages = [failed, healthy] if mixed else [failed]
lock = prepare(tmp_path, monkeypatch, packages)
before = lock.path.read_bytes()
- args = Namespace(names=[p.name for p in packages], target=None, check=check, uv=True, npm=True)
+ args = Namespace(names=[p.name for p in packages], target=None, check=check, uv=True, npm=True, termux=False)
assert cli.cmd_update(args) == 1
assert "fixture index unavailable" in capsys.readouterr().out
assert lock.path.read_bytes() == before
@@ -69,7 +69,7 @@ def test_current_and_manual_results_are_successful_without_writes(tmp_path, monk
lock = prepare(tmp_path, monkeypatch, [package])
before = lock.path.read_bytes()
for check in (True, False):
- args = Namespace(names=[package.name], target=None, check=check, uv=False, npm=False)
+ args = Namespace(names=[package.name], target=None, check=check, uv=False, npm=False, termux=False)
assert cli.cmd_update(args) == 0
assert lock.path.read_bytes() == before
assert not (tmp_path / "tools").exists()
diff --git a/tests/scripts/test_archive_inputs.py b/tests/scripts/test_archive_inputs.py
index b61309cb9cc..df7a41a2d7f 100644
--- a/tests/scripts/test_archive_inputs.py
+++ b/tests/scripts/test_archive_inputs.py
@@ -19,8 +19,7 @@ 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")
+ (repo / "pm/termux_runtime_libs.json").write_text(json.dumps(libs or {"libs": {}}), encoding="utf-8")
@pytest.fixture
@@ -245,7 +244,7 @@ def test_committed_inventory_matches_every_http_pin():
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"))
+ table = json.loads((repo / "pm/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
diff --git a/website/docs/reference/package-management.md b/website/docs/reference/package-management.md
index 531f97e4ece..980c67c92f3 100644
--- a/website/docs/reference/package-management.md
+++ b/website/docs/reference/package-management.md
@@ -507,6 +507,7 @@ not substitutes for an installed application's update mechanism.
| `pm update --check` | Query without writing. Exit 1 can mean updates exist; inspect output to distinguish an error. |
| `pm update --target TARGET` | Resolve versions for the specified target. |
| `pm update --uv` / `--npm` | Also refresh the Python or npm dependency resolution. |
+| `pm update --termux [--check]` | Repin the termux pool archives the rolling pool has retired (the runtime-lib pin table and the bionic lock rows). `--check` reports without writing and exits 1 when a pin is retired. |
| `pm install --target TARGET NAME...` | Stage explicit cross-target packages without recording them as the host's installed runtime. |
| `pm bundle --out DIR [--ref REF]` | Stage a source snapshot, native tools, facts, and Python dependencies. It does not produce a signed desktop installer. |