The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(termux): android wheelhouse builder + PEP 738 retagger
ethernet8023e84e625d87d7
diff --git a/scripts/termux/build_wheels.py b/scripts/termux/build_wheels.pynew file mode 100644index 00000000000..80653cc6272--- /dev/null+++ b/scripts/termux/build_wheels.py@@ -0,0 +1,395 @@+#!/usr/bin/env python3+"""Container-side wheelhouse build: build the android build set from sdist+against THIS container's bionic python, retag, and run the offline+completeness + import gates. Invoked by termux_build.sh inside the+digest-pinned termux/termux-docker container.++Usage: build_wheels.py --resolved RESOLVED.txt --build-set BUILD_SET.txt \+ --wheelhouse DIR --retag RETAG_SCRIPT --platform-tag TAG++Everything here runs under the container's termux python (bionic): pip+builds sdists with clang/rust from $PREFIX, wheels land in the wheelhouse,+retagging stamps the PEP 738 android tag, and the --no-index gate proves the+FULL marker-admitted lock graph installs offline from the built bytes.+"""++from __future__ import annotations++import argparse+import os+import subprocess+import sys+import tarfile+import tempfile+import shutil+from pathlib import Path, PurePosixPath+++def parse_args() -> argparse.Namespace:+ p = argparse.ArgumentParser(description=__doc__)+ p.add_argument("--resolved", required=True, help="tab-separated name/spec/marker file")+ p.add_argument("--build-set", required=True, help="names needing sdist builds (one per line)")+ p.add_argument("--wheelhouse", required=True)+ p.add_argument("--retag", required=True, help="path to retag_wheel.py")+ p.add_argument("--platform-tag", required=True)+ p.add_argument("--uv", required=True, help="path to the staged uv binary")+ return p.parse_args()+++def parse_reqs(resolved: Path) -> list[tuple[str, str]]:+ """(name, spec) pairs for every non-empty resolved line."""+ out: list[tuple[str, str]] = []+ for line in resolved.read_text(encoding="utf-8").splitlines():+ if not line.strip():+ continue+ parts = line.split("\t")+ out.append((parts[0], parts[1] if len(parts) > 1 else ""))+ return out+++def load_entries(resolved: Path) -> dict[str, str]:+ """name -> version spec ('==x.y.z') for the build loop's locked pins."""+ entries: dict[str, str] = {}+ for name, spec in parse_reqs(resolved):+ entries[name] = spec.strip()+ return entries+++def write_reqs_file(resolved: Path, reqs: Path) -> None:+ """name==spec[ ; marker] lines for a pip/uv -r file: markers+ stay attached so the INSTALLER evaluates them on the target platform+ (win32-marker deps resolve-skip on bionic); documented build misses+ are skipped (no offline solution exists for them, by design).+ """+ out = []+ for name, spec, marker in _parse_full(resolved):+ if name in BUILD_MISSES:+ continue+ line = f"{name}{spec.strip()}" if spec.strip() else name+ if marker:+ line += " ; " + marker+ out.append(line)+ body = chr(10).join(out) + chr(10)+ reqs.write_text(body, encoding="utf-8")+++def safe_extract(archive: Path, dest: Path) -> Path:+ """Safe-extract a tarball, rejecting traversal/symlink/device members."""+ with tarfile.open(archive, "r:gz") as tf:+ for member in tf.getmembers():+ path = PurePosixPath(member.name)+ parts = tuple(p for p in path.parts if p not in ("", "."))+ if path.is_absolute() or ".." in parts or not parts:+ raise RuntimeError(f"unsafe archive member path: {member.name!r}")+ target = dest.joinpath(*parts)+ if member.isdir():+ target.mkdir(parents=True, exist_ok=True)+ continue+ if not member.isfile():+ raise RuntimeError(f"unsupported archive member type: {member.name}")+ target.parent.mkdir(parents=True, exist_ok=True)+ extracted = tf.extractfile(member)+ if extracted is None:+ raise RuntimeError(f"cannot read archive member: {member.name}")+ with extracted, open(target, "wb") as dst:+ shutil.copyfileobj(extracted, dst)+ try:+ target.chmod(member.mode & 0o777)+ except OSError:+ pass+ roots = sorted(p for p in dest.iterdir() if p.is_dir())+ return roots[0] if roots else dest+++PSUTIL_MARKER = 'LINUX = sys.platform.startswith("linux")'+PSUTIL_PATCH = 'LINUX = sys.platform.startswith(("linux", "android"))'+++def patch_psutil(src_root: Path) -> None:+ common = src_root / "psutil" / "_common.py"+ if not common.is_file():+ return # not a psutil sdist; nothing to patch+ content = common.read_text(encoding="utf-8-sig")+ if PSUTIL_MARKER not in content:+ raise RuntimeError("psutil android patch marker not found -- update the patch for the pinned psutil pin")+ common.write_text(content.replace(PSUTIL_MARKER, PSUTIL_PATCH), encoding="utf-8")+++def _dist_version(name: str, spec: str) -> str | None:+ # Exact pins carry the version ("==X.Y.Z"); anything else cannot be+ # skip-checked safely, so it always builds.+ return spec.strip().lstrip("=") if spec.strip().startswith("==") else None+++def build_wheels(build_set: list[str], specs: dict[str, str], wheelhouse: Path) -> None:+ for name in build_set:+ spec = specs.get(name, "")+ req = f"{name}{spec}" if spec else name+ ver = _dist_version(name, spec)+ if ver is not None and any(+ wheelhouse.glob(f"{name.replace('-', '_')}-{ver}-*.whl")+ ):+ print(f"==> {name} {ver} already in the wheelhouse (cache restore); skipping")+ continue+ if name in ("psutil", "uvloop"):+ print(f"==> building {name} (download + extract + pre-build fixups)")+ with tempfile.TemporaryDirectory(prefix=f"hermes-build-{name}-") as tmp:+ tmp = Path(tmp)+ sdist_dir = tmp / "sdist"+ sdist_dir.mkdir()+ subprocess.run(+ [sys.executable, "-m", "pip", "download", "--no-deps", "--no-binary", ":all:",+ "--no-build-isolation", "-d", str(sdist_dir), req],+ check=True, cwd=tmp,+ )+ archives = list(sdist_dir.glob("*.tar.gz"))+ if len(archives) != 1:+ raise RuntimeError(f"expected exactly one sdist archive for {name}, got {len(archives)}")+ src = safe_extract(archives[0], tmp / "src")+ patch_psutil(src)+ if name == "uvloop":+ # uvloop vendors libuv at vendor/libuv/ WITH its own+ # autogen.sh + generated configure; the build backend+ # expects libuv CONFIGURED (build artifacts present)+ # before setup.py runs it. We run configure ourselves:+ # setup.py's own ['./configure'] invocation 127s on the+ # rewritten shebang (subprocess execv semantics), but a+ # completed configure leaves artifacts setup.py reuses.+ libuv = src / "vendor" / "libuv"+ if libuv.is_dir():+ # bash-invoked: the sdist's autogen.sh may carry a+ # non-exec mode (extraction preserves it). autogen+ # also (re)writes ./configure WITHOUT the exec bit+ # (setup.py then 127s) -- chmod after bootstrap.+ proc = subprocess.run(["bash", "autogen.sh"], cwd=libuv,+ check=False, capture_output=True, text=True)+ if proc.returncode == 0 and (libuv / "configure").is_file():+ # Run configure under the container's own sh+ # (its #!/bin/sh shebang can't exec here).+ cfg_proc = subprocess.run(+ [os.environ["PREFIX"] + "/bin/sh", "./configure"],+ cwd=libuv, check=False, capture_output=True, text=True,+ )+ if cfg_proc.returncode != 0:+ print(f"FIXUP FAILED (libuv configure) for {name}")+ print("stdout:", cfg_proc.stdout[-1500:])+ print("stderr:", cfg_proc.stderr[-1500:])+ raise subprocess.CalledProcessError(cfg_proc.returncode, cfg_proc.args)+ if proc.returncode != 0:+ # autogen needs autoreconf when configure is+ # stale; fall back to explicit bootstrap+ proc2 = subprocess.run(["autoreconf", "-i"], cwd=libuv,+ check=False, capture_output=True, text=True)+ if proc2.returncode != 0:+ print(f"FIXUP FAILED (libuv bootstrap) for {name}")+ print("autogen stdout:", proc.stdout[-1200:])+ print("autogen stderr:", proc.stderr[-1200:])+ print("autoreconf stderr:", proc2.stderr[-1200:])+ raise subprocess.CalledProcessError(proc2.returncode, proc2.args)+ proc = subprocess.run(+ [sys.executable, "-m", "pip", "wheel", "--no-deps", "--no-build-isolation",+ "-w", str(wheelhouse), str(src)],+ check=False, cwd=tmp, capture_output=True, text=True,+ )+ if proc.returncode != 0:+ print(f"BUILD FAILED: {name}")+ print("stdout:", proc.stdout[-2000:])+ print("stderr:", proc.stderr[-2000:])+ raise subprocess.CalledProcessError(proc.returncode, proc.args)+ else:+ # Build isolation LEFT ON: --no-build-isolation requires every+ # sdist's declared backend (pdm, hatchling, maturin...) to be+ # pre-installed, and the lock graph uses more backends than the+ # pinned toolchain covers. The invariant is the USER machine+ # never resolves/compiles -- the build container may fetch.+ print(f"==> building {name} (direct pip wheel, isolated backend)")+ proc = subprocess.run(+ [sys.executable, "-m", "pip", "wheel", "--no-deps",+ "--no-binary", ":all:", "-w", str(wheelhouse), req],+ check=False, capture_output=True, text=True,+ )+ if proc.returncode != 0:+ print(f"BUILD FAILED: {name}")+ print("stdout:", proc.stdout[-2000:])+ print("stderr:", proc.stderr[-2000:])+ raise subprocess.CalledProcessError(proc.returncode, proc.args)+++TARGET_ENV = {+ "implementation_name": "cpython",+ "implementation_version": "3.11.15",+ "os_name": "posix",+ "platform_machine": "aarch64",+ "platform_release": "",+ "platform_system": "Linux",+ "platform_version": "",+ "python_full_version": "3.11.15",+ "python_version": "3.11",+ "sys_platform": "linux",+}++# Mirrors the documented misses in termux_build.sh's probe (single+# source is ideal; duplicated until the probe emits a sidecar file).+BUILD_MISSES = {"nemo-relay"}+++def _marker_admits(marker: str) -> bool:+ if not marker:+ return True+ from packaging.markers import Marker+ try:+ return Marker(marker).evaluate(TARGET_ENV)+ except Exception:+ return True+++def _parse_full(resolved: Path) -> list[tuple[str, str, str]]:+ """(name, spec, marker) triples from the tab-separated resolved file."""+ out: list[tuple[str, str, str]] = []+ for line in resolved.read_text(encoding="utf-8").splitlines():+ if not line.strip():+ continue+ parts = line.split("\t")+ out.append((parts[0], parts[1] if len(parts) > 1 else "",+ parts[2] if len(parts) > 2 else ""))+ return out+++def fetch_pure_wheels(build_set: list[str], specs: dict[str, str], wheelhouse: Path, resolved: Path) -> None:+ """Fetch every APPLICABLE dep's py3-none-any wheel into the wheelhouse.++ The offline completeness gate installs the FULL marker-admitted graph+ from --find-links wheelhouse under --no-index; the natives were built+ here, but the pure wheels live only on PyPI. Fetch them (the build+ container may resolve; the USER machine never does). Wheels already+ present (built natives) are skipped by pip download naturally.+ Marker-excluded deps (pywin32, winrt-*) and documented build misses+ (nemo-relay) are skipped -- the gate's reqs carry the same exclusions+ via the venv's own marker evaluation... which they do NOT: write_reqs_file+ writes the full list and uv evaluates markers from the RUNNING platform.+ The gate reqs keep all lines; pip/uv on bionic skips the win32 ones.+ """+ reqs = []+ for name, spec, marker in _parse_full(resolved):+ if name in build_set or name in BUILD_MISSES:+ continue+ if not _marker_admits(marker):+ continue+ reqs.append(f"{name}{spec.strip()}" if spec.strip() else name)+ # Build-backend deps the deb-venv's app install resolves offline:+ # the app dir install (even --no-deps) prepares metadata through+ # build-system.requires, which needs setuptools in the find-links.+ reqs.append("setuptools==83.0.0")+ if not reqs:+ return+ proc = subprocess.run(+ [sys.executable, "-m", "pip", "download", "--no-deps",+ "--only-binary", ":all:", "-d", str(wheelhouse), *reqs],+ check=False, capture_output=True, text=True,+ )+ if proc.returncode != 0:+ print("PURE-WHEEL FETCH FAILED")+ print("stdout:", proc.stdout[-1500:])+ print("stderr:", proc.stderr[-1500:])+ raise subprocess.CalledProcessError(proc.returncode, proc.args)+ fetched = len(list(wheelhouse.glob("*.whl")))+ print(f" pure wheels fetched; wheelhouse now holds {fetched} wheels")+++def retag_all(wheelhouse: Path, retag_script: Path, platform_tag: str) -> None:+ wheels = sorted(wheelhouse.glob("*.whl"))+ if not wheels:+ raise RuntimeError(f"no wheels built into {wheelhouse}")+ # maturin-built wheels (cryptography, pydantic-core, jiter, watchfiles)+ # emerge ANDROID-tagged already (ANDROID_API_LEVEL drives the build);+ # only the setuptools/distutils-built ones carry linux_aarch64 tags and+ # need the retag. Retagging an android wheel again is a hard error.+ linux_tagged = [w for w in wheels if "linux" in w.name and "none-any" not in w.name]+ android_tagged = [w for w in wheels if "android" in w.name]+ if linux_tagged:+ subprocess.run(+ [sys.executable, str(retag_script), "--platform-tag", platform_tag, *linux_tagged],+ check=True,+ )+ retagged = list(wheelhouse.glob(f"*{platform_tag}*.whl"))+ total_android = len(retagged)+ if total_android == 0:+ raise RuntimeError(f"no wheels retagged to {platform_tag}")+ print(f" retagged {len(linux_tagged)} linux-tagged wheels; {len(android_tagged)} were android-tagged at build; {total_android} android wheels total")+++def wheelhouse_gates(resolved: Path, wheelhouse: Path, build_set: list[str]) -> None:+ """Offline install of every marker-admitted dep into ONE clean venv,+ shared by both gates (the full offline install runs once, not twice).++ 1. completeness: --no-index makes completeness a build-time invariant+ -- a dep missing from the wheelhouse fails loudly. The container's+ own bionic python evaluates the markers exactly as the phone will+ (sys_platform/platform_machine are real here), so deps the android+ target excludes (pywin32, winrt-*) are skipped by pip itself.+ 2. imports: every NATIVE wheel we built must import (the py3-none-any+ wheels are PyPI bytes; OUR builds are what this gate proves).+ """+ with tempfile.TemporaryDirectory(prefix="hermes-wheelhouse-gate-") as tmp:+ tmp = Path(tmp)+ venv = tmp / "venv"+ subprocess.run(+ [UV, "venv", "--python", sys.executable, str(venv)],+ check=True,+ )+ vp = venv / "bin" / "python"+ reqs = tmp / "reqs.txt"+ write_reqs_file(resolved, reqs)+ subprocess.run(+ [UV, "pip", "install", "--python", str(vp),+ "--only-binary", ":all:", "--no-index",+ "--find-links", str(wheelhouse), "-r", str(reqs)],+ check=True,+ )+ subprocess.run([UV, "pip", "check", "--python", str(vp)], check=True)+ print(" completeness gate: offline install of the marker-admitted graph OK")+ # dist -> module (only where they differ)+ MODULE = {+ "ruamel-yaml-clib": "_ruamel_yaml",+ "cffi": "_cffi_backend",+ "pillow": "PIL",+ "pyyaml": "yaml",+ }+ mods = [MODULE.get(n, n.replace("-", "_")) for n in build_set]+ script = ",".join(mods)+ subprocess.run(+ [str(vp), '-c',+ 'import importlib, sys\n'+ 'for name in sys.argv[1].split(''):\n'+ ' importlib.import_module(name)\n'+ ' print('' imported'', name)\n',+ script],+ check=True,+ )+ print(" import gate: every built native wheel imports")++++UV = ""+++def main() -> int:+ global UV+ args = parse_args()+ UV = str(Path(args.uv))+ resolved = Path(args.resolved)+ build_set = [l.strip() for l in Path(args.build_set).read_text(encoding="utf-8").splitlines() if l.strip()]+ wheelhouse = Path(args.wheelhouse)+ wheelhouse.mkdir(parents=True, exist_ok=True)+ specs = load_entries(resolved)++ build_wheels(build_set, specs, wheelhouse)+ fetch_pure_wheels(build_set, specs, wheelhouse, Path(args.resolved))+ retag_all(wheelhouse, Path(args.retag), args.platform_tag)+ wheelhouse_gates(resolved, wheelhouse, build_set)+ print(f"wheelhouse complete: {len(list(wheelhouse.glob('*.whl')))} wheels in {wheelhouse}")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/termux/retag_wheel.py b/scripts/termux/retag_wheel.pynew file mode 100644index 00000000000..388f47938d2--- /dev/null+++ b/scripts/termux/retag_wheel.py@@ -0,0 +1,287 @@+#!/usr/bin/env python3+"""PEP 738 wheel retagger for the Termux/Android wheelhouse.++Rewrites a built (e.g. linux_aarch64 / manylinux) wheel so it installs on+Android/bionic under Termux:++ * wheel filename platform field (last dash-field before ``.whl``)+ * every ``Tag:`` line inside ``<dist>.dist-info/WHEEL``+ * ``RECORD`` is regenerated from the new member contents++Everything is verified before anything is rewritten:++ * the wheel's filename package/version must match its ``METADATA``+ * the archive must pass a full ZIP integrity check+ * the wheel must contain at least one native extension (``.so``) --+ retagging a pure wheel onto a platform tag would be a lie+ * the target platform tag must be a valid PEP 738 android tag++Pure stdlib. ASCII only.+"""++from __future__ import annotations++import argparse+import base64+import csv+import hashlib+import io+import os+import re+import sys+import tempfile+import zipfile++ANDROID_TAG_RE = re.compile(r"^android_(\d+)_arm64_v8a$")+RECORD_SUFFIX = "dist-info/RECORD"+WHEEL_SUFFIX = "dist-info/WHEEL"+++class RetagError(RuntimeError):+ """Raised when a wheel cannot be safely retagged."""+++def record_hash(data: bytes) -> str:+ digest = hashlib.sha256(data).digest()+ return "sha256=" + base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")+++def parse_wheel_filename(filename: str) -> tuple[str, str, str, str, str]:+ """Return (distribution, version, python_tag, abi_tag, platform_tag)."""+ if not filename.endswith(".whl"):+ raise RetagError(f"not a wheel filename: {filename!r}")+ stem = filename[: -len(".whl")]+ parts = stem.split("-")+ if len(parts) != 5:+ raise RetagError(+ f"unexpected wheel filename shape (want 5 dash fields): {filename!r}"+ )+ distribution, version, python_tag, abi_tag, platform_tag = parts+ if not distribution or not version:+ raise RetagError(f"empty distribution/version in {filename!r}")+ return distribution, version, python_tag, abi_tag, platform_tag+++def _read_metadata(archive: zipfile.ZipFile) -> tuple[str, str]:+ """Return (name, version) parsed from METADATA."""+ records = [n for n in archive.namelist() if n.endswith(RECORD_SUFFIX)]+ if len(records) != 1:+ raise RetagError(f"expected exactly one dist-info/RECORD, found {records!r}")+ metadata_name = records[0][: -len("RECORD")] + "METADATA"+ try:+ text = archive.read(metadata_name).decode("utf-8")+ except KeyError:+ raise RetagError(f"missing {metadata_name}") from None+ name = None+ version = None+ for line in text.splitlines():+ if line.startswith("Name:"):+ name = line[len("Name:"):].strip()+ elif line.startswith("Version:"):+ version = line[len("Version:"):].strip()+ if name is not None and version is not None:+ break+ if not name or not version:+ raise RetagError(f"incomplete METADATA in {metadata_name}")+ return name, version+++def _validate(archive: zipfile.ZipFile, filename: str, new_platform: str) -> str:+ """Run all pre-retag checks; return the wheel's dist-info prefix."""+ distribution, version, _, _, platform_tag = parse_wheel_filename(filename)++ if ANDROID_TAG_RE.match(platform_tag):+ raise RetagError(f"{filename} is already an android-tagged wheel")++ name, meta_version = _read_metadata(archive)+ # PEP 503-normalized comparison: setuptools writes canonical lowercase+ # filenames while METADATA carries the display name (markupsafe vs+ # MarkupSafe). Case is not identity for package names.+ def _norm(n: str) -> str:+ return re.sub(r"[-._]+", "-", n).lower()++ if name and distribution and _norm(name) != _norm(distribution):+ raise RetagError(+ f"wheel filename package {distribution!r} does not match "+ f"METADATA Name {name!r}"+ )+ if meta_version != version:+ raise RetagError(+ f"wheel filename version {version!r} does not match "+ f"METADATA Version {meta_version!r}"+ )++ # No archive-wide testzip(): every member read below (archive.read)+ # already verifies the member CRC and raises zipfile.BadZipFile on+ # mismatch, so the full-archive decompress would be pure duplicated work.++ if not any(n.endswith(".so") for n in archive.namelist()):+ raise RetagError(+ f"{filename} contains no native extension (.so); refusing to "+ "stamp a platform tag onto a pure wheel"+ )++ dist_info_prefix = f"{distribution}-{version}.dist-info/"+ wheel_member = dist_info_prefix + "WHEEL"+ if wheel_member not in archive.namelist():+ raise RetagError(f"missing {wheel_member}")+ tags = [+ line[len("Tag:"):].strip()+ for line in archive.read(wheel_member).decode("utf-8").splitlines()+ if line.startswith("Tag:")+ ]+ if not tags:+ raise RetagError(f"no Tag: lines in {wheel_member}")+ for tag in tags:+ fields = tag.split("-")+ if len(fields) != 3 or fields[2] != platform_tag:+ raise RetagError(+ f"WHEEL tag {tag!r} inconsistent with filename platform "+ f"{platform_tag!r}"+ )++ if not ANDROID_TAG_RE.match(new_platform):+ raise RetagError(+ f"target platform tag {new_platform!r} is not a PEP 738 "+ "android_<abi>_arm64_v8a style tag"+ )+ return dist_info_prefix+++def retag_wheel(wheel_path: str, new_platform: str) -> str:+ """Retag the wheel at *wheel_path*; return the new wheel path."""+ wheel_path = os.path.abspath(wheel_path)+ wheel_name = os.path.basename(wheel_path)+ distribution, version, python_tag, abi_tag, _ = parse_wheel_filename(wheel_name)+ new_wheel_name = "-".join(+ (distribution, version, python_tag, abi_tag, new_platform)+ ) + ".whl"++ with zipfile.ZipFile(wheel_path, "r") as archive:+ dist_info_prefix = _validate(archive, wheel_name, new_platform)++ wheel_member = dist_info_prefix + "WHEEL"+ old_wheel_text = archive.read(wheel_member).decode("utf-8")++ new_wheel_lines = []+ for line in old_wheel_text.splitlines():+ if line.startswith("Tag:"):+ fields = line[len("Tag:"):].strip().split("-")+ new_tag = "-".join((fields[0], fields[1], new_platform))+ new_wheel_lines.append("Tag: " + new_tag)+ else:+ new_wheel_lines.append(line)+ new_wheel_text = "\n".join(new_wheel_lines) + "\n"++ members: list[tuple[str, bytes]] = []+ for info in archive.infolist():+ if info.is_dir():+ continue+ members.append((info.filename, archive.read(info.filename)))++ new_members: list[tuple[str, bytes]] = []+ record_rows: list[tuple[str, str, str]] = []+ for name, data in members:+ if name == wheel_member:+ data = new_wheel_text.encode("utf-8")+ new_members.append((name, data))+ record_rows.append((name, record_hash(data), str(len(data))))+ elif name == dist_info_prefix + "RECORD":+ continue # regenerated below+ else:+ new_members.append((name, data))+ record_rows.append((name, record_hash(data), str(len(data))))+ record_rows.append((dist_info_prefix + "RECORD", "", ""))++ record_buf = io.StringIO()+ writer = csv.writer(record_buf, lineterminator="\n")+ writer.writerows(record_rows)+ new_members.append(+ (dist_info_prefix + "RECORD", record_buf.getvalue().encode("utf-8"))+ )++ out_dir = os.path.dirname(wheel_path)+ fd, tmp_path = tempfile.mkstemp(prefix=".retag-", suffix=".whl", dir=out_dir)+ os.close(fd)+ try:+ with zipfile.ZipFile(tmp_path, "w", zipfile.ZIP_DEFLATED) as out:+ for name, data in new_members:+ out.writestr(name, data)+ new_wheel_path = os.path.join(out_dir, new_wheel_name)+ os.replace(tmp_path, new_wheel_path)+ finally:+ if os.path.exists(tmp_path):+ os.unlink(tmp_path)++ if os.path.abspath(new_wheel_path) != wheel_path:+ os.unlink(wheel_path)+ return new_wheel_path+++def self_check() -> int:+ """Refuse to run unless the module's invariants hold (used by the build gate)."""+ with tempfile.TemporaryDirectory() as tmp:+ good = os.path.join(tmp, "demo_pkg-1.0-cp312-cp312-linux_aarch64.whl")+ with zipfile.ZipFile(good, "w") as zf:+ zf.writestr("demo_pkg/__init__.py", "x = 1\n")+ zf.writestr("demo_pkg/_native.so", b"\x7fELFfake")+ metadata = "Metadata-Version: 2.1\nName: demo_pkg\nVersion: 1.0\n"+ zf.writestr("demo_pkg-1.0.dist-info/METADATA", metadata)+ zf.writestr(+ "demo_pkg-1.0.dist-info/WHEEL",+ "Wheel-Version: 1.0\nTag: cp312-cp312-linux_aarch64\n",+ )+ zf.writestr("demo_pkg-1.0.dist-info/RECORD", "")+ retag_wheel(good, "android_24_arm64_v8a")+ retagged = os.path.join(+ tmp, "demo_pkg-1.0-cp312-cp312-android_24_arm64_v8a.whl"+ )+ if not os.path.exists(retagged):+ raise SystemExit("self_check: retagged wheel missing")+ with zipfile.ZipFile(retagged) as zf:+ names = zf.namelist()+ wheel_txt = zf.read("demo_pkg-1.0.dist-info/WHEEL").decode("utf-8")+ record_txt = zf.read("demo_pkg-1.0.dist-info/RECORD").decode("utf-8")+ assert "Tag: cp312-cp312-android_24_arm64_v8a" in wheel_txt+ assert any(n.endswith("_native.so") for n in names)+ assert "demo_pkg-1.0.dist-info/RECORD,," in record_txt+ return 0+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(+ description="Retag one or more wheels for PEP 738 Android/Termux."+ )+ parser.add_argument(+ "wheels",+ nargs="*",+ help="paths to the wheels to retag (batch mode: all processed "+ "in-process, stopping at the first error)",+ )+ parser.add_argument(+ "--platform-tag",+ default="android_24_arm64_v8a",+ help="target platform tag (default: android_24_arm64_v8a)",+ )+ parser.add_argument(+ "--self-check",+ action="store_true",+ help="run the built-in round-trip self-check instead of retagging",+ )+ args = parser.parse_args(argv)+ if args.self_check:+ return self_check()+ if not args.wheels:+ parser.error("at least one wheel path is required unless --self-check is given")+ for wheel in args.wheels:+ try:+ new_path = retag_wheel(wheel, args.platform_tag)+ except (RetagError, zipfile.BadZipFile, OSError) as exc:+ print(f"retag_wheel: error: {wheel}: {exc}", file=sys.stderr)+ return 1+ print(new_path)+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/termux/termux_build.sh b/scripts/termux/termux_build.shnew file mode 100644index 00000000000..c470a6bdf95--- /dev/null+++ b/scripts/termux/termux_build.sh@@ -0,0 +1,453 @@+#!/usr/bin/env bash+# Android/Termux wheelhouse builder -- the ONE entry point. Two halves:+#+# HOST half (glibc runner): tag gates, archive, uv resolve, marker-aware+# PyPI probe -> resolved.txt + build_set.txt. Pure data work; arch-free.+#+# CONTAINER half (bionic termux-docker): toolchain pins, the 13-ish native+# sdist builds (clang/rust against the container's own termux python),+# PEP 738 retag, the --no-index completeness gate, and the import gate.+# The wheels MUST be bionic: building them on the glibc host would ship+# glibc binaries that cannot exec on any phone.+#+# The script re-invokes ITSELF with --in-container inside the digest-pinned+# image (from pm/lock.json's termux-docker package). No opt-out flags.+#+# Inputs (host mode, all required):+# --repo <dir> hermes-agent checkout to build from (must contain the tag)+# --tag <tag> immutable release tag (vX.Y.Z or vX.Y.Z-canary.<ts>)+# --out <dir> output dir (wheelhouse/ + index.json + SHA256SUMS land here)++set -Eeuo pipefail++HERE="$(cd "$(dirname "$0")" && pwd)"+# shellcheck source=scripts/termux/build_config.sh+. "$HERE/build_config.sh"++log() { printf '\n==> %s\n' "$*"; }+fail() { printf 'termux_build: FAILED: %s\n' "$*" >&2; exit 1; }++if [ "${1:-}" = "--in-container" ]; then+ # =================== CONTAINER HALF (bionic) =======================+ RESOLVED="$2"; BUILD_SET="$3"; WHEELHOUSE="$4"+ # $5 (optional) is the staged payload root (mounted at /payload):+ # the wheels are built with THE PAYLOAD'S OWN python -- the TUR .deb+ # pm staged from the lock -- so the ABI is the shipped ABI by+ # construction and the offline gate installs into a venv of the very+ # interpreter the phone will run.+ PAYLOAD_ROOT="${5:-}"+ export PREFIX=/data/data/com.termux/files/usr+ STAGED_PY="$PAYLOAD_ROOT/python$PREFIX/bin/python3.11"+ STAGED_UV="$PAYLOAD_ROOT/uv$PREFIX/bin/uv"+ # The staged binaries' RUNPATHs point at the phone's $PREFIX layout+ # (linkerconfig on-device). Inside the container the tree lives at+ # $PAYLOAD_ROOT/python$PREFIX, so the dynamic linker needs to be told+ # where the payload's libs live before any staged binary runs.+ export LD_LIBRARY_PATH="$PAYLOAD_ROOT/python$PREFIX/lib:$PAYLOAD_ROOT/node$PREFIX/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"+ if [ -n "$PAYLOAD_ROOT" ] && [ -x "$STAGED_PY" ] && [ -x "$STAGED_UV" ]; then+ PY="$STAGED_PY"+ UV="$STAGED_UV"+ log "Using the staged payload python ($PY) and uv ($UV)"+ else+ # No payload staged (or missing): refuse. Building against any+ # other interpreter (the container's pkg python is 3.14!) ships+ # wheels the payload venv cannot install. No silent fallback.+ fail "staged payload python missing at $STAGED_PY -- stage the payload (pm lock rows) before the wheelhouse"+ fi+ # BUILD tools come from termux's own apt (the image is a bare+ # bootstrap). The USER machine never does any of this.+ if ! command -v clang >/dev/null 2>&1; then+ log "Provisioning the container build toolchain (termux apt)"+ export DEBIAN_FRONTEND=noninteractive+ # Pin the OFFICIAL mirror and use apt DIRECTLY: pkg (the wrapper)+ # re-runs mirror selection and rewrote our pin to a desynced+ # third-party mirror mid-run (live 404 on libexpat). apt respects+ # sources.list as written. Retry the update for propagation windows.+ printf '%s\n' "deb https://packages.termux.dev/apt/termux-main stable main" \+ > "$PREFIX/etc/apt/sources.list"+ rm -f "$PREFIX/etc/apt/sources.list.d"/*.list 2>/dev/null || true+ apt update || apt update \+ || fail "apt update failed in the container"+ apt install -y clang rust make patchelf binutils pkg-config protobuf cmake ninja autoconf automake libtool \+ libandroid-posix-semaphore libandroid-support libbz2 libffi \+ libjpeg-turbo libpng freetype libtiff libwebp openjpeg littlecms \+ libyaml openssl readline zlib liblzma libsqlite ncurses \+ || fail "apt install of the build toolchain failed"+ fi+ # BINARIES, not package names: the rust package provides rustc/cargo+ # (there is no `rust` binary).+ for tool in clang rustc cargo make; do+ command -v "$tool" >/dev/null 2>&1 \+ || fail "container lacks $tool after provisioning"+ done+ # Serial builds only -- parallel Rust/C builds OOM arm runners.+ export CARGO_BUILD_JOBS=1+ export MAKEFLAGS=-j1+ export UV_CONCURRENT_BUILDS=1+ # Native extension links need the STAGED payload's libpython: the+ # container's own $PREFIX/lib (bootstrap only) is on the default+ # -L path, but libpython3.11.so lives in the staged tree. setuptools+ # honors LDFLAGS, so every sdist build's link step finds it.+ STAGED_PYLIB="$PAYLOAD_ROOT/python$PREFIX/lib"+ export LDFLAGS="-L$STAGED_PYLIB ${LDFLAGS:-}"+ export CFLAGS="-I$PAYLOAD_ROOT/python$PREFIX/include ${CFLAGS:-}"+ # maturin (rust-backend sdists: cryptography, pydantic-core, ...) needs+ # the Android API level explicitly on a non-phone host. Matches the+ # wheel platform tag (android_24_arm64_v8a).+ export ANDROID_API_LEVEL=24+ # The container has no /bin/sh (termux's sh lives at $PREFIX/bin/sh);+ # scripts with #!/bin/sh shebangs (uvloop's libuv configure) exec-127.+ # Link the standard path into the container's namespace.+ if [ ! -e /bin/sh ]; then+ ln -s "$PREFIX/bin/sh" /bin/sh \+ || fail "could not link /bin/sh to the termux sh"+ fi+ # cargo composes its OWN link line (ignores LDFLAGS); pyo3 finds the+ # python BINARY via PYO3_PYTHON but the -lpython lib search path must+ # come through RUSTFLAGS, which cargo forwards to the linker.+ export RUSTFLAGS="-L$STAGED_PYLIB ${RUSTFLAGS:-}"+ # protoc-bin-vendored ships no android binary; the termux protobuf+ # package provides one, and PROTOC_BIN_PATH points vendored crates+ # at it (nemo-relay's worker-proto otherwise fails codegen).+ export PROTOC="$PREFIX/bin/protoc"+ export PROTOC_BIN_PATH="$PREFIX/bin/protoc"+ log "Creating the scratch build venv + enforcing toolchain pins (staged uv)"+ # The container runs as its own uid: /out (runner-owned) and /tmp are+ # NOT writable, but the container's own termux prefix IS (provisioning+ # already writes there). Scratch venv under $PREFIX/tmp.+ mkdir -p "$PREFIX/tmp"+ BUILD_VENV="$PREFIX/tmp/hermes-build-venv"+ "$UV" venv --python "$PY" "$BUILD_VENV" \+ || fail "scratch build venv creation failed"+ # uv venvs ship WITHOUT pip; the sdist build loop shells out to+ # `python -m pip wheel`, which needs pip INSIDE the venv. uv installs+ # it from outside (the only tool that can, cleanly, on bionic).+ "$UV" pip install --python "$BUILD_VENV/bin/python" pip packaging \+ || fail "pip bootstrap into the build venv failed"+ "$UV" pip install --python "$BUILD_VENV/bin/python" "${TOOLCHAIN_PINS[@]}" \+ || fail "toolchain pin enforcement failed"+ log "Building the android wheel set from sdist (bionic, payload ABI)"+ "$BUILD_VENV/bin/python" -u "$HERE/build_wheels.py" \+ --resolved "$RESOLVED" --build-set "$BUILD_SET" \+ --wheelhouse "$WHEELHOUSE" --retag "$HERE/retag_wheel.py" \+ --platform-tag "$PLATFORM_TAG" --uv "$UV" \+ || fail "wheel building failed"+ log "Wheelhouse container phase complete"+ # Root-owned outputs: make world-readable BEFORE exiting so the+ # host runner (different uid) can read/hash/publish them. The bind+ # mount's own top dir resists chmod (host-owned); only the FILES+ # need to be readable.+ find "$WHEELHOUSE" -type f -exec chmod a+r {} + 2>/dev/null || true+ exit 0+fi++# ===================== HOST HALF (glibc runner) ==========================+REPO=""+TAG=""+OUT=""+while [ "$#" -gt 0 ]; do+ case "$1" in+ --repo) REPO="${2:?}"; shift 2 ;;+ --tag) TAG="${2:?}"; shift 2 ;;+ --out) OUT="${2:?}"; shift 2 ;;+ *) printf 'usage: termux_build.sh --repo <dir> --tag <tag> --out <dir>\n' >&2; exit 2 ;;+ esac+done+[ -n "$REPO" ] && [ -n "$TAG" ] && [ -n "$OUT" ] || {+ printf 'usage: termux_build.sh --repo <dir> --tag <tag> --out <dir>\n' >&2; exit 2; }++for tool in uv git curl docker python3; do+ command -v "$tool" >/dev/null 2>&1 \+ || fail "missing tool: $tool (CI must provision the pinned toolchain before running this script)"+done++ARCH="$(uname -m)"+case "$ARCH" in+ aarch64|arm64) ;;+ *) fail "refusing to build on non-aarch64 host (uname -m: $ARCH)" ;;+esac++# [b] FIRST: refuse mutable releases.+log "Verifying release tag $TAG exists on origin"+git -C "$REPO" ls-remote --exit-code --tags origin "$TAG" >/dev/null \+ || fail "tag $TAG not found on origin; refusing to build a mutable release"+if command -v gh >/dev/null 2>&1; then+ gh release view "$TAG" --repo "$(git -C "$REPO" remote get-url origin | sed -e 's#.*github.com[:/]##' -e 's#\.git$##')" >/dev/null 2>&1 \+ || fail "release $TAG not found; refusing to build before the release exists"+fi++REPO_ABS="$(cd "$REPO" && pwd)"+OUT_ABS="$(mkdir -p "$OUT" && cd "$OUT" && pwd)"+WORK="$OUT_ABS/.work"+WHEELHOUSE="$OUT_ABS/wheelhouse"+# Clear ONLY the scratch work dir: the wheelhouse may hold the CI-restored+# cache the fast-path check (below) verifies; deleting it here would force+# the 20-minute container rebuild on every run. A cache miss rebuilds into+# the same dir (the container phase overwrites/extends it). resolved.txt+# rides the same cache and the skip path's reqs generation consumes it, so+# carry it across the wipe.+RESOLVED_KEEP=""+if [ -f "$WORK/resolved.txt" ]; then+ RESOLVED_KEEP="$(mktemp)"+ cp "$WORK/resolved.txt" "$RESOLVED_KEEP"+fi+rm -rf "$WORK"+mkdir -p "$WORK" "$WHEELHOUSE"+if [ -n "$RESOLVED_KEEP" ] && [ -f "$RESOLVED_KEEP" ]; then+ cp "$RESOLVED_KEEP" "$WORK/resolved.txt"+ rm -f "$RESOLVED_KEEP"+fi++# [c] Stage the tag as a gitless tree.+log "Archiving $TAG into $WORK/tree"+git -C "$REPO_ABS" archive --format=tar "$TAG" | tar -xf - -C "$WORK/tree" 2>/dev/null || {+ mkdir -p "$WORK/tree"+ git -C "$REPO_ABS" archive --format=tar -o "$WORK/tree.tar" "$TAG"+ tar -xf "$WORK/tree.tar" -C "$WORK/tree"+ rm -f "$WORK/tree.tar"+}+[ -f "$WORK/tree/pyproject.toml" ] || fail "archived tag tree has no pyproject.toml -- bad tag?"++# Cache-hit fast path (checked BEFORE the resolve/probe so a hit skips the+# ~100-round-trip PyPI coverage probe too): the wheelhouse cache key covers+# uv.lock + the build scripts, so a restored wheelhouse is BY CONSTRUCTION+# the exact graph the gates proved on the run that saved it. resolved.txt+# rides the same cache (the deb's reqs generation consumes it).+WHEELHOUSE_CACHE_OK=0+if python3 - "$OUT_ABS/index.json" "$OUT_ABS/wheelhouse" <<'PYCHK' 2>/dev/null+import hashlib, json, sys+from pathlib import Path++index_file, wheelhouse = Path(sys.argv[1]), Path(sys.argv[2])+if not index_file.is_file():+ sys.exit(1)+index = json.loads(index_file.read_text(encoding="utf-8"))+for wheel in index.get("wheels", []):+ f = wheelhouse / wheel["name"]+ if not f.is_file() or hashlib.sha256(f.read_bytes()).hexdigest() != wheel["sha256"]:+ sys.exit(1)+sys.exit(0)+PYCHK+then+ WHEELHOUSE_CACHE_OK=1+ log "Wheelhouse cache restored complete -- skipping resolve, probe, and the container build"+fi++if [ "$WHEELHOUSE_CACHE_OK" -eq 0 ]; then+# [d] Resolve the real graph from the tag's own lock.+log "Resolving dependency graph from the tag's uv.lock"+( cd "$WORK/tree" && uv export --frozen --no-emit-project -o "$WORK/req.txt" ) \+ || fail "uv export failed (frozen lock at $TAG)"+RESOLVED="$WORK/resolved.txt"+python3 - "$WORK/req.txt" "$RESOLVED" <<'PYEOF' || fail "failed to normalize requirements"+import re, sys+out = []+for line in open(sys.argv[1], encoding="utf-8"):+ line = line.strip()+ # uv export wraps long lines with backslash continuations; strip the+ # trailing continuation BEFORE capturing markers/specs -- a backslash+ # riding into a marker makes Marker() throw (and a throwing marker+ # must not silently admit the package into the build set).+ line = re.sub(r"\\\s*$", "", line)+ if not line or line.startswith("#"):+ continue+ marker = ""+ m = re.search(r"\s;\s*(.+)$", line)+ if m:+ marker = m.group(1).strip()+ line = line[: m.start()]+ line = re.sub(r"\s*--.*$", "", line)+ if line.startswith("--") or not line:+ continue+ m = re.match(r"^([A-Za-z0-9._-]+)(\[[^]]*\])?([=<>~!^].*)?$", line)+ if m:+ out.append((m.group(1), m.group(3) or "", marker))+open(sys.argv[2], "w", encoding="utf-8").write(+ "\n".join(f"{name}\t{spec}\t{marker}" for name, spec, marker in out) + "\n"+)+PYEOF+[ -s "$RESOLVED" ] || fail "resolved dependency list is empty"++# [e] Marker-aware PyPI wheel-coverage probe: build set = resolved deps+# whose marker admits android AND that have no installable none-any wheel.+log "Probing PyPI wheel coverage (android markers)"+BUILD_SET="$WORK/build_set.txt"+python3 - "$RESOLVED" "$BUILD_SET" <<'PYEOF' || fail "PyPI wheel-coverage probe failed"+import json, re, sys, urllib.request+from concurrent.futures import ThreadPoolExecutor++# The TARGET environment the wheelhouse must satisfy: Termux's bionic+# python. TUR 3.11 reports sys.platform "linux" (the android value only+# arrived in 3.13), so markers keying on linux admit it -- and windows/+# darwin markers exclude it, which is the whole point.+TARGET_ENV = {+ "implementation_name": "cpython",+ "implementation_version": "3.11.15",+ "os_name": "posix",+ "platform_machine": "aarch64",+ "platform_release": "",+ "platform_system": "Linux",+ "platform_version": "",+ "python_full_version": "3.11.15",+ "python_version": "3.11",+ "sys_platform": "linux",+}++def locked_version(spec: str) -> str | None:+ m = re.search(r"==\s*([A-Za-z0-9._+!-]+)", spec or "")+ return m.group(1) if m else None++def marker_admits(marker: str) -> bool:+ if not marker:+ return True+ from packaging.markers import Marker+ try:+ return Marker(marker).evaluate(TARGET_ENV)+ except Exception:+ # An unevaluable marker is a build-set decision, not a silent+ # exclude: admit it so the wheel build surfaces the truth loudly.+ return True++entries = []+for line in open(sys.argv[1], encoding="utf-8"):+ if not line.strip():+ continue+ name, spec, marker = (line.split("\t", 2) + ["", ""])[:3]+ entries.append((name, spec, marker))++def probe(item):+ name, spec, marker = item+ if not marker_admits(marker):+ return name, None, None+ try:+ with urllib.request.urlopen(f"https://pypi.org/pypi/{name}/json", timeout=30) as r:+ d = json.load(r)+ locked = locked_version(spec) or d["info"]["version"]+ files = d["releases"].get(locked, [])+ # Coverage means INSTALLABLE on android/bionic, not "a wheel exists":+ # only py3-none-any wheels satisfy a package; anything else installs+ # nowhere on termux and must be built from sdist here.+ covered = any(+ f["filename"].endswith(".whl") and "-none-any.whl" in f["filename"]+ for f in files+ )+ return name, covered, None+ except Exception as exc: # noqa: BLE001 -- a probe miss means BUILD it+ return name, False, str(exc)++with ThreadPoolExecutor(max_workers=10) as ex:+ results = list(ex.map(probe, entries))++# Documented android build misses: upstream packages whose vendored+# toolchain excludes android and cannot be built without a fork.+# nemo-relay: worker-proto uses protoc-bin-vendored, which ships no+# android protoc and fails codegen regardless of PROTOC* env (verified+# live twice). The .deb ships without the relay exporter.+ANDROID_BUILD_MISSES = {+ "nemo-relay": "protoc-bin-vendored ships no android protoc (upstream)",+}++needs_build = []+excluded = 0+missed = []+for name, covered, err in results:+ if covered is None:+ excluded += 1+ continue+ if err is not None:+ print(f" probe miss {name}: {err} -> building from sdist", file=sys.stderr)+ if not covered:+ if name in ANDROID_BUILD_MISSES:+ missed.append((name, ANDROID_BUILD_MISSES[name]))+ continue+ needs_build.append(name)+open(sys.argv[2], "w", encoding="utf-8").write("\n".join(needs_build) + "\n")+print(f" {excluded} of {len(entries)} deps are marker-excluded for android")+for name, why in missed:+ print(f" documented build miss: {name} ({why})")+print(f" {len(needs_build)} of {len(entries) - excluded} applicable packages need sdist builds")+PYEOF+[ -s "$BUILD_SET" ] || fail "build set is empty -- nothing to build (probe bug?)"+fi++# [f] Container digest comes from pm/lock.json (termux-docker package).+REPO_ROOT="$(cd "$HERE/../.." && pwd)"+DIGEST="$(cd "$REPO_ROOT" && python3 -c 'import sys; sys.path.insert(0, "."); from pm.lock import termux_docker_digest; print(termux_docker_digest())')"+[ -n "$DIGEST" ] || fail "termux-docker digest missing from pm/lock.json"+[ -n "$DIGEST" ] || fail "termux-docker digest missing from pm/lock.json"+# The derived builder image (toolchain pre-baked) when CI provides it;+# the bare pinned base otherwise. Its tag IS this lock digest (short+# form), so a lock bump rolls the builder image with the base.+IMAGE="${TERMUX_BUILDER_IMAGE:-termux/termux-docker@$DIGEST}"++# [g] The build itself runs in the pinned container: the wheels must be+# bionic, and they are built with THE PAYLOAD'S OWN staged python (the+# exact TUR .deb pm staged from the lock), so the ABI matches the shipped+# interpreter by construction. The payload must be staged before this.+log "Building the wheelhouse inside the pinned container (payload ABI)"+PAYLOAD_ABS="$OUT_ABS"+[ -f "$PAYLOAD_ABS/python/data/data/com.termux/files/usr/bin/python3.11" ] \+ || fail "staged payload python missing -- run build_cpython.sh first (the wheelhouse builds with the payload interpreter)"+# The container mounts OUT_ABS at /out; translate the host-side work+# paths before crossing the boundary (host absolutes do not exist inside).+# The wheelhouse must be container-WRITABLE: /out is runner-owned, so+# pre-create the dir with open perms (the build writes wheels there).+mkdir -p "$OUT_ABS/wheelhouse"+chmod 0777 "$OUT_ABS/wheelhouse"++# The cache verdict was computed before [d]; on a hit the resolve, probe,+# and this container phase are all skipped (same flag guards each).+if [ "$WHEELHOUSE_CACHE_OK" -eq 1 ]; then+ :+else+ C_RESOLVED="/out/.work/resolved.txt"+ C_BUILD_SET="/out/.work/build_set.txt"+ C_WHEELHOUSE="/out/wheelhouse"+ # --user root: the build must create /bin/sh (autotools config.sub,+ # configure shebangs expect the standard path); termux binaries run+ # fine as root in the build container (no phone-uid semantics here).+ docker run --rm --platform linux/arm64 \+ --user root \+ --tmpfs /bin \+ -v "$REPO_ROOT:/repo" \+ -v "$OUT_ABS:/out" \+ "$IMAGE" bash /repo/scripts/termux/termux_build.sh \+ --in-container "$C_RESOLVED" "$C_BUILD_SET" "$C_WHEELHOUSE" "/out" \+ || fail "container wheelhouse build failed"+fi++# [h+] Stage the archived tag tree as the payload's app/ -- build_deb.sh+# assembles the .deb from payload/{python,node,app,venv,bin}.+rm -rf "$OUT_ABS/app"+cp -a "$WORK/tree" "$OUT_ABS/app"++# [h] Emit the manifest artifacts (host side: pure data over the results).+log "Emitting index.json, system-packages.txt, SHA256SUMS"+python3 - "$WHEELHOUSE" "$OUT_ABS" "$TAG" "$PLATFORM_TAG" "$PYTHON_ABI" <<'PYEOF' || fail "manifest emission failed"+import hashlib, json, subprocess, sys+from pathlib import Path++wheelhouse, out, tag, platform_tag, python_abi = sys.argv[1:6]+wheels = sorted(Path(wheelhouse).glob("*.whl"))+digests = {w.name: hashlib.sha256(w.read_bytes()).hexdigest() for w in wheels}+index = {+ "schemaVersion": 1,+ "tag": tag,+ "platformTag": platform_tag,+ "pythonAbi": python_abi,+ "wheels": [{"name": w.name, "sha256": digests[w.name]} for w in wheels],+}+Path(out, "index.json").write_text(json.dumps(index, indent=2) + "\n", encoding="utf-8")+try:+ syspkgs = subprocess.run(["dpkg-query", "-W", "-f", "${Package} ${Version}\n"],+ capture_output=True, text=True, check=False)+ Path(out, "system-packages.txt").write_text(syspkgs.stdout or "unavailable\n", encoding="utf-8")+except Exception:+ Path(out, "system-packages.txt").write_text("unavailable\n", encoding="utf-8")+with open(Path(out, "SHA256SUMS"), "w", encoding="utf-8", newline="\n") as f:+ for w in wheels:+ f.write(f"{digests[w.name]} {w.name}\n")+print(f" {len(wheels)} wheels indexed")+PYEOF++log "Wheelhouse complete: $WHEELHOUSE"diff --git a/tests/test_termux_retag_wheel.py b/tests/test_termux_retag_wheel.pynew file mode 100644index 00000000000..466dac4a0bd--- /dev/null+++ b/tests/test_termux_retag_wheel.py@@ -0,0 +1,142 @@+"""Behavior contracts for scripts/termux/retag_wheel.py (PEP 738 retagger).++Fixture wheels are tiny fake wheels built with stdlib zipfile -- no network,+no real native compilation. The contracts assert HOW the retagged wheel must+relate to the original (filename/WHEEL/RECORD agreement, valid RECORD hashes,+native .so presence), not snapshots of any real package.++Run: scripts/run_tests.sh tests/test_termux_retag_wheel.py+"""++from __future__ import annotations++import base64+import csv+import hashlib+import io+import sys+import zipfile+from pathlib import Path++import pytest++SCRIPTS_DIR = Path(__file__).resolve().parent.parent / "scripts" / "termux"+sys.path.insert(0, str(SCRIPTS_DIR))++import retag_wheel # noqa: E402++ANDROID_TAG = "android_24_arm64_v8a"+++def _record_hash(data: bytes) -> str:+ digest = hashlib.sha256(data).digest()+ return "sha256=" + base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")+++def _write_wheel(+ path: Path,+ distribution: str,+ version: str,+ platform_tag: str,+ *,+ metadata_version: str | None = None,+ include_so: bool = True,+) -> None:+ """Build a tiny fake wheel with the same shape the builder produces."""+ dist_info = f"{distribution}-{version}.dist-info"+ members: list[tuple[str, bytes]] = []+ if include_so:+ # A fake native extension -- retagging a pure wheel onto a platform+ # tag would be a lie, so fixtures default to carrying one.+ members.append((f"{distribution}/_native.cpython-314-aarch64-linux-gnu.so", b"\x7fELFfake"))+ members.append((f"{distribution}/__init__.py", b""))+ metadata_version = metadata_version or version+ members.append((f"{dist_info}/METADATA", f"Metadata-Version: 2.1\nName: {distribution}\nVersion: {metadata_version}\n".encode()))+ members.append((f"{dist_info}/WHEEL", f"Wheel-Version: 1.0\nRoot-Is-Purelib: false\nTag: py3-none-{platform_tag}\nGenerator: fixture\n".encode()))++ # RECORD with real hashes so the retagger's ZIP-integrity/consistency+ # checks exercise the true path.+ rows: list[list[str]] = []+ for name, data in members:+ rows.append([name, _record_hash(data), str(len(data))])+ rows.append([f"{dist_info}/RECORD", "", ""])+ buf = io.StringIO()+ csv.writer(buf, lineterminator="\n").writerows(rows)+ members.append((f"{dist_info}/RECORD", buf.getvalue().encode()))++ filename = f"{distribution}-{version}-py3-none-{platform_tag}.whl"+ with zipfile.ZipFile(path / filename, "w", zipfile.ZIP_DEFLATED) as zf:+ for name, data in members:+ zf.writestr(name, data)+++def _read_member(zf: zipfile.ZipFile, name: str) -> bytes:+ return zf.read(name)+++def _record_rows(zf: zipfile.ZipFile, dist_info: str) -> dict[str, tuple[str, str]]:+ text = zf.read(f"{dist_info}/RECORD").decode("utf-8")+ return {row[0]: (row[1], row[2]) for row in csv.reader(io.StringIO(text)) if row}+++def wheel(tmp_path: Path) -> Path:+ _write_wheel(tmp_path, "fakedep", "1.2.3", "linux_aarch64")+ return tmp_path / "fakedep-1.2.3-py3-none-linux_aarch64.whl"+++def test_filename_and_wheel_tags_rewritten_consistently(wheel: Path) -> None:+ new_path = Path(retag_wheel.retag_wheel(str(wheel), ANDROID_TAG))++ assert new_path.name == f"fakedep-1.2.3-py3-none-{ANDROID_TAG}.whl"+ assert not wheel.exists(), "the original wheel must be replaced, not left beside the new one"++ with zipfile.ZipFile(new_path) as zf:+ wheel_txt = zf.read("fakedep-1.2.3.dist-info/WHEEL").decode("utf-8")+ tag_lines = [l for l in wheel_txt.splitlines() if l.startswith("Tag:")]+ assert tag_lines == [f"Tag: py3-none-{ANDROID_TAG}"], wheel_txt+++def test_record_rows_valid_after_retag(wheel: Path) -> None:+ new_path = Path(retag_wheel.retag_wheel(str(wheel), ANDROID_TAG))++ with zipfile.ZipFile(new_path) as zf:+ rows = _record_rows(zf, "fakedep-1.2.3.dist-info")+ for member in zf.namelist():+ if member.endswith("/"):+ continue+ if member == "fakedep-1.2.3.dist-info/RECORD":+ # RECORD's own row is digest-less by spec; checked separately+ continue+ data = _read_member(zf, member)+ digest, size = rows[member]+ assert digest == _record_hash(data), f"RECORD hash stale for {member}"+ assert size == str(len(data)), f"RECORD size stale for {member}"+ record_row = rows["fakedep-1.2.3.dist-info/RECORD"]+ assert record_row == ("", ""), "RECORD's own row must be digest-less"+++def test_native_extension_presence_required(tmp_path: Path) -> None:+ _write_wheel(tmp_path, "puredist", "0.1.0", "linux_aarch64", include_so=False)+ pure = tmp_path / "puredist-0.1.0-py3-none-linux_aarch64.whl"+ with pytest.raises(retag_wheel.RetagError, match="native"):+ retag_wheel.retag_wheel(str(pure), ANDROID_TAG)+++def test_refuses_version_mismatch_between_filename_and_metadata(tmp_path: Path) -> None:+ # METADATA says 9.9.9 while the filename says 1.2.3 -- a lie the+ # retagger must refuse rather than launder.+ _write_wheel(tmp_path, "fakedep", "1.2.3", "linux_aarch64", metadata_version="9.9.9")+ lying = tmp_path / "fakedep-1.2.3-py3-none-linux_aarch64.whl"+ with pytest.raises(retag_wheel.RetagError):+ retag_wheel.retag_wheel(str(lying), ANDROID_TAG)+++def test_refuses_invalid_target_platform_tag(wheel: Path) -> None:+ with pytest.raises(retag_wheel.RetagError):+ retag_wheel.retag_wheel(str(wheel), "not_a_platform")+++def test_self_check_passes() -> None:+ # The built-in round-trip self-check is the builder's smoke gate.+ assert retag_wheel.self_check() == 0