The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(termux): complete the sealed CLI payload and verify installed startup
ethernet7606b014f56c
diff --git a/.github/workflows/desktop-bundled-release.yml b/.github/workflows/desktop-bundled-release.ymlindex 6b9c6f44f0b..a709bc76986 100644--- a/.github/workflows/desktop-bundled-release.yml+++ b/.github/workflows/desktop-bundled-release.yml@@ -71,6 +71,11 @@ on:description: 'Release tag to bundle (vX.Y.Z or vX.Y.0-canary.YYYYMMDDHHMMSS). Must exist on the repo.'required: truetype: string+ termux_only:+ description: 'Build and publish only the Termux package'+ required: false+ type: boolean+ default: falseupload_release:description: 'Upload artifacts to the R2 release bucket (staging + feeds)'required: false@@ -152,6 +157,7 @@ jobs:# Store submission) is gated on THIS job, never on mac/linux.build-win32:name: bundled ${{ matrix.target.label }}+ if: inputs.termux_only != trueneeds: validateruns-on: ${{ matrix.target.runner }}environment: release-signing@@ -777,7 +783,7 @@ jobs:publish-darwin-updater:name: Publish the macOS updater feed (disabled for now)needs: [validate, build-darwin]- if: inputs.upload_release == true+ if: inputs.upload_release == true && inputs.termux_only != trueruns-on: ubuntu-24.04timeout-minutes: 5steps:@@ -804,12 +810,11 @@ jobs:CLOUDFLARE_R2_BUCKET: ${{ vars.CLOUDFLARE_R2_BUCKET }}CLOUDFLARE_R2_PUBLIC_URL: ${{ vars.CLOUDFLARE_R2_PUBLIC_URL }}steps:- # Full checkout: build_deb.sh verifies the tag in-repo and assembles the- # .deb from the checkout's app/ tree — a sparse tree would ship a- # partial payload.+ # Use the admitted commit, not a tag that can move after validation.- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2with:- ref: ${{ inputs.tag }}+ ref: ${{ needs.validate.outputs.sha }}+ fetch-depth: 0fetch-tags: true- name: Resolve toolchain pins from pm/lock.json@@ -863,6 +868,9 @@ jobs:termux-build/payload/pythontermux-build/payload/nodetermux-build/payload/uv+ termux-build/payload/npm+ termux-build/payload/ffmpeg+ termux-build/payload/ripgreptermux-build/payload/runtime-libskey: termux-payload-${{ hashFiles('pm/lock.json', 'scripts/termux/build_cpython.sh', 'scripts/termux/build_node.sh', 'scripts/termux/build_uv.sh', 'scripts/termux/runtime_libs.json', 'scripts/termux/stage_runtime_libs.py') }}restore-keys: |@@ -892,6 +900,13 @@ jobs:run: bash scripts/termux/build_uv.sh termux-build/payload+ - name: Stage the remaining CLI runtime tools+ shell: bash+ run: |+ for tool in npm ffmpeg ripgrep; do+ bash scripts/termux/termux_pkg_build.sh "$tool" "$tool" termux-build/payload+ done+- name: Save the payload builds# Save regardless of the wheelhouse/deb phases' outcome: the staged# tool payload is only stale when the lock or a stager changes, and@@ -903,6 +918,9 @@ jobs:termux-build/payload/pythontermux-build/payload/nodetermux-build/payload/uv+ termux-build/payload/npm+ termux-build/payload/ffmpeg+ termux-build/payload/ripgreptermux-build/payload/runtime-libskey: termux-payload-${{ hashFiles('pm/lock.json', 'scripts/termux/build_cpython.sh', 'scripts/termux/build_node.sh', 'scripts/termux/build_uv.sh', 'scripts/termux/runtime_libs.json', 'scripts/termux/stage_runtime_libs.py') }}@@ -937,7 +955,8 @@ jobs:termux-build/payload/index.jsontermux-build/payload/SHA256SUMStermux-build/payload/.work/resolved.txt- key: termux-wheelhouse-${{ hashFiles('uv.lock', 'scripts/termux/build_wheels.py', 'scripts/termux/termux_build.sh') }}+ termux-build/payload/.work/build_set.txt+ key: termux-wheelhouse-${{ hashFiles('uv.lock', 'pyproject.toml', 'pm/lock.json', 'scripts/termux/runtime_libs.json', 'scripts/termux/build_config.sh', 'scripts/termux/build_wheels.py', 'scripts/termux/termux_build.sh', 'scripts/termux/retag_wheel.py', 'scripts/termux/python_linkage.py', 'scripts/termux/wheelhouse_cache.py', 'scripts/termux/termux-builder.Dockerfile') }}restore-keys: |termux-wheelhouse-@@ -954,9 +973,8 @@ jobs:--out termux-build/payload- name: Save the wheelhouse- # Save even when the deb assembly/validation later fails: the gates- # have already proven the wheels by this point.- if: always()+ # Only proven wheels enter the cache. Saving before deb assembly+ # preserves them if a later packaging step fails.uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0with:path: |@@ -964,7 +982,8 @@ jobs:termux-build/payload/index.jsontermux-build/payload/SHA256SUMStermux-build/payload/.work/resolved.txt- key: termux-wheelhouse-${{ hashFiles('uv.lock', 'scripts/termux/build_wheels.py', 'scripts/termux/termux_build.sh') }}+ termux-build/payload/.work/build_set.txt+ key: termux-wheelhouse-${{ hashFiles('uv.lock', 'pyproject.toml', 'pm/lock.json', 'scripts/termux/runtime_libs.json', 'scripts/termux/build_config.sh', 'scripts/termux/build_wheels.py', 'scripts/termux/termux_build.sh', 'scripts/termux/retag_wheel.py', 'scripts/termux/python_linkage.py', 'scripts/termux/wheelhouse_cache.py', 'scripts/termux/termux-builder.Dockerfile') }}- name: Build the TUI bundle for the debshell: bash@@ -1040,8 +1059,16 @@ jobs:# cwd and a bare `node scripts/r2-release.mjs` would ENOENT.R2="$GITHUB_WORKSPACE/scripts/r2-release.mjs"cd termux-build/apt- for f in **/*; do- [ -f "$f" ] || continue+ files=(pool/**/*.deb key.asc+ "dists/hermes-$CHANNEL/main/binary-aarch64/Packages"+ "dists/hermes-$CHANNEL/main/binary-aarch64/Packages.gz"+ "dists/hermes-$CHANNEL/Release"+ "dists/hermes-$CHANNEL/Release.gpg"+ "dists/hermes-$CHANNEL/InRelease")+ # APT reads InRelease first. Publish it only after every referenced+ # index and package has been uploaded and read back successfully.+ for f in "${files[@]}"; do+ test -f "$f"node "$R2" put \--tag "$HERMES_PAYLOAD_TAG" \--key "releases/termux/$CHANNEL/$f" \@@ -1050,7 +1077,7 @@ jobs:donebuilds-pending:name: Mark the builds table as in progress- if: inputs.upload_release == true+ if: inputs.upload_release == true && inputs.termux_only != trueruns-on: ubuntu-24.04steps:- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2diff --git a/.github/workflows/termux-verify.yml b/.github/workflows/termux-verify.ymlindex 8f2df7f1e02..f1e38f540c2 100644--- a/.github/workflows/termux-verify.yml+++ b/.github/workflows/termux-verify.yml@@ -39,7 +39,12 @@ jobs:uv export --frozen --extra dev --no-emit-project --no-hashes -o "$RUNNER_TEMP/requirements.txt"uv pip install --python .venv/bin/python -r "$RUNNER_TEMP/requirements.txt"- name: Run the native linker and wheel contracts- run: bash scripts/run_tests.sh -j 2 tests/test_termux_python_linkage.py tests/test_termux_retag_wheel.py+ run: |+ bash scripts/run_tests.sh -j 2 \+ tests/test_termux_python_linkage.py tests/test_termux_retag_wheel.py \+ tests/test_termux_wheelhouse_cache.py tests/test_termux_runtime_libs.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.pynative-linkage:name: Reproduce and verify bionic Python linkagediff --git a/pm/ensure.py b/pm/ensure.pyindex cba75fa1319..94f9d3705c5 100644--- a/pm/ensure.py+++ b/pm/ensure.py@@ -3,6 +3,7 @@ and hand back its composed environment."""from __future__ import annotations+import jsonimport loggingimport shutilfrom pathlib import Path@@ -137,6 +138,18 @@ def _remove_entry(store: Store, entry_name: str) -> None:time.sleep(0.2 * (attempt + 1))+def _entry_proven(entry: Path, entry_name: str, previous: Optional[dict], artifacts: list) -> bool:+ """Does a recorded fact PROVE the published entry's bytes were realized+ from exactly the pin the lock holds now? It must name this entry, be+ recorded against these artifact digests, and the realized tree digest+ must still match the bytes on disk (tree_digest, as adopt() checks)."""+ if not previous or previous.get("entry") != entry_name:+ return False+ if (previous.get("artifacts") or []) != [a["sha256"] for a in artifacts]:+ return False+ return previous.get("digest") == tree_digest(entry)++def _install(package: Package,lockfile: Lockfile,@@ -165,8 +178,15 @@ def _install():returnentry = store.entry(entry_name)- _cond = store.published(entry_name) and package.verify(entry, target) == ""- if _cond:+ # Removal is a REPAIR decision, not housekeeping. verify() returns+ # '' on success; the entry is removed only when it fails+ # verification, or when no fact proves it was realized from the pin+ # the lock holds now (missing facts, or a same-version repin — the+ # recorded artifacts no longer match). A proven entry is kept.+ proven = _entry_proven(entry, entry_name, facts.get(package.name), artifacts)+ if store.published(entry_name) and (+ package.verify(entry, target) != "" or not proven+ ):_remove_entry(store, entry_name)if not store.published(entry_name):if not artifacts:@@ -282,10 +302,25 @@ def stage_only(name: str, target: str, progress=None) -> "Path":return store.root / package.store_entry(version, target)artifacts = lockfile.artifacts(package.name, target)entry_name = package.store_entry(version, target)+ # The stage pin marker (same identity shape as a fact's recorded+ # artifacts: target + artifact digests) lets stage_only honor a+ # same-version hash repin without any host-side facts: the entry+ # belongs to ANOTHER machine, so the marker travels inside the entry.+ pin = json.dumps({"target": target, "sha256": [a["sha256"] for a in artifacts]})with store.install_lock():entry = store.entry(entry_name)- if store.published(entry_name) and not package.verify(entry, target):- shutil.rmtree(entry, ignore_errors=True)+ if store.published(entry_name):+ marker = entry / ".pm-stage-pin.json"+ try:+ recorded = marker.read_text(encoding="utf-8")+ except OSError:+ recorded = None+ # verify() returns '' on success — a non-empty reason is the+ # invalid case. A valid entry is NEVER deleted; an invalid one+ # or one staged from a different pin (same version, repinned+ # hash, or pre-marker) is rebuilt.+ if package.verify(entry, target) or recorded != pin:+ _remove_entry(store, entry_name)if not store.published(entry_name):if not artifacts:raise InstallError(@@ -307,6 +342,10 @@ def stage_only(name: str, target: str, progress=None) -> "Path":package.unpack(archive, extra, target)merge_tree(extra, staged)package.stage(store, staged, version, target)+ reason = package.verify(staged, target)+ if reason:+ raise InstallError(package.name, f"staged entry failed verification: {reason}")+ (staged / ".pm-stage-pin.json").write_text(pin, encoding="utf-8")store.publish(staged, entry_name)reason = package.verify(store.entry(entry_name), target)if reason:diff --git a/pm/lock.json b/pm/lock.jsonindex 6a805750a88..b2ad24da9ca 100644--- a/pm/lock.json+++ b/pm/lock.json@@ -110,6 +110,10 @@"sha256": "92cff3dec20d996bb5b8a918b156b64301338e7c28046053c82d0935cf7c6eb2","url": "https://ffmpeg.martin-riedl.de/download/linux/arm64/1787072884_9.0.1/ffmpeg.zip"},+ "linux-arm64-bionic": {+ "sha256": "1ec37f4f092521cb785e0ccfa2d82cc4a79ec8d2a4864f5eefc50a314f2d5dec",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/f/ffmpeg/ffmpeg_8.1.2-5_aarch64.deb"+ },"linux-x64": {"sha256": "18bec7d5c2ab3b24d277466b758394e109b0479133b98d155c5540ed3013fa74","url": "https://ffmpeg.martin-riedl.de/download/linux/amd64/1787074600_9.0.1/ffmpeg.zip"@@ -308,8 +312,8 @@"url": "https://github.com/astral-sh/python-build-standalone/releases/download/20260814/cpython-3.11.16+20260814-aarch64-unknown-linux-gnu-install_only.tar.gz"},"linux-arm64-bionic": {- "sha256": "b927d1cbeacffb426d52e4860650caf9afd1945f85eaece26f37ae3327d5fa7c",- "url": "https://tur.kcubeterm.com/pool/tur/python3.11_3.11.15_aarch64.deb"+ "sha256": "61a8df1dfee53de364757aa751faac033725262a4be04f086c3e3fedbe38991d",+ "url": "https://tur.kcubeterm.com/pool/tur/python3.11_3.11.16_aarch64.deb"},"linux-x64": {"sha256": "33994fad90145ba559ebbe8a18d69fa7e56653502f7ba14ba07199b52cde3775",@@ -340,6 +344,10 @@"sha256": "800b1e7206afe799dfb5a6901f23147cfaabe0e52210538100f61e86e1740915","url": "https://github.com/BurntSushi/ripgrep/releases/download/15.2.0/ripgrep-15.2.0-aarch64-unknown-linux-musl.tar.gz"},+ "linux-arm64-bionic": {+ "sha256": "800b1e7206afe799dfb5a6901f23147cfaabe0e52210538100f61e86e1740915",+ "url": "https://github.com/BurntSushi/ripgrep/releases/download/15.2.0/ripgrep-15.2.0-aarch64-unknown-linux-musl.tar.gz"+ },"linux-x64": {"sha256": "33e15bcf1624b25cdd2a55813a47a2f95dbe126268203e76aa6a585d1e7b149c","url": "https://github.com/BurntSushi/ripgrep/releases/download/15.2.0/ripgrep-15.2.0-x86_64-unknown-linux-musl.tar.gz"diff --git a/pm/package.py b/pm/package.pyindex c5007abb3e8..94870157443 100644--- a/pm/package.py+++ b/pm/package.py@@ -219,8 +219,17 @@ class DebPackage(Package):import ioimport posixpathimport shutil+ import stat as stat_modimport tarfile+ real_staged = os.path.realpath(staged)++ def _contained(p: Path) -> bool:+ """True when p's REAL location (following any planted symlink+ ancestors) stays inside the staged tree."""+ real = os.path.realpath(p)+ return real == real_staged or real.startswith(real_staged + os.sep)+deferred_links = []with tarfile.open(fileobj=io.BytesIO(payload)) as tf:for member in tf.getmembers():@@ -231,14 +240,24 @@ class DebPackage(Package):if not parts:continue # the "./" root membertarget = staged.joinpath(*parts)+ if not _contained(target):+ raise InstallError(self.name, f"member escapes staged tree: {member.name}")if member.isdir():target.mkdir(parents=True, exist_ok=True)continueif member.issym():+ if PurePosixPath(member.linkname).is_absolute() or Path(member.linkname).is_absolute():+ raise InstallError(+ self.name,+ f"absolute symlink target {member.linkname!r} "+ f"in {member.name}",+ )link_dir = "/".join(parts[:-1])resolved = posixpath.normpath(posixpath.join(link_dir, member.linkname))if resolved == ".." or resolved.startswith("../"):raise InstallError(self.name, f"symlink escapes root: {member.name}")+ if not _contained(target.parent / member.linkname):+ raise InstallError(self.name, f"symlink escapes staged tree: {member.name}")target.parent.mkdir(parents=True, exist_ok=True)if target.exists() or target.is_symlink():target.unlink()@@ -254,6 +273,12 @@ class DebPackage(Package):if not member.isfile():raise InstallError(self.name, f"unsupported member type: {member.name}")target.parent.mkdir(parents=True, exist_ok=True)+ if not _contained(target.parent):+ raise InstallError(+ self.name,+ f"member {member.name} resolves outside the staged tree "+ "through a symlinked ancestor",+ )extracted = tf.extractfile(member)if extracted is None:raise InstallError(self.name, f"cannot read member {member.name}")@@ -264,6 +289,11 @@ class DebPackage(Package):except OSError:passfor _linkname, target, resolved_path in deferred_links:+ if not _contained(resolved_path):+ raise InstallError(+ self.name,+ f"symlink {target.name} resolves outside the staged tree",+ )if not (target.exists() or target.is_symlink()) and resolved_path.is_file():shutil.copy2(resolved_path, target)# Termux debs carry owner-only modes across the whole tree (700 on@@ -273,14 +303,20 @@ class DebPackage(Package):# linker cannot read a 700 lib, the interpreter cannot read a 600# encoding module. Normalize EVERYTHING: a+r on all regular files,# a+X on anything that was executable. The deb's bytes are pinned- # by digest; modes are not part of the pin.+ # by digest; modes are not part of the pin. Symlinks are skipped:+ # chmod through one would follow it outside the staged tree.for root, dirs, files in os.walk(staged):+ dirs[:] = [d for d in dirs if not (Path(root) / d).is_symlink()]for name in files:f = Path(root) / nametry:- mode = f.stat().st_mode+ mode = f.lstat().st_modeexcept OSError:continue+ if stat_mod.S_ISLNK(mode):+ continue+ if not _contained(f):+ continuewanted = 0o644 | (0o111 if mode & 0o111 else 0)try:f.chmod(wanted)@@ -319,7 +355,7 @@ def machine_matches_binary(binary: Path, target: str) -> Optional[bool]:which is not a mismatch."""import struct- arch = target.rsplit("-", 1)[-1]+ arch = target.split("-")[1]try:with open(binary, "rb") as f:head = f.read(64)diff --git a/pm/packages.py b/pm/packages.pyindex f0219289cd4..bf01ca5d934 100644--- a/pm/packages.py+++ b/pm/packages.py@@ -128,9 +128,16 @@ class _BionicDebArm:else:BinaryPackage.unpack(self, archive, staged, target)+ def stage(self, store: Store, staged: Path, version: str, target: str) -> None:+ if target != "linux-arm64-bionic":+ BinaryPackage.stage(self, store, staged, version, target)+def binary(self, entry: Path, target: str) -> Optional[Path]:if target == "linux-arm64-bionic":- return None # bionic binaries cannot exec on the staging host+ # File evidence, not exec: the staged .deb's main binary.+ # Cross-target verify() never probes it; consumers (env PATH,+ # bundle layout) need the real path.+ return entry / self.prefix_rel / self.main_rel(target)return BinaryPackage.binary(self, entry, target)def verify(self, entry: Path, target: str) -> str:@@ -167,13 +174,6 @@ class Uv(_BionicDebArm, BinaryPackage, DebPackage):ext = "zip" if target.startswith("win32") else "tar.gz"return f"https://github.com/astral-sh/uv/releases/download/{version}/uv-{triple}.{ext}"- def env(self, entry: Path, target: str) -> dict:- """The bionic arm exposes uv through PATH composition -- the same- mechanism every other pm package uses. No system PATH install."""- if target == "linux-arm64-bionic":- return {"PATH": str(entry / self.prefix_rel / "bin")}- return BinaryPackage.env(self, entry, target)-def latest_versions(self, target: str, locked=None) -> list[str]:return github_release_tags("astral-sh/uv")@@ -611,6 +611,28 @@ class Npm(BinaryPackage):bundled npm instead. --offline pins the bytes to the verifiedtarball; --ignore-scripts + a sanitized env keep user npm/nodeconfig out of the staging."""+ if target == "linux-arm64-bionic":+ from pm.store import extract++ unpacked = staged / ".unpacked"+ extract(archive, unpacked)+ package = unpacked / "package"+ lib = staged / "lib/node_modules/npm"+ lib.parent.mkdir(parents=True, exist_ok=True)+ package.rename(lib)+ unpacked.rmdir()+ bindir = staged / "bin"+ bindir.mkdir()+ for name in ("npm", "npx"):+ wrapper = bindir / name+ wrapper.write_text(+ "#!/data/data/com.termux/files/usr/bin/sh\n"+ 'here="$(cd "$(dirname "$0")" && pwd)"\n'+ f'exec node "$here/../lib/node_modules/npm/bin/{name}-cli.js" "$@"\n',+ encoding="utf-8",+ )+ wrapper.chmod(0o755)+ returnfrom pm.ensure import _facts, _storefrom pm.registry import get_package@@ -735,7 +757,7 @@ class Gh(BinaryPackage):@register-class Ffmpeg(BinaryPackage):+class Ffmpeg(_BionicDebArm, BinaryPackage, DebPackage):"""Static ffmpeg. GPLv3 builds; always bundled.optional=False: ffmpeg is a required runtime tool. Sealed bundles shipit baked into the payload (post_update skips provisioning sealed@@ -746,7 +768,12 @@ class Ffmpeg(BinaryPackage):no ffprobe)."""name = "ffmpeg"+ deb_package = "ffmpeg"optional = False++ def main_rel(self, target: str) -> str:+ return "bin/ffmpeg"+# The posix (martin-riedl) and win32 (BtbN) build streams have no shared# release cadence — they drift in PATCH. The lockfile version label is# major.minor; each target's exact patch lives in its artifact urls.@@ -762,6 +789,8 @@ class Ffmpeg(BinaryPackage):probe_args = ["-version"]def fetch_url(self, version: str, target: str) -> str:+ if target == "linux-arm64-bionic":+ return f"https://packages.termux.dev/apt/termux-main/pool/main/f/ffmpeg/ffmpeg_{version}_aarch64.deb"osname, arch = target.split("-")if osname == "win32":# BtbN: the newest autobuild tag whose assets carry this version.@@ -810,7 +839,14 @@ class Ripgrep(BinaryPackage):name = "ripgrep"binary_rel = {"win32": "rg.exe", "posix": "rg"}+ def verify(self, entry: Path, target: str) -> str:+ if target == "linux-arm64-bionic":+ return Package.verify(self, entry, target)+ return super().verify(entry, target)+def fetch_url(self, version: str, target: str) -> str:+ if target == "linux-arm64-bionic":+ target = "linux-arm64" # This upstream artifact is a static musl executable.triple = _RUST_TRIPLE[target].replace("-unknown-linux-gnu", "-unknown-linux-musl")ext = "zip" if target.startswith("win32") else "tar.gz"return (diff --git a/scripts/termux/build_deb.sh b/scripts/termux/build_deb.shindex 96a194ad7b5..d51f954870c 100644--- a/scripts/termux/build_deb.sh+++ b/scripts/termux/build_deb.sh@@ -28,8 +28,7 @@ HERE="$(cd "$(dirname "$0")" && pwd)"# from the single lock beside every other third-party artifact pin.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 "failed to read the termux-docker digest from pm/lock.json"-[ -n "$DIGEST" ] || fail "termux-docker digest missing from pm/lock.json"+[ -n "$DIGEST" ] || { printf 'termux-docker digest missing from pm/lock.json\n' >&2; exit 1; }# 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.@@ -68,7 +67,7 @@ OUT_ABS="$(mkdir -p "$OUT" && cd "$OUT" && pwd)"# captured ONCE here and reused for the install stamp below.COMMIT="$(git -C "$REPO_ABS" rev-parse --verify "refs/tags/$TAG^{commit}")" \|| fail "tag $TAG not found in $REPO_ABS"-for d in python node app wheelhouse; do+for d in python node uv npm ffmpeg ripgrep runtime-libs app wheelhouse; do[ -d "$PAYLOAD_ABS/$d" ] || fail "payload missing $d/ -- run termux_build.sh + build_cpython.sh + build_node.sh first"donePYBIN_REL="data/data/com.termux/files/usr/bin/python3.11"@@ -125,10 +124,10 @@ chmod 0777 "$PAYLOAD_ABS/venv"# absolute paths (interpreter symlink, pyvenv.cfg) that must be correct# on-device from birth -- a /payload alias would bake container paths in.docker run --rm --platform linux/arm64 \- --user root \- -v "$PAYLOAD_ABS/python:/data/data/com.termux/files/usr/lib/hermes-agent/python" \- -v "$PAYLOAD_ABS/node:/data/data/com.termux/files/usr/lib/hermes-agent/node" \- -v "$PAYLOAD_ABS/uv:/data/data/com.termux/files/usr/lib/hermes-agent/uv" \+ --user root --network none \+ -v "$PAYLOAD_ABS/python:/data/data/com.termux/files/usr/lib/hermes-agent/tools/python" \+ -v "$PAYLOAD_ABS/node:/data/data/com.termux/files/usr/lib/hermes-agent/tools/node" \+ -v "$PAYLOAD_ABS/uv:/data/data/com.termux/files/usr/lib/hermes-agent/tools/uv" \-v "$PAYLOAD_ABS/runtime-libs:/data/data/com.termux/files/usr/lib/hermes-agent/runtime-libs" \-v "$PAYLOAD_ABS/wheelhouse:/data/data/com.termux/files/usr/lib/hermes-agent/wheelhouse" \-v "$PAYLOAD_ABS/.work:/data/data/com.termux/files/usr/lib/hermes-agent/.work" \@@ -140,12 +139,12 @@ docker run --rm --platform linux/arm64 \# The staged binary is dynamically linked against its OWN tree lib;# the container linker needs to be told where it lives (same fix as# the wheelhouse container half).- export LD_LIBRARY_PATH="$PREFIX/lib/hermes-agent/python$PREFIX/lib:$PREFIX/lib/hermes-agent/node$PREFIX/lib:$PREFIX/lib/hermes-agent/runtime-libs/lib$PREFIX/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"+ export LD_LIBRARY_PATH="$PREFIX/lib/hermes-agent/tools/python$PREFIX/lib:$PREFIX/lib/hermes-agent/tools/node$PREFIX/lib:$PREFIX/lib/hermes-agent/runtime-libs/lib:$PREFIX/lib"# The staged tree is mounted at its REAL $PREFIX path so the venv# recorded absolute paths are correct on-device from birth.mkdir -p "$PREFIX" 2>/dev/null || true- PY="$PREFIX/lib/hermes-agent/python$PREFIX/bin/python3.11"- UV="$PREFIX/lib/hermes-agent/uv$PREFIX/bin/uv"+ PY="$PREFIX/lib/hermes-agent/tools/python$PREFIX/bin/python3.11"+ UV="$PREFIX/lib/hermes-agent/tools/uv$PREFIX/bin/uv"# Desktop payload canon: the venv holds the DEPENDENCY tree only;# the app runs from its own directory via PYTHONPATH (the wheel# build is deliberately blocked in setup.py -- Hermes is not a@@ -154,12 +153,12 @@ docker run --rm --platform linux/arm64 \# hermes-agent) so every absolute path the venv records --# interpreter symlink, pyvenv.cfg home -- is correct after# dpkg installs the tree to exactly that location.- "$UV" venv --python "$PY" --seed "$PREFIX/lib/hermes-agent/venv"+ "$UV" venv --python "$PY" "$PREFIX/lib/hermes-agent/venv"# The dep graph with markers intact (the installer evaluates# them on bionic); documented android build misses skipped --# nemo-relay is the only casualty (the relay exporter)."$UV" pip install --python "$PREFIX/lib/hermes-agent/venv/bin/python" \- --no-index --find-links "$PREFIX/lib/hermes-agent/wheelhouse" \+ --offline --no-index --only-binary :all: --find-links "$PREFIX/lib/hermes-agent/wheelhouse" \-r "$PREFIX/lib/hermes-agent/.work/resolved-reqs.txt""$UV" pip check --python "$PREFIX/lib/hermes-agent/venv/bin/python"' || fail "venv assembly failed inside the container (offline wheelhouse install)"@@ -169,54 +168,9 @@ docker run --rm --platform linux/arm64 \# to route hermes update -> pkg upgrade remediation.printf 'apt\n' > "$PAYLOAD_ABS/app/.install_method"-# [3] Trampolines: POSIX sh, resolve their own dir, dispatch on the bundled-# python. Installed under $PREFIX/lib/hermes-agent/bin; ../python is a sibling.+# [3] Entry functions come from the archived project's script declarations.log "Writing trampolines"-mkdir -p "$PAYLOAD_ABS/bin"-# One trampoline shape, three entrypoints: the bodies are identical-# except the exec'd module. Emit the QUOTED heredoc once with a-# placeholder (quoting keeps every $var literal in the output file)-# and sed the module in per entrypoint: adding an entrypoint is a-# word in MODULES, not a fourth heredoc.-MODULES="hermes:hermes_cli.main hermes-agent:hermes_cli.run_agent hermes-acp:hermes_cli.acp"-for spec in $MODULES; do- name="${spec%%:*}"- mod="${spec#*:}"- tramp="$PAYLOAD_ABS/bin/$name"- cat > "$tramp" <<'EOF'-#!/data/data/com.termux/files/usr/bin/sh-# invoked via the $PREFIX/bin symlink: resolve to the real file so-# Termux always exports PREFIX; hard fallback for exotic shells.-PREFIX="${PREFIX:-/data/data/com.termux/files/usr}"-self="${0}"-while [ -L "$self" ]; do- tgt="$(readlink "$self")"- case "$tgt" in- /*) self="$tgt" ;;- *) self="$(dirname "$self")/$tgt" ;;- esac-done-self_dir="$(cd "$(dirname "$self")" && pwd)"-# The bundled interpreter links its OWN libpython: put the payload-# lib dirs on the linker path (the image does not rpath them).-LD_LIBRARY_PATH="$self_dir/../python$PREFIX/lib:$self_dir/../node$PREFIX/lib:$self_dir/../runtime-libs/lib:$PREFIX/lib" \-export LD_LIBRARY_PATH-# Desktop canon: deps live in the venv, the app runs from its own-# directory -- put it on PYTHONPATH for the interpreter.-PYTHONPATH="$self_dir/../app" \-exec "$self_dir/../venv/bin/python" -m __HERMES_MODULE__ "$@"-export PYTHONPATH-# The prebuilt TUI bundle ships inside the deb: hand its launchers-# the payload node (HERMES_NODE) and this venv (HERMES_PYTHON) so they-# never fall back to PATH lookups the phone cannot satisfy.-HERMES_NODE="$self_dir/../node$PREFIX/bin/node"-HERMES_PYTHON="$self_dir/../venv/bin/python"-export HERMES_NODE HERMES_PYTHON-EOF- sed -i "s/__HERMES_MODULE__/$mod/" "$tramp"-done--chmod 755 "$PAYLOAD_ABS/bin/hermes" "$PAYLOAD_ABS/bin/hermes-agent" "$PAYLOAD_ABS/bin/hermes-acp"+python3 "$HERE/launchers.py" --payload "$PAYLOAD_ABS"# [4] Install stamp: provenance for the steward contract (distribution# apt-termux -> update/uninstall refuse with pkg remediation). Written by the@@ -243,32 +197,14 @@ rm -rf "$STAGE"# dpkg try to create /lib and fail on the read-only root.ROOT_IN_DEB=data/data/com.termux/files/usrDEST="$STAGE/$ROOT_IN_DEB/lib/hermes-agent"-mkdir -p "$STAGE/DEBIAN" "$DEST"-cp -a "$PAYLOAD_ABS/python" "$PAYLOAD_ABS/node" "$PAYLOAD_ABS/runtime-libs" "$PAYLOAD_ABS/app" "$PAYLOAD_ABS/venv" "$PAYLOAD_ABS/bin" "$DEST/"+mkdir -p "$STAGE/DEBIAN" "$DEST/tools"+for tool in python node uv npm ffmpeg ripgrep; do+ cp -a "$PAYLOAD_ABS/$tool" "$DEST/tools/"+done+cp -a "$PAYLOAD_ABS/runtime-libs" "$PAYLOAD_ABS/app" "$PAYLOAD_ABS/venv" "$PAYLOAD_ABS/bin" "$DEST/"+python3 "$HERE/payload_facts.py" "$DEST" "$PAYLOAD_ABS/.work/build_set.txt"-# postinst/prerm: manage the ONE leak, $PREFIX/bin/hermes, idempotently.-cat > "$STAGE/DEBIAN/postinst" <<'EOF'-#!/data/data/com.termux/files/usr/bin/sh-# Ensure $PREFIX/bin/hermes -> lib/hermes-agent/bin/hermes (idempotent).-LINK="$PREFIX/bin/hermes"-TARGET="../lib/hermes-agent/bin/hermes"-mkdir -p "$PREFIX/bin"-# Atomic: ln either creates the link or fails (EEXIST); never a-# check-then-create race. A pre-existing link is fine; any other ln failure-# is a loud nonzero exit, not a swallowed one.-ln -s "$TARGET" "$LINK" 2>/dev/null || [ -L "$LINK" ]-exit 0-EOF-cat > "$STAGE/DEBIAN/prerm" <<'EOF'-#!/data/data/com.termux/files/usr/bin/sh-# Remove $PREFIX/bin/hermes if it points at us (never clobber a foreign file).-LINK="$PREFIX/bin/hermes"-if [ -L "$LINK" ] && [ "$(readlink "$LINK")" = "../lib/hermes-agent/bin/hermes" ]; then- rm -f "$LINK"-fi-exit 0-EOF-chmod 755 "$STAGE/DEBIAN/postinst" "$STAGE/DEBIAN/prerm"+python3 "$HERE/launchers.py" --payload "$DEST" --control "$STAGE/DEBIAN"cat > "$STAGE/DEBIAN/control" <<EOFPackage: $PKG@@ -285,77 +221,18 @@ EOFlog "Validating in a fresh pinned termux-docker container"DEB="$OUT_ABS/${PKG}_${DEB_VERSION}_aarch64.deb"rm -f "$DEB"-# -Zxz: uniform xz compression for data AND control. The apt stager- dpkg-deb --build -Zxz --root-owner-group "$STAGE" "$DEB" || fail "dpkg-deb --build failed"+# Use xz for both archive members so Termux dpkg can extract the package.+dpkg-deb --build -Zxz --root-owner-group "$STAGE" "$DEB" || fail "dpkg-deb --build failed"rm -rf "$STAGE"[ -f "$DEB" ] || fail "dpkg-deb did not produce $DEB"-VD="$OUT_ABS/.deb-validate"-rm -rf "$VD"; mkdir -p "$VD"-cat > "$VD/check.sh" <<"CHECK"-set -eu-export PATH="$PREFIX/bin:$PATH"-# termux patched dpkg ALWAYS chroots maintscripts into the instdir;-# chroot(2) is EPERM inside this container even under --privileged-# (a runner-docker artifact -- real devices run maintscripts natively).-# So validate the real artifacts without dpkg script-wrapping:-# real payload extraction, real postinst, real trampolines.-dpkg-deb -I /tmp/pkg.deb | grep -q "Package: hermes-agent"-mkdir -p "$PREFIX/tmp/deb-x"-dpkg-deb -x /tmp/pkg.deb "$PREFIX/tmp/deb-x"-# Layout contract: the payload must sit exactly at the on-device-# path (android-fs-rooted) so a real-device dpkg -i extracts it-# into the writable /data/data region without touching /.-XROOT="$PREFIX/tmp/deb-x/data/data/com.termux/files/usr"-[ -d "$XROOT/lib/hermes-agent" ] || { echo "FAIL: deb payload not staged at data/data/com.termux/files/usr"; exit 1; }-cp -a "$XROOT/." "$PREFIX/"-dpkg-deb -e /tmp/pkg.deb "$PREFIX/tmp/ctrl"-test -x "$PREFIX/lib/hermes-agent/bin/hermes"-sh "$PREFIX/tmp/ctrl/postinst"-test -L "$PREFIX/bin/hermes"-echo "--- hermes --version ---"-"$PREFIX/bin/hermes" --version-# C-extension gate: every stdlib module that dlopens a runtime lib must-# import. This is the bug class the first real-device install hit-# (ctypes -> libffi.so): catch a missing payload lib BEFORE shipping.-echo "--- python C-extension imports ---"-LD_LIBRARY_PATH="$PREFIX/lib/hermes-agent/python$PREFIX/lib:$PREFIX/lib/hermes-agent/node$PREFIX/lib:$PREFIX/lib/hermes-agent/runtime-libs/lib" \-PYTHONPATH="$PREFIX/lib/hermes-agent/app" \-"$PREFIX/lib/hermes-agent/venv/bin/python" -c 'import ctypes, ssl, sqlite3, bz2, lzma, zlib, hashlib, readline; print("C extensions OK")'-echo "--- bundled node ---"-LD_LIBRARY_PATH="$PREFIX/lib/hermes-agent/runtime-libs/lib" \-"$PREFIX/lib/hermes-agent/node$PREFIX/bin/node" --version-# The deb ships the prebuilt TUI: the bundle must be present in the-# installed tree and parseable by the payload node (hermes --tui runs-# it directly; there is no npm on-device to rebuild it).-TUI="$PREFIX/lib/hermes-agent/app/hermes_cli/tui_dist/entry.js"-test -f "$TUI" || { echo "FAIL: prebuilt TUI bundle missing from the deb"; exit 1; }-LD_LIBRARY_PATH="$PREFIX/lib/hermes-agent/runtime-libs/lib" \-"$PREFIX/lib/hermes-agent/node$PREFIX/bin/node" --check "$TUI"-echo "--- install method (must be apt) ---"-LD_LIBRARY_PATH="$PREFIX/lib/hermes-agent/python$PREFIX/lib:$PREFIX/lib/hermes-agent/node$PREFIX/lib:$PREFIX/lib/hermes-agent/runtime-libs/lib" \-PYTHONPATH="$PREFIX/lib/hermes-agent/app" "$PREFIX/lib/hermes-agent/venv/bin/python" -c 'import hermes_cli.config as c; m = c.detect_install_method(); print("install method:", m); exit(0 if m == "apt" else 1)'-echo "--- hermes update (must refuse with pkg remediation) ---"-set +e-UPD_OUT="$("$PREFIX/bin/hermes" update 2>&1)"-RC=$?-set -e-echo "$UPD_OUT"-[ "$RC" -ne 0 ] || { echo "FAIL: hermes update exited 0 -- it must refuse"; exit 1; }-echo "$UPD_OUT" | grep -q "pkg upgrade hermes-agent" ||- { echo "FAIL: refusal does not mention pkg upgrade hermes-agent"; exit 1; }-echo "VALIDATION OK"-CHECK-# The validation must run the BARE pinned base, never the builder image:-# the builder carries the whole toolchain (libffi among it), which hid-# the missing-payload-lib bug class from CI while a real phone hit it.-# The base rootfs matches a first-boot termux device.+# The bare rootfs has no build toolchain to hide a missing payload library.docker run --rm --platform linux/arm64 \- --user root --privileged \+ --user 1000:1000 --network none \-v "$DEB:/tmp/pkg.deb:ro" \- -v "$VD/check.sh:/tmp/check.sh:ro" \- "termux/termux-docker@$DIGEST" sh /tmp/check.sh \+ -v "$HERE/check_deb.sh:/tmp/check.sh:ro" \+ -v "$HERE/validate_installed.py:/tmp/validate_installed.py:ro" \+ "termux/termux-docker@$DIGEST" bash /tmp/check.sh \|| fail "container validation failed"-rm -rf "$VD"log "Built $DEB (validated)"diff --git a/scripts/termux/build_wheels.py b/scripts/termux/build_wheels.pyindex 1b964a6c467..4f0d1756793 100644--- a/scripts/termux/build_wheels.py+++ b/scripts/termux/build_wheels.py@@ -319,7 +319,20 @@ def retag_all(wheelhouse: Path, retag_script: Path, platform_tag: str) -> None: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:+def import_native_modules(build_set: list[str]) -> None:+ import importlib++ modules = {+ "ruamel-yaml-clib": "_ruamel_yaml", "cffi": "_cffi_backend",+ "pillow": "PIL._imaging", "pyyaml": "yaml._yaml", "firecrawl-anydoc": "anydoc",+ }+ for name in build_set:+ module = modules.get(name, name.replace("-", "_"))+ importlib.import_module(module)+ print(" imported", module, flush=True)+++def wheelhouse_gates(resolved: Path, wheelhouse: Path, build_set: list[str], uv: 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).@@ -335,50 +348,34 @@ def wheelhouse_gates(resolved: Path, wheelhouse: Path, build_set: list[str]) ->tmp = Path(tmp)venv = tmp / "venv"subprocess.run(- [UV, "venv", "--python", sys.executable, str(venv)],+ [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),+ [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)+ 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",- "firecrawl-anydoc": "anydoc",- }- 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],+ [str(vp), str(Path(__file__).resolve()), "--import-modules", *build_set],check=True,)print(" import gate: every built native wheel imports")-UV = ""--def main() -> int:- global UV+ if sys.argv[1:2] == ["--import-modules"]:+ import_native_modules(sys.argv[2:])+ return 0args = parse_args()- UV = str(Path(args.uv))+ 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)@@ -397,7 +394,7 @@ def main() -> int:repaired = repair_wheel(wheel, library)if repaired:print(f" linked {repaired} native extensions to {library.name}: {wheel.name}")- wheelhouse_gates(resolved, wheelhouse, build_set)+ wheelhouse_gates(resolved, wheelhouse, build_set, uv)print(f"wheelhouse complete: {len(list(wheelhouse.glob('*.whl')))} wheels in {wheelhouse}")return 0diff --git a/scripts/termux/check_deb.sh b/scripts/termux/check_deb.shnew file mode 100755index 00000000000..8e451d58286--- /dev/null+++ b/scripts/termux/check_deb.sh@@ -0,0 +1,16 @@+#!/data/data/com.termux/files/usr/bin/bash+# Install and test the real package in a fresh, offline Termux rootfs.+set -euo pipefail+export PREFIX=/data/data/com.termux/files/usr+export PATH="$PREFIX/bin:$PATH"+mkdir -p "$PREFIX/tmp"+# Termux runs without root. The image already owns the writable prefix.+dpkg --force-not-root --force-script-chrootless --install /tmp/pkg.deb+root="$PREFIX/lib/hermes-agent"+export LD_LIBRARY_PATH="$root/tools/python$PREFIX/lib:$root/tools/node$PREFIX/lib:$root/tools/ffmpeg$PREFIX/lib:$root/runtime-libs/lib:$PREFIX/lib"+export PYTHONPATH="$root/app"+"$root/venv/bin/python" /tmp/validate_installed.py+# Reinstall exercises maintainer-script idempotence without changing user state.+dpkg --force-not-root --force-script-chrootless --install /tmp/pkg.deb+[ "$(readlink "$PREFIX/bin/hermes")" = ../lib/hermes-agent/bin/hermes ]+printf 'DEB_INSTALL_AND_REINSTALL_OK\n'diff --git a/scripts/termux/launchers.py b/scripts/termux/launchers.pynew file mode 100644index 00000000000..ade06f8fcdf--- /dev/null+++ b/scripts/termux/launchers.py@@ -0,0 +1,98 @@+"""Emit Termux entrypoints and package-manager hooks from declared scripts."""+from __future__ import annotations++import argparse+from pathlib import Path+import shlex+import tomllib+++_LAUNCHER = '''#!/data/data/com.termux/files/usr/bin/sh+set -eu+self="$0"+while [ -L "$self" ]; do+ target="$(readlink "$self")"+ case "$target" in+ /*) self="$target" ;;+ *) self="$(dirname "$self")/$target" ;;+ esac+done+root="$(cd "$(dirname "$self")/.." && pwd)"+PREFIX="${PREFIX:-/data/data/com.termux/files/usr}"+export PREFIX+unset PYTHONHOME+export LD_LIBRARY_PATH="$root/tools/python/data/data/com.termux/files/usr/lib:$root/tools/node/data/data/com.termux/files/usr/lib:$root/tools/ffmpeg/data/data/com.termux/files/usr/lib:$root/runtime-libs/lib:$PREFIX/lib"+export PYTHONPATH="$root/app"+export HERMES_PYTHON_SRC_ROOT="$root/app"+export HERMES_PYTHON="$root/venv/bin/python"+export HERMES_NODE="$root/tools/node/data/data/com.termux/files/usr/bin/node"+export HERMES_RUNTIME_DIR="$root/tools"+export PATH="$root/tools/npm/bin:$root/tools/node/data/data/com.termux/files/usr/bin:$root/tools/ffmpeg/data/data/com.termux/files/usr/bin:$root/tools/ripgrep:$PATH"+export PYTHONPYCACHEPREFIX="${PYTHONPYCACHEPREFIX:-${XDG_CACHE_HOME:-$HOME/.cache}/hermes-pycache}"+exec "$HERMES_PYTHON" -c __ENTRY__ "$@"+'''+++def write_launchers(payload: Path, entries: dict[str, str]) -> None:+ bindir = payload / "bin"+ bindir.mkdir(parents=True, exist_ok=True)+ for name, entry in entries.items():+ module, func = entry.split(":", 1)+ script = f"import sys; from {module} import {func}; sys.exit({func}())"+ path = bindir / name+ path.write_text(_LAUNCHER.replace("__ENTRY__", shlex.quote(script)), encoding="utf-8")+ path.chmod(0o755)+++def write_maintainer_scripts(control: Path, names: list[str]) -> None:+ names_text = " ".join(shlex.quote(name) for name in names)+ postinst = '''#!/data/data/com.termux/files/usr/bin/sh+set -eu+PREFIX="${PREFIX:-/data/data/com.termux/files/usr}"+mkdir -p "$PREFIX/bin"+for name in __NAMES__; do+ link="$PREFIX/bin/$name"+ target="../lib/hermes-agent/bin/$name"+ if [ -L "$link" ] && [ "$(readlink "$link")" = "$target" ]; then+ continue+ fi+ if [ -e "$link" ] || [ -L "$link" ]; then+ printf 'Refusing to replace foreign launcher: %s\\n' "$link" >&2+ exit 1+ fi+ ln -s "$target" "$link"+done+'''+ prerm = '''#!/data/data/com.termux/files/usr/bin/sh+set -eu+PREFIX="${PREFIX:-/data/data/com.termux/files/usr}"+case "${1:-remove}" in+ remove|deconfigure) ;;+ *) exit 0 ;;+esac+for name in __NAMES__; do+ link="$PREFIX/bin/$name"+ if [ -L "$link" ] && [ "$(readlink "$link")" = "../lib/hermes-agent/bin/$name" ]; then+ rm -f "$link"+ fi+done+'''+ for name, script in (("postinst", postinst), ("prerm", prerm)):+ path = control / name+ path.write_text(script.replace("__NAMES__", names_text), encoding="utf-8")+ path.chmod(0o755)+++def main() -> None:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--payload", type=Path, required=True)+ parser.add_argument("--control", type=Path)+ args = parser.parse_args()+ entries = tomllib.loads((args.payload / "app/pyproject.toml").read_text(encoding="utf-8"))["project"]["scripts"]+ write_launchers(args.payload, entries)+ if args.control is not None:+ write_maintainer_scripts(args.control, list(entries))+++if __name__ == "__main__":+ main()diff --git a/scripts/termux/payload_facts.py b/scripts/termux/payload_facts.pynew file mode 100644index 00000000000..e34e3678df7--- /dev/null+++ b/scripts/termux/payload_facts.py@@ -0,0 +1,46 @@+"""Record the staged bionic tools through pm's existing facts contract."""+from __future__ import annotations++import argparse+import json+from pathlib import Path+import sys++sys.path.insert(0, str(Path(__file__).resolve().parents[2]))++from pm.lock import Facts, Lockfile+from pm.store import tree_digest+from pm.registry import get_package+import pm.packages # Registers the runtime definitions.+++def write_facts(payload: Path, lock_path: Path, build_set: Path) -> None:+ target = "linux-arm64-bionic"+ lock = Lockfile(lock_path)+ store = payload / "tools"+ facts = Facts(store / "facts.json")+ for name in ("python", "node", "uv", "npm", "ffmpeg", "ripgrep"):+ entry = store / name+ if not entry.is_dir():+ raise RuntimeError(f"missing payload tool: {name}")+ version = lock.version(name)+ artifacts = lock.artifacts(name, target)+ if not version or not artifacts:+ raise RuntimeError(f"missing pin: {name} on {target}")+ facts.record(+ name, version, name, get_package(name).env(entry, target), store,+ target=target, artifacts=[a["sha256"] for a in artifacts],+ digest=tree_digest(entry),+ )+ natives = [line.strip() for line in build_set.read_text(encoding="utf-8").splitlines() if line.strip()]+ (payload / "native-wheels.json").write_text(json.dumps(natives) + "\n", encoding="utf-8")+ manifest = {"schema": 1, "target": target, "repo": "app", "venv": "venv", "store": "tools"}+ (payload / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")+++if __name__ == "__main__":+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("payload", type=Path)+ parser.add_argument("build_set", type=Path)+ args = parser.parse_args()+ write_facts(args.payload, args.payload / "app/pm/lock.json", args.build_set)diff --git a/scripts/termux/python_linkage.py b/scripts/termux/python_linkage.pyindex 7b7c81295e1..569ec8d3e2b 100644--- a/scripts/termux/python_linkage.py+++ b/scripts/termux/python_linkage.py@@ -78,6 +78,7 @@ def repair_wheel(wheel: Path, library: Path, *, repair=link_extension) -> int:with zipfile.ZipFile(staged, "w", zipfile.ZIP_DEFLATED) as archive:for info, data in updated:archive.writestr(info, record.getvalue().encode() if info.filename == records[0] else data)+ os.chmod(staged, wheel.stat().st_mode & 0o777)os.replace(staged, wheel)finally:Path(staged).unlink(missing_ok=True)diff --git a/scripts/termux/runtime_libs.json b/scripts/termux/runtime_libs.jsonindex 71712a37d56..1792df454b2 100644--- a/scripts/termux/runtime_libs.json+++ b/scripts/termux/runtime_libs.json@@ -1,26 +1,106 @@{- "_comment": "Runtime libs the sealed termux deb ships INSIDE the payload. Derived from the suppliers' own dependency metadata: the TUR python3.11 .deb's Depends line + uv's zstd + nodejs's libc++/c-ares/libicu. The deb is self-contained by contract -- the device's termux tree may have none of these installed. stage_runtime_libs.py downloads + verifies each against its sha256 and unpacks the payloads (hardened ar+tar via pm's DebPackage).",+ "_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.","libs": {+ "brotli": {+ "sha256": "db1502601d40fb44e6085ad8bfd9311a8b472e98db831ceec9d404c5708bb52c",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/b/brotli/brotli_1.2.0_aarch64.deb",+ "version": "1.2.0"+ },"c-ares": {"sha256": "7681fc23e822d7988ba8b2adf3468f93ae68f724dda365cff1385096a9fa87e6","url": "https://packages.termux.dev/apt/termux-main/pool/main/c/c-ares/c-ares_1.34.8_aarch64.deb","version": "1.34.8"},+ "fftw": {+ "sha256": "0a5140986bbfc69dbfa8f939f78521fb3dc02a193b6c822b7218dae44d99ffd5",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/f/fftw/fftw_3.3.11_aarch64.deb",+ "version": "3.3.11"+ },+ "fontconfig": {+ "sha256": "7f8b70dd7ca85b1e7cbb14a11e9e6bd4ce3189ab985aa7af51145484d85f2c61",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/f/fontconfig/fontconfig_2.18.3_aarch64.deb",+ "version": "2.18.3"+ },+ "freetype": {+ "sha256": "670d27d8f53ef2d887b67f8b82fa480f7132b65ac2264a39b3c5b4db637ee285",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/f/freetype/freetype_2.14.3_aarch64.deb",+ "version": "2.14.3"+ },+ "fribidi": {+ "sha256": "a15369457781dbe0af15344d9d184f22ad5da4a7546f94c44c3614646d1f6904",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/f/fribidi/fribidi_1.0.16-1_aarch64.deb",+ "version": "1.0.16-1"+ },+ "game-music-emu": {+ "sha256": "ffe1c43919d485409b2459d462b2dc6389492afeea869aef701b391a4ed29c67",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/g/game-music-emu/game-music-emu_0.6.5_aarch64.deb",+ "version": "0.6.5"+ },"gdbm": {"sha256": "c378de833aae3cf41f3028491ea11836479d9833ab653edc27d0c0e0e691d5c5","url": "https://packages.termux.dev/apt/termux-main/pool/main/g/gdbm/gdbm_1.26-1_aarch64.deb","version": "1.26-1"},+ "glib": {+ "sha256": "b1bfc40c4cfde83470de9efac1e546fdf643b77a966c20a8612bddc7c59cd3dc",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/g/glib/glib_2.88.3_aarch64.deb",+ "version": "2.88.3"+ },+ "glslang": {+ "sha256": "9b1f96bdb0c7679c79d9ae60c1089deb38c0f8731a80232795fbd3aa582f8ac7",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/g/glslang/glslang_16.5.0_aarch64.deb",+ "version": "16.5.0"+ },+ "harfbuzz": {+ "sha256": "7f39fffee18a0956f65d2d3b8e86a36204829cf44f09d36c27d5e5177f36d360",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/h/harfbuzz/harfbuzz_14.4.0_aarch64.deb",+ "version": "14.4.0"+ },+ "highway": {+ "sha256": "d716b2cd6136dc65b1585e87df1a1876929c07c629faeecd57917704f0c74ebb",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/h/highway/highway_1.4.0_aarch64.deb",+ "version": "1.4.0"+ },+ "libandroid-glob": {+ "sha256": "2276ae8adedf0db76c2f4ffc94cc4cceb2f4f5d78e021b54e2e046d1233e7826",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/liba/libandroid-glob/libandroid-glob_0.6-3_aarch64.deb",+ "version": "0.6-3"+ },"libandroid-posix-semaphore": {"sha256": "0efa8677a0166315ba4e685863712eba0ca0a1732827492f38226e2723730c7a","url": "https://packages.termux.dev/apt/termux-main/pool/main/liba/libandroid-posix-semaphore/libandroid-posix-semaphore_0.1-4_aarch64.deb","version": "0.1-4"},+ "libandroid-shmem": {+ "sha256": "0da3a24d558b93c92bcf8d611e0826a99ff96e396b148e6cdf33b47c47c57ff6",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/liba/libandroid-shmem/libandroid-shmem_0.7_aarch64.deb",+ "version": "0.7"+ },"libandroid-support": {"sha256": "f2f145d6135ad4843ac9670153be3e3944dc1e6f1736d46d2306c28f2b86f517","url": "https://packages.termux.dev/apt/termux-main/pool/main/liba/libandroid-support/libandroid-support_29-1_aarch64.deb","version": "29-1"},+ "libaom": {+ "sha256": "f284096506dbdeb160ac09d803948b8fb3ad26535361776535ec43d87f185841",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/liba/libaom/libaom_3.15.0_aarch64.deb",+ "version": "3.15.0"+ },+ "libass": {+ "sha256": "4f94205285ea2062be4f60e695723a6f3350339ec89720943b0dce5ae30db01d",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/liba/libass/libass_0.17.5_aarch64.deb",+ "version": "0.17.5"+ },+ "libbluray": {+ "sha256": "8045df20cfb42de55c14990137391a0cb2f72fa709df672e86e0ebb6107fbf39",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/libb/libbluray/libbluray_1.5.0_aarch64.deb",+ "version": "1.5.0"+ },+ "libbs2b": {+ "sha256": "c71660d99e4baa064ba93f0ef750b6b2ea0d1d494a754cf1c67b550bb4baa91d",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/libb/libbs2b/libbs2b_3.1.0-2_aarch64.deb",+ "version": "3.1.0-2"+ },"libbz2": {"sha256": "4335d7f060650b0aabef545d1334c2f9f280223d5962e13c24a00ec934b794ba","url": "https://packages.termux.dev/apt/termux-main/pool/main/libb/libbz2/libbz2_1.0.8-8_aarch64.deb",@@ -36,6 +116,21 @@"url": "https://packages.termux.dev/apt/termux-main/pool/main/libc/libcrypt/libcrypt_0.2-6_aarch64.deb","version": "0.2-6"},+ "libdav1d": {+ "sha256": "4c2ffdcbbb805727caaa2e91b56917830dbacf4245dd439cf2e1c0d61a541613",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/libd/libdav1d/libdav1d_1.5.4_aarch64.deb",+ "version": "1.5.4"+ },+ "libdvdnav": {+ "sha256": "fd8509a88b5966cdadf9925b2687e50c31d796e773cb326e651e76c0a3b16958",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/libd/libdvdnav/libdvdnav_7.0.0_aarch64.deb",+ "version": "7.0.0"+ },+ "libdvdread": {+ "sha256": "8e1606f7d2aec40c9e8f748ab595cf0f684c998b4642bc59fa6b18b5fe1d2fb0",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/libd/libdvdread/libdvdread_7.1.1_aarch64.deb",+ "version": "7.1.1"+ },"libexpat": {"sha256": "71934cf00b404627702034bd1308cb58353dd851d9a2d3ecd9205b4ae6a67a27","url": "https://packages.termux.dev/apt/termux-main/pool/main/libe/libexpat/libexpat_2.8.4_aarch64.deb",@@ -46,21 +141,211 @@"url": "https://packages.termux.dev/apt/termux-main/pool/main/libf/libffi/libffi_3.5.2_aarch64.deb","version": "3.5.2"},+ "libgraphite": {+ "sha256": "15ac85737a35150cecb9e46ecb32567ae2a4fc28071cdf58fb95e1b77d7889d9",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/libg/libgraphite/libgraphite_1.3.15_aarch64.deb",+ "version": "1.3.15"+ },+ "libiconv": {+ "sha256": "b19e6f348034bb48d2a5590b5cb242769f682c476717374d134d004cc663dc84",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/libi/libiconv/libiconv_1.18-1_aarch64.deb",+ "version": "1.18-1"+ },"libicu": {"sha256": "f536403f65a08fe0df6e7304184e902d54def77d5c3bd5edfd9109d57601d276","url": "https://packages.termux.dev/apt/termux-main/pool/main/libi/libicu/libicu_78.3_aarch64.deb","version": "78.3"},+ "libjpeg-turbo": {+ "sha256": "e6339075bcde28b4902d5a51f4063164834abfd2fa115e881ae637a34585e54f",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/libj/libjpeg-turbo/libjpeg-turbo_3.2.0_aarch64.deb",+ "version": "3.2.0"+ },+ "libjxl": {+ "sha256": "5deef55b1940aef2bc2666fdb4bfcba66cfbf73c17a419f299ddabe312b2ce11",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/libj/libjxl/libjxl_0.12.0-1_aarch64.deb",+ "version": "0.12.0-1"+ },"liblzma": {"sha256": "594925a313879f590fbd24050305551a78eadd9a9319f6e612389b1a521113c6","url": "https://packages.termux.dev/apt/termux-main/pool/main/libl/liblzma/liblzma_5.8.3_aarch64.deb","version": "5.8.3"},+ "libmp3lame": {+ "sha256": "8c28c74209eb5c31675b4e9c1ee5193c1bf22c49ff5965612dcf9aede5d870d9",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/libm/libmp3lame/libmp3lame_3.100-7_aarch64.deb",+ "version": "3.100-7"+ },+ "libmpg123": {+ "sha256": "883b104faae53820b2e758363300ccf99e28f627a263d766af61ae07b73b07b3",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/libm/libmpg123/libmpg123_1.33.7_aarch64.deb",+ "version": "1.33.7"+ },+ "libmysofa": {+ "sha256": "b083050d4bc0bd11db0f73382ae3db8c5dc352520b78aaa44f150d87cff80215",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/libm/libmysofa/libmysofa_1.3.5_aarch64.deb",+ "version": "1.3.5"+ },+ "libogg": {+ "sha256": "4f1700a532f251ad3600f44f88cd764f1f6b0542d3343391117944b47a92802d",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/libo/libogg/libogg_1.3.6-1_aarch64.deb",+ "version": "1.3.6-1"+ },+ "libopencore-amr": {+ "sha256": "8ad25c12b892d56e85a21517d814146109fea7865b2548b8637743d7d6e0fee2",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/libo/libopencore-amr/libopencore-amr_0.1.6-1_aarch64.deb",+ "version": "0.1.6-1"+ },+ "libopenmpt": {+ "sha256": "80c0b91a3804edc69bd45ec8a9ef4f1d1a1b5be2b8712dafce9469069cc1acc0",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/libo/libopenmpt/libopenmpt_0.8.9_aarch64.deb",+ "version": "0.8.9"+ },+ "libopus": {+ "sha256": "005a9335ce0ec0f510bbe6e0229c901d6f920cc375fcda56461e96cef70f8ff0",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/libo/libopus/libopus_1.6.1_aarch64.deb",+ "version": "1.6.1"+ },+ "libplacebo": {+ "sha256": "903ba38d4b1184a7fb37584e93967a73791f5df22fb3f81de5b33051b77b73ca",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/libp/libplacebo/libplacebo_7.360.1_aarch64.deb",+ "version": "7.360.1"+ },+ "libpng": {+ "sha256": "e47937405c72734867513cf0c63d27f36400d462666b65dfada984667d7228c4",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/libp/libpng/libpng_1.6.58_aarch64.deb",+ "version": "1.6.58"+ },+ "librav1e": {+ "sha256": "ac7842a5896bdff1b4d4974d9c02e60f7d4a587b8618df691118a8591f8dbccf",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/libr/librav1e/librav1e_0.8.1_aarch64.deb",+ "version": "0.8.1"+ },+ "libsamplerate": {+ "sha256": "521d46cc49557c00b2d5c107da1f86f0cdda8a3a3b84bd9958bd7fc52bec2dae",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/libs/libsamplerate/libsamplerate_0.2.2-4_aarch64.deb",+ "version": "0.2.2-4"+ },+ "libsodium": {+ "sha256": "a9fbbc3a7a5a2a0f514474ee706d49b576ac09268b87142a3690edb9f5f3643d",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/libs/libsodium/libsodium_1.0.22-1_aarch64.deb",+ "version": "1.0.22-1"+ },+ "libsoxr": {+ "sha256": "a1c5f66aae3b9900e9a492b43901b2b98586870c7905feb9f3c835cc9af464be",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/libs/libsoxr/libsoxr_0.1.3-8_aarch64.deb",+ "version": "0.1.3-8"+ },"libsqlite": {"sha256": "0e909ce0d50fe123305446cd22e0c5edf535d40344b9b065fbdcdee52f53198d","url": "https://packages.termux.dev/apt/termux-main/pool/main/libs/libsqlite/libsqlite_3.53.4_aarch64.deb","version": "3.53.4"},+ "libsrt": {+ "sha256": "6199d01dd9d1630a32c220f7fdb9bca958adbd7062f90e9bfc010cf75fdef07a",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/libs/libsrt/libsrt_1.5.7_aarch64.deb",+ "version": "1.5.7"+ },+ "libssh": {+ "sha256": "05cfb1d6f70e9b316f1eac7a5ec9139f884e644d6d91e668e9ca49716aad8ff0",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/libs/libssh/libssh_0.12.2_aarch64.deb",+ "version": "0.12.2"+ },+ "libtheora": {+ "sha256": "9d4582f14f71df7a48101ee05297a57a898654ead55ef10ca4d73e254151b1e8",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/libt/libtheora/libtheora_1.2.0-1_aarch64.deb",+ "version": "1.2.0-1"+ },+ "libtiff": {+ "sha256": "998c583d65d7d42dcb177548a218545661f02385a51bb9f5c24f0da4fd046574",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/libt/libtiff/libtiff_4.7.2_aarch64.deb",+ "version": "4.7.2"+ },+ "libudfread": {+ "sha256": "61a7e02c30ae61f9cbe46bf8cefa8e361a16b29010a07cacb43513ff533df81c",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/libu/libudfread/libudfread_1.2.0_aarch64.deb",+ "version": "1.2.0"+ },+ "libvidstab": {+ "sha256": "4611cb90ee015b02bf69b5da9031aff64ae1ec11589986e58e37ea6dfe6f4cd4",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/libv/libvidstab/libvidstab_1.1.1-3_aarch64.deb",+ "version": "1.1.1-3"+ },+ "libvmaf": {+ "sha256": "a94f2338b1193603ba8ecd6cddbb29b85b0b3c0b4e35bc16ceacb18309672a22",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/libv/libvmaf/libvmaf_3.2.0-1_aarch64.deb",+ "version": "3.2.0-1"+ },+ "libvo-amrwbenc": {+ "sha256": "aa913ca492246ed1e6ce57a3c52fe856c323cbb6e8dbdb6904b80214551f6e00",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/libv/libvo-amrwbenc/libvo-amrwbenc_0.1.3-2_aarch64.deb",+ "version": "0.1.3-2"+ },+ "libvorbis": {+ "sha256": "6bfd70c4b570b85594bd06116b75a6f8109ec58cbc123e938b630a6eefdedf4e",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/libv/libvorbis/libvorbis_1.3.7-4_aarch64.deb",+ "version": "1.3.7-4"+ },+ "libvpx": {+ "sha256": "1dbc5be0610c9da58732f480c7a27dbb32cf72a472e88c6c0993bdc0feeae00a",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/libv/libvpx/libvpx_1:1.17.0_aarch64.deb",+ "version": "1:1.17.0"+ },+ "libwebp": {+ "sha256": "80fa46bec4faad0ccfd969df5acfd501d813ca9d112b5c49f3f91390e987f3a9",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/libw/libwebp/libwebp_1.6.0-rc1-0_aarch64.deb",+ "version": "1.6.0-rc1-0"+ },+ "libx264": {+ "sha256": "fe98852cb06ce1c963a54284179d8cda42af2fa82afcac09f7d81e6de4d9bbc1",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/libx/libx264/libx264_1:0.164.3191-1_aarch64.deb",+ "version": "1:0.164.3191-1"+ },+ "libx265": {+ "sha256": "8dbfd50ad2ceea5ffa2384f0f4cc16a87cbf56ac83b4861fa4f640d1beb352cd",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/libx/libx265/libx265_4.3_aarch64.deb",+ "version": "4.3"+ },+ "libxau": {+ "sha256": "2d86bed61ce89dd8fdb55e565aede10155f2ce3adaccb61d5f1375aec3314083",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/libx/libxau/libxau_1.0.12-2_aarch64.deb",+ "version": "1.0.12-2"+ },+ "libxcb": {+ "sha256": "191c3642b6a8c754bc75b69b94a81858ecb5f18766dc085aff55559b8087ad34",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/libx/libxcb/libxcb_1.17.0-1_aarch64.deb",+ "version": "1.17.0-1"+ },+ "libxdmcp": {+ "sha256": "caea0cf5c0028af0840774094b8900ef7afffd8f9bbd7b1abfbe66851f0d6077",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/libx/libxdmcp/libxdmcp_1.1.5-2_aarch64.deb",+ "version": "1.1.5-2"+ },+ "libxml2": {+ "sha256": "cc518f2045db589a0dfc10b0d2c4a18234b80911c8e89ec60bf0eff7bb4db600",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/libx/libxml2/libxml2_2.15.4_aarch64.deb",+ "version": "2.15.4"+ },+ "libyaml": {+ "sha256": "fad02df630fcee4219133112377965d119543a9d999dcbc6e19a2c1550bf2b60",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/liby/libyaml/libyaml_0.2.5-5_aarch64.deb",+ "version": "0.2.5-5"+ },+ "libzimg": {+ "sha256": "a776d30cdb5734fa8feb17fb89fe8a67d14d64e491777d9b62b0fd714a9b59e8",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/libz/libzimg/libzimg_3.0.6_aarch64.deb",+ "version": "3.0.6"+ },+ "libzmq": {+ "sha256": "1d59efb56905e79159808c6b656cc768ffcc210012bc2d9b63f23162f65480d2",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/libz/libzmq/libzmq_4.3.5-2_aarch64.deb",+ "version": "4.3.5-2"+ },+ "littlecms": {+ "sha256": "274f732a186563beca204f5d016d30cac8e5c24f7c4395b60881f9613eddf1a1",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/l/littlecms/littlecms_2.19.1_aarch64.deb",+ "version": "2.19.1"+ },"ncurses": {"sha256": "f44bbfdc3d42ec0217bffa978309390e59cea5a48a9a83226d4a496c42ad0b99","url": "https://packages.termux.dev/apt/termux-main/pool/main/n/ncurses/ncurses_6.6.20260307+really6.5.20250830_aarch64.deb",@@ -71,16 +356,46 @@"url": "https://packages.termux.dev/apt/termux-main/pool/main/n/ncurses-ui-libs/ncurses-ui-libs_6.6.20260307+really6.5.20250830_aarch64.deb","version": "6.6.20260307+really6.5.20250830"},+ "ocl-icd": {+ "sha256": "2d76ddf09069ad599a4d5b2aee374c58411e1a3b0618b1ca5412467c9fd7b26a",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/o/ocl-icd/ocl-icd_2.3.5_aarch64.deb",+ "version": "2.3.5"+ },+ "openjpeg": {+ "sha256": "93ad32c8caa0eb8943e2dd86b5c2eaf48a767709a3fa069a5b670d948656c7d8",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/o/openjpeg/openjpeg_2.5.4_aarch64.deb",+ "version": "2.5.4"+ },"openssl": {"sha256": "86760e9ce736f463236f2c15b1eb3a3fdcfc5778d0fd7077a917448dcc90f3aa","url": "https://packages.termux.dev/apt/termux-main/pool/main/o/openssl/openssl_1:3.6.3_aarch64.deb","version": "1:3.6.3"},+ "pcre2": {+ "sha256": "51f915d22de639bfca6ec029ae613987bbe3bc73626eede13319fd2e95f50b63",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/p/pcre2/pcre2_10.47_aarch64.deb",+ "version": "10.47"+ },"readline": {"sha256": "e50fb67f40753247dbb83efb17c7fbee0ac868ffcb5b5555d44d76ec8d90b4b1","url": "https://packages.termux.dev/apt/termux-main/pool/main/r/readline/readline_8.3.3_aarch64.deb","version": "8.3.3"},+ "rubberband": {+ "sha256": "1172030a1e3ed70976114c8ca3eb4da0b82c1714825bd751ac1ada606dbc685a",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/r/rubberband/rubberband_4.0.0-1_aarch64.deb",+ "version": "4.0.0-1"+ },+ "svt-av1": {+ "sha256": "e1fd576d086e2d870429e3ae16610b24cb1d0c8f9fcf330fa0abba9e867aabdb",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/s/svt-av1/svt-av1_4.2.0_aarch64.deb",+ "version": "4.2.0"+ },+ "xvidcore": {+ "sha256": "2f358b11fd750935b43ac19f09bb7c4228e007079426e0b73ee8bae1ddf26fc1",+ "url": "https://packages.termux.dev/apt/termux-main/pool/main/x/xvidcore/xvidcore_1.3.7-1_aarch64.deb",+ "version": "1.3.7-1"+ },"zlib": {"sha256": "75e7d0af17fcc3b40004309fdc00a1ddb9ae08346dce5e269902c34ac3966ac9","url": "https://packages.termux.dev/apt/termux-main/pool/main/z/zlib/zlib_1.3.2_aarch64.deb",diff --git a/scripts/termux/stage_apt_repo.py b/scripts/termux/stage_apt_repo.pyindex 44f4a6faa93..46941ca94c5 100644--- a/scripts/termux/stage_apt_repo.py+++ b/scripts/termux/stage_apt_repo.py@@ -27,6 +27,7 @@ import shutilimport subprocessimport sysimport tarfile+import tempfileimport timefrom pathlib import Path@@ -201,17 +202,17 @@ def existing_published(out_dir: Path, suite: str) -> set:published = set()if packages_file.exists():text = packages_file.read_text(encoding="utf-8")- pkg = ver = None- for line in text.splitlines():- if line.startswith("Package: "):- pkg = line[len("Package: "):].strip()- elif line.startswith("Version: "):- ver = line[len("Version: "):].strip()- elif not line.strip() and pkg and ver:+ # deb822 records are separated by blank lines; never rely on field+ # order inside a record.+ for stanza in text.split("\n\n"):+ pkg = ver = None+ for line in stanza.splitlines():+ if line.startswith("Package: "):+ pkg = line[len("Package: "):].strip()+ elif line.startswith("Version: "):+ ver = line[len("Version: "):].strip()+ if pkg and ver:published.add((pkg, ver))- pkg = ver = None- if pkg and ver:- published.add((pkg, ver))return published@@ -258,11 +259,15 @@ def stage(pool_dir: Path, out_dir: Path, suite: str, gpg_key_file: Path | None)})- # Packages sorted by version, canary (~) below stable+ # Packages stanzas MUST be separated by blank lines: apt parses the file+ # as deb822 records and a missing blank line merges consecutive records+ # into one garbled stanza (biting exactly when the repo carries multiple+ # versions of the same package -- the first thing a canary+stable repo+ # has). existing_published() below relies on the same blank-line layout.stanzas.sort(key=lambda s: (s["Package"], deb_version_key(s["Version"])))- packages_text = "\n".join(+ packages_text = "\n\n".join("\n".join(f"{k}: {v}" for k, v in stanza.items()) for stanza in stanzas) + ("\n" if stanzas else "")@@ -307,62 +312,195 @@ def stage(pool_dir: Path, out_dir: Path, suite: str, gpg_key_file: Path | None)return 3-def sign(dists: Path, release_path: Path, gpg_key_file: Path) -> None:- # Real signing keys are usually passphrase-protected; TERMUX_APT_GPG_PASSPHRASE- # (set only when the key needs one) rides in via argv -- never the key material.- passphrase = os.environ.get("TERMUX_APT_GPG_PASSPHRASE", "")- base = ["gpg", "--batch", "--yes", "--pinentry-mode", "loopback"]- if passphrase:- base += ["--passphrase", passphrase]-- def gpg(*args: str, stdin: bytes | None = None) -> bytes:- result = subprocess.run(- [*base, *args],- input=stdin, capture_output=True,+def _gpg_homedir_arg(path: Path) -> str:+ """Format a homedir path for the host's gpg.++ On Windows the commonly available gpg is the MSYS/Git-for-Windows build,+ which rejects native ``C:\\...`` paths for --homedir and needs the+ ``/c/...`` form. POSIX gpg (CI's ubuntu runner) needs paths untouched,+ so the conversion applies only to Windows drive-letter paths.+ """+ s = str(path)+ if os.name == "nt" and len(s) >= 2 and s[1] == ":":+ return f"/{s[0].lower()}{s[2:].replace(chr(92), '/')}"+ return s+++def _gpg_run(+ homedir: Path,+ args: list,+ *,+ stdin: bytes | None = None,+ passphrase: str | None = None,+) -> subprocess.CompletedProcess:+ """Run gpg with an explicit isolated homedir.++ The passphrase, when the key needs one, is fed on STDIN via+ ``--passphrase-fd 0`` -- it is never placed in argv (visible in+ /proc or error output) and never written to disk.+ """+ cmd = ["gpg", "--batch", "--yes", "--homedir", _gpg_homedir_arg(homedir)]+ if passphrase is not None:+ cmd += ["--pinentry-mode", "loopback", "--passphrase-fd", "0"]+ if stdin is not None:+ raise StageError("internal error: passphrase and data stdin are the same fd")+ stdin = passphrase.encode("utf-8")++ # File-backed capture, not pipes: gpg's spawned gpg-agent can outlive+ # (and inherit) the child's stdout/stderr pipes, and a reader waiting+ # for pipe EOF would then hang forever after gpg itself has exited.+ # A wait() on files returns as soon as gpg exits.+ # Also guarantee HOME: hardened CI runners execute with a scrubbed+ # environment (env -i), and the gpg-agent spawned by gpg fails to start+ # with no HOME set.+ env = dict(os.environ)+ if not env.get("HOME"):+ env["HOME"] = str(homedir)+ with tempfile.TemporaryDirectory(prefix="apt-stage-gpg-io-") as io_dir:+ out_path = Path(io_dir) / "stdout"+ err_path = Path(io_dir) / "stderr"+ with open(out_path, "wb") as fo, open(err_path, "wb") as fe:+ result = subprocess.run(+ [*cmd, *args],+ input=stdin,+ stdin=subprocess.DEVNULL if stdin is None else None,+ stdout=fo, stderr=fe, env=env,+ )+ result.stdout = out_path.read_bytes()+ result.stderr = err_path.read_bytes()+ if result.returncode != 0:+ raise StageError(+ f"gpg {' '.join(args[:2])} failed: {result.stderr.decode(errors='replace').strip()}")- if result.returncode != 0:- raise StageError(f"gpg failed: {result.stderr.decode(errors='replace')}")- return result.stdout-- secret = gpg_key_file.read_bytes()- gpg("--import", stdin=secret)- # key file may be a full keypair; extract the key id via listing- listing = gpg("--list-secret-keys", "--with-colons").decode()- key_id = None+ return result+++def _sole_secret_key_fingerprint(homedir: Path) -> str:+ """Fingerprint of the ONLY signing-capable secret key in the homedir.++ The homedir is a fresh temp dir into which exactly the supplied key file+ was imported, so whatever is here came from the import -- never a+ pre-existing unrelated key from a user keyring. If the file carried+ multiple keys we fail closed rather than silently signing with the+ first one.+ """+ listing = _gpg_run(+ homedir, ["--with-colons", "--list-secret-keys"]+ ).stdout.decode("utf-8", "replace")+ fingerprints = []+ primary = Falsefor line in listing.splitlines():- if line.startswith("sec:"):- key_id = line.split(":")[4]- break- if not key_id:- raise StageError("no secret key found after import")+ fields = line.split(":")+ if fields[0] in ("sec", "ssb"):+ primary = fields[0] == "sec"+ elif fields[0] == "fpr" and primary:+ fingerprints.append(fields[9])+ primary = False+ if not fingerprints:+ raise StageError("supplied key file produced no secret key after import")+ if len(set(fingerprints)) != 1:+ raise StageError(+ f"supplied key file contains {len(set(fingerprints))} secret keys; "+ "refusing to guess which one signs the repository"+ )+ return fingerprints[0]- gpg(- "--clearsign", "--local-user", key_id,- "--output", str(dists / "InRelease"),- str(release_path),- )- gpg(- "--detach-sign", "--armor", "--local-user", key_id,- "--output", str(dists / "Release.gpg"),- str(release_path),- )- # Publish the signing key's public half at the repo root. The published- # key is exported from the exact key that signed THIS suite, so the two- # can never drift -- a key rotation re-publishes itself on the next- # run. Users fetch it from a stable URL (docs point here).- root = dists.parent.parent- pub = gpg("--armor", "--export", key_id)- if not pub.strip():- raise StageError("gpg exported an empty public key")- (root / "key.asc").write_bytes(pub)+def _verify_signature(+ homedir: Path, expected_fpr: str, sig_path: Path, signed_path: Path | None+) -> None:+ """Fail-closed check that sig_path is a GOOD signature by expected_fpr.++ Verified via gpg --status-fd VALIDSIG (not exit code alone), and the+ fingerprint must match the key that was selected from the import.+ """+ args = ["--with-colons", "--status-fd", "1", "--verify", str(sig_path)]+ if signed_path is not None:+ args.append(str(signed_path))+ result = _gpg_run(homedir, args)+ valid = []+ for line in result.stdout.decode("utf-8", "replace").splitlines():+ if line.startswith("[GNUPG:] VALIDSIG "):+ fields = line.split()+ valid.append(fields[2])+ if len(fields) > 11:+ valid.append(fields[11]) # Primary key when a signing subkey made the signature.+ if expected_fpr not in valid:+ raise StageError(+ f"post-sign verification failed for {sig_path.name}: no VALIDSIG "+ f"for {expected_fpr}; refusing to publish the repository"+ )+++def sign(dists: Path, release_path: Path, gpg_key_file: Path) -> None:+ """Sign Release as InRelease + detached Release.gpg in an ISOLATED+ temp GNUPGHOME, verify the signatures fail-closed, then publish the+ signing key's public half at the repo root.++ Nothing here touches the invoking user's real keyring: the gpg homedir+ is a throwaway temp directory whose only content is the supplied key+ file, and it is removed afterwards. Real signing keys are usually+ passphrase-protected; TERMUX_APT_GPG_PASSPHRASE (set only when the key+ needs one) reaches gpg via stdin, never argv.+ """+ passphrase = os.environ.get("TERMUX_APT_GPG_PASSPHRASE", "")+ homedir = Path(tempfile.mkdtemp(prefix="apt-stage-gnupg-"))+ try:+ secret = gpg_key_file.read_bytes()+ _gpg_run(homedir, ["--import"], stdin=secret)+ key_id = _sole_secret_key_fingerprint(homedir)++ _gpg_run(+ homedir,+ [+ "--clearsign", "--local-user", key_id,+ "--output", str(dists / "InRelease"),+ str(release_path),+ ],+ passphrase=passphrase,+ )+ _gpg_run(+ homedir,+ [+ "--detach-sign", "--armor", "--local-user", key_id,+ "--output", str(dists / "Release.gpg"),+ str(release_path),+ ],+ passphrase=passphrase,+ )++ # Fail closed: the run is only a success if both artifacts verify as+ # GOOD signatures from the exact imported key. A signature that does+ # not verify is worse than none -- apt would reject the repo, but so+ # would any mirror that already cached it.+ _verify_signature(homedir, key_id, dists / "InRelease", None)+ _verify_signature(homedir, key_id, dists / "Release.gpg", release_path)++ # Publish the signing key's public half at the repo root. The key is+ # exported from the exact key that signed THIS suite, so the two can+ # never drift -- a key rotation re-publishes itself on the next run.+ # Users verify it by fingerprint (see website/docs/getting-started/+ # termux.md); the fingerprint is the trust anchor, not the URL.+ pub = _gpg_run(homedir, ["--armor", "--export", key_id]).stdout+ if not pub.strip():+ raise StageError("gpg exported an empty public key")+ (dists.parent.parent / "key.asc").write_bytes(pub)+ finally:+ shutil.rmtree(homedir, ignore_errors=True)def main(argv: list | None = None) -> int:ap = argparse.ArgumentParser(description="Stage a static APT repo layout.")ap.add_argument("--pool", required=True, type=Path)ap.add_argument("--out", required=True, type=Path)- ap.add_argument("--suite", required=True, choices=["hermes-stable", "hermes-canary"])+ # hermes-nightly is the suite actually published today+ # (https://hermes-assets.nousresearch.com/releases/termux/nightly/,+ # verified 2026-09-06); hermes-stable/hermes-canary are what CI stages+ # for the stable/canary channels.+ ap.add_argument(+ "--suite", required=True,+ choices=["hermes-stable", "hermes-canary", "hermes-nightly"],+ )ap.add_argument("--gpg-key-file", type=Path, default=None)args = ap.parse_args(argv)diff --git a/scripts/termux/stage_runtime_libs.py b/scripts/termux/stage_runtime_libs.pyindex 993958bde0f..e0acd536a54 100644--- a/scripts/termux/stage_runtime_libs.py+++ b/scripts/termux/stage_runtime_libs.py@@ -15,13 +15,20 @@ dpkg, never executing package content). Every *.so* from the package'slib/ payload merges into ONE flat directory -- the trampolines then put asingle payload dir on the linker path.-Idempotent: the merged directory is rebuilt per package (missing files are-restored), so this also serves as the cache-restore path.+Cache correctness: the merged directory is only trusted when a manifest+(runtime-libs/manifest.json) records it. The manifest binds the EXACT pin+table (its sha256) to every merged .so's sha256, and is usable only when+the staged set is nonempty, EXACTLY matches the manifest's file set, and+every hash matches. Anything else -- missing file, extra file, stale+bytes, stale table -- is a miss: the merged dir is rebuilt COMPLETELY+from digest-verified .deb downloads/extractions and the manifest is+emitted only after the complete build succeeds.Usage: stage_runtime_libs.py <payload-dir>"""from __future__ import annotations+import hashlibimport jsonimport shutilimport sys@@ -35,6 +42,11 @@ from pm.downloader import Download, Source # noqa: E402from pm.package import DebPackage # noqa: E402PREFIX_REL = "data/data/com.termux/files/usr"+MANIFEST_NAME = "manifest.json"+++class StageError(RuntimeError):+ """Runtime-lib staging failed; the merged dir may be incomplete."""class _LibDeb(DebPackage):@@ -51,70 +63,158 @@ class _LibDeb(DebPackage):return ""-def _extracted_sonames(work: Path, name: str) -> list[Path]:- """The .so* files a package's extract dir holds (empty when the extract- dir is absent -- cold cache)."""- lib_dir = work / "extract" / name / PREFIX_REL / "lib"- return list(lib_dir.glob("*.so*")) if lib_dir.is_dir() else []---def main() -> int:- if len(sys.argv) != 2:- print("usage: stage_runtime_libs.py <payload-dir>", file=sys.stderr)- return 2- payload = Path(sys.argv[1]).resolve()+def _sha256_file(path: Path) -> str:+ digest = hashlib.sha256()+ with open(path, "rb") as f:+ for block in iter(lambda: f.read(1 << 20), b""):+ digest.update(block)+ return digest.hexdigest()+++def _table_sha256(table: dict) -> str:+ return hashlib.sha256(+ json.dumps(table, sort_keys=True, separators=(",", ":")).encode()+ ).hexdigest()+++def _cache_valid(out: Path, manifest_path: Path, table: dict) -> bool:+ """The staged merged dir is usable only when a manifest exists that+ binds the exact current table to a nonempty, EXACT set of .so files+ whose bytes all hash to the recorded values."""+ if not out.is_dir() or not manifest_path.is_file():+ return False+ try:+ manifest = json.loads(manifest_path.read_text(encoding="utf-8"))+ files = manifest["files"]+ except (ValueError, KeyError, OSError):+ return False+ if manifest.get("table_sha256") != _table_sha256(table):+ return False+ if not isinstance(files, dict) or not files:+ return False+ staged = {p.name: p for p in out.glob("*.so*")}+ if set(staged) != set(files):+ return False # extra or missing files: do not trust the survivor+ for name, want in files.items():+ try:+ if _sha256_file(staged[name]) != want:+ return False+ except OSError:+ return False+ return True+++def _ensure_extracted(work: Path, name: str, row: dict) -> Path:+ """Return the package's extract dir, downloading + unpacking the+ digest-verified .deb when the extraction is absent or stale (its+ extraction marker does not match the currently pinned sha256)."""+ extract = work / "extract" / name+ scratch = work / "dl"+ scratch.mkdir(parents=True, exist_ok=True)+ archive = scratch / f"{name}.deb"+ marker = extract / ".deb-sha256"++ archive_ok = False+ if archive.exists():+ try:+ archive_ok = _sha256_file(archive) == row["sha256"]+ except OSError:+ archive_ok = False+ extraction_ok = (+ any(extract.glob(f"{PREFIX_REL}/lib/*.so*"))+ and marker.is_file()+ and marker.read_text(encoding="utf-8").strip() == row["sha256"]+ )+ if extraction_ok and archive_ok:+ return extract++ if not archive_ok:+ Download([Source(row["url"], archive, row["sha256"])],+ partials_dir=scratch).run()+ if extract.exists():+ shutil.rmtree(extract)+ extract.mkdir(parents=True, exist_ok=True)+ _LibDeb(name).unpack(archive, extract, "linux-arm64-bionic")+ marker.write_text(row["sha256"], encoding="utf-8")+ return extract+++def stage(payload: Path, table: dict) -> Path:+ """Stage every pinned runtime lib into <payload>/runtime-libs/lib/.++ Returns the merged output dir. Raises StageError on any failure; the+ manifest is written only after a complete, verified build.+ """+ payload = Path(payload).resolve()payload.mkdir(parents=True, exist_ok=True)out = payload / "runtime-libs" / "lib"-- table = json.loads((HERE / "runtime_libs.json").read_text(encoding="utf-8"))["libs"]work = payload / ".work" / "runtime-libs"- scratch = work / "dl"- scratch.mkdir(parents=True, exist_ok=True)+ manifest_path = payload / "runtime-libs" / MANIFEST_NAME- # The merged output dir IS the cache-restore surface (the CI workflow- # caches payload/runtime-libs, not the scratch extract dirs), so the- # skip check keys on it: a complete merged dir means every pinned .deb- # already made it in, and the whole download+unpack pass is skipped.- expected_sonames = {- so.name- for name in table- for so in _extracted_sonames(work, name)- }- merged_now = {so.name for so in out.glob("*.so*")} if out.is_dir() else set()- # Guard the empty>=empty cold-start case: with nothing staged there is- # nothing to skip -- run the full download+unpack pass.- if merged_now and merged_now >= expected_sonames:- print(f"runtime libs already staged: {len(merged_now)} .so* -> {out}")- return 0+ if _cache_valid(out, manifest_path, table):+ print(f"runtime libs already staged (manifest-verified): "+ f"{len(list(out.glob('*.so*')))} .so* -> {out}")+ return out++ # Miss: rebuild the merged dir COMPLETELY from scratch. Nothing from+ # a previous partial or corrupted state survives.+ if out.exists():+ shutil.rmtree(out)+ out.mkdir(parents=True, exist_ok=True)merged = 0for name, row in table.items():- extract = work / "extract" / name- if not any(extract.glob(f"{PREFIX_REL}/lib/*.so*")):- archive = scratch / f"{name}.deb"- Download([Source(row["url"], archive, row["sha256"])], partials_dir=scratch).run()- if extract.exists():- shutil.rmtree(extract)- extract.mkdir(parents=True, exist_ok=True)- _LibDeb(name).unpack(archive, extract, "linux-arm64-bionic")+ extract = _ensure_extracted(work, name, row)lib_dir = extract / PREFIX_REL / "lib"- if not lib_dir.is_dir():- print(f" {name}: no {PREFIX_REL}/lib in the package", file=sys.stderr)- return 1+ sos = sorted(lib_dir.glob("*.so*"))+ if not sos:+ raise StageError(f"{name}: no shared objects in "+ f"{PREFIX_REL}/lib of the package")n = 0- for so in sorted(lib_dir.glob("*.so*")):+ for so in sos:dest = out / so.nameif dest.exists():- continue # co-installed packages share sonames; first wins+ # Co-installed packages share sonames: only identical+ # bytes may collide.+ if _sha256_file(so) != _sha256_file(dest):+ raise StageError(+ f"soname collision with different bytes: "+ f"{so.name} from {name} vs already-staged")+ continuedest.parent.mkdir(parents=True, exist_ok=True)shutil.copy2(so, dest)n += 1merged += nprint(f" {name} {row['version']}: {n} new .so* -> runtime-libs/lib")+if not any(out.glob("*.so*")):- print("no shared objects staged", file=sys.stderr)+ raise StageError("no shared objects staged")++ # Manifest last: its existence is the promise that the build above+ # completed for the exact table.+ manifest = {+ "table_sha256": _table_sha256(table),+ "files": {p.name: _sha256_file(p) for p in sorted(out.glob("*.so*"))},+ }+ manifest_path.write_text(+ json.dumps(manifest, indent=2, sort_keys=True) + "\n", encoding="utf-8")+ print(f"runtime libs staged: {len(table)} packages, {merged} new .so* "+ f"-> {out}")+ return out+++def main() -> int:+ if len(sys.argv) != 2:+ 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"))["libs"]+ try:+ stage(payload, table)+ except Exception as exc: # noqa: BLE001 -- CLI boundary reports and exits+ print(f"runtime-lib staging failed: {exc}", file=sys.stderr)return 1- print(f"runtime libs staged: {len(table)} packages, {merged} new .so* -> {out}")return 0diff --git a/scripts/termux/termux_build.sh b/scripts/termux/termux_build.shindex c470a6bdf95..725c0d33e06 100644--- a/scripts/termux/termux_build.sh+++ b/scripts/termux/termux_build.sh@@ -30,6 +30,8 @@ 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"+ # Readers on the host must retain failed-build evidence too.+ umask 022# $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@@ -43,7 +45,7 @@ if [ "${1:-}" = "--in-container" ]; then# (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}"+ export LD_LIBRARY_PATH="$PAYLOAD_ROOT/python$PREFIX/lib:$PAYLOAD_ROOT/node$PREFIX/lib:$PAYLOAD_ROOT/runtime-libs/lib:$PREFIX/lib"if [ -n "$PAYLOAD_ROOT" ] && [ -x "$STAGED_PY" ] && [ -x "$STAGED_UV" ]; thenPY="$STAGED_PY"UV="$STAGED_UV"@@ -180,63 +182,37 @@ 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+# Preserve cached requirements and the native-build list until the manifest+# verifies both. Only the application archive changes for every release tag.+rm -rf "$WORK/tree"+mkdir -p "$WORK/tree" "$WHEELHOUSE"# [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"-}+git -C "$REPO_ABS" archive --format=tar "$TAG" | tar -xf - -C "$WORK/tree"[ -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).+REPO_ROOT="$(cd "$HERE/../.." && pwd)"+DIGEST="$(cd "$REPO_ROOT" && python3 -c 'from pm.lock import termux_docker_digest; print(termux_docker_digest())')"+[ -n "$DIGEST" ] || fail "termux-docker digest missing from pm/lock.json"+IMAGE="${TERMUX_BUILDER_IMAGE:-termux/termux-docker@$DIGEST}"+docker pull "$IMAGE"+IMAGE="$(docker image inspect --format '{{index .RepoDigests 0}}' "$IMAGE")"+CACHE_ARGS=(--payload "$OUT_ABS" --repo "$WORK/tree" --builder "$IMAGE"+ --platform-tag "$PLATFORM_TAG" --python-abi "$PYTHON_ABI")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+if python3 "$HERE/wheelhouse_cache.py" check "${CACHE_ARGS[@]}"; thenWHEELHOUSE_CACHE_OK=1- log "Wheelhouse cache restored complete -- skipping resolve, probe, and the container build"+ log "Wheelhouse cache verified -- skipping resolve, probe, and native builds"fiif [ "$WHEELHOUSE_CACHE_OK" -eq 0 ]; then+# An unproven wheel must not reach the per-package skip check.+rm -rf "$WHEELHOUSE"+mkdir -p "$WHEELHOUSE"+rm -f "$OUT_ABS/index.json" "$OUT_ABS/SHA256SUMS" "$WORK/resolved.txt" "$WORK/build_set.txt"# [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" ) \+( cd "$WORK/tree" && uv export --frozen --no-emit-project --extra acp -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"@@ -370,16 +346,6 @@ 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@@ -421,33 +387,9 @@ firm -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+# [h] Only a successful native build and both gates can publish cache proof.+log "Emitting index.json and SHA256SUMS"+python3 "$HERE/wheelhouse_cache.py" write "${CACHE_ARGS[@]}" --tag "$TAG" \+ || fail "manifest emission failed"log "Wheelhouse complete: $WHEELHOUSE"diff --git a/scripts/termux/validate_installed.py b/scripts/termux/validate_installed.pynew file mode 100644index 00000000000..f2069e4115d--- /dev/null+++ b/scripts/termux/validate_installed.py@@ -0,0 +1,133 @@+"""Exercise a freshly installed Termux bundle with networking disabled."""+from __future__ import annotations++import fcntl+import importlib+import json+import os+from pathlib import Path+import pty+import re+import select+import signal+import struct+import subprocess+import sys+import termios+import tempfile+import time+++def run(argv: list[str], env: dict[str, str], cwd: Path) -> subprocess.CompletedProcess:+ result = subprocess.run(argv, env=env, cwd=cwd, capture_output=True, text=True, timeout=90)+ print("+", " ".join(argv), flush=True)+ print(result.stdout, result.stderr, flush=True)+ result.check_returncode()+ return result+++def tui_smoke(launcher: Path, env: dict[str, str], cwd: Path) -> None:+ master, slave = pty.openpty()+ fcntl.ioctl(slave, termios.TIOCSWINSZ, struct.pack("HHHH", 40, 120, 0, 0))+ child = subprocess.Popen(+ [str(launcher), "--tui"], stdin=slave, stdout=slave, stderr=slave,+ cwd=cwd, env={**env, "TERM": "xterm-256color"}, start_new_session=True,+ )+ os.close(slave)+ captured = bytearray()+ ready = False+ try:+ deadline = time.monotonic() + 90+ while time.monotonic() < deadline:+ if select.select([master], [], [], 0.5)[0]:+ try:+ chunk = os.read(master, 65536)+ except OSError:+ break+ if not chunk:+ break+ captured.extend(chunk)+ plain = re.sub(rb"\x1b\[[0-?]*[ -/]*[@-~]", b"", bytes(captured))+ if b"Setup Required" in plain and b"/model" in plain:+ ready = True+ break+ if child.poll() is not None:+ break+ if not ready:+ raise RuntimeError("TUI never reached its real setup screen:\n" + captured.decode(errors="replace"))+ print("TUI_SETUP_SCREEN_OK", flush=True)+ finally:+ if child.poll() is None:+ os.killpg(child.pid, signal.SIGTERM)+ try:+ child.wait(timeout=10)+ except subprocess.TimeoutExpired:+ os.killpg(child.pid, signal.SIGKILL)+ child.wait(timeout=10)+ os.close(master)+++def main() -> None:+ prefix = Path(os.environ["PREFIX"])+ root = prefix / "lib/hermes-agent"+ with tempfile.TemporaryDirectory(prefix="hermes-install-proof-", dir=prefix / "tmp") as tmp:+ home = Path(tmp)+ env = {+ "PREFIX": str(prefix), "HOME": str(home), "HERMES_HOME": str(home / "state"),+ "PATH": str(prefix / "bin"), "TERM": "xterm-256color", "LANG": "C.UTF-8",+ "LD_LIBRARY_PATH": ":".join((+ str(root / "tools/python" / prefix.relative_to("/") / "lib"),+ str(root / "tools/node" / prefix.relative_to("/") / "lib"),+ str(root / "tools/ffmpeg" / prefix.relative_to("/") / "lib"),+ str(root / "runtime-libs/lib"), str(prefix / "lib"),+ )),+ "HERMES_RUNTIME_DIR": str(root / "tools"),+ "PYTHONPATH": str(root / "app"),+ "PYTHONPYCACHEPREFIX": str(home / "pycache"),+ }+ launcher = prefix / "bin/hermes"+ run([str(launcher), "--version"], env, home)+ run([str(launcher), "chat", "--help"], env, home)+ run([str(prefix / "bin/hermes-acp"), "--check"], env, home)+ python = root / "venv/bin/python"+ run([+ str(python), "-c",+ "import ctypes, ssl, sqlite3, bz2, lzma, zlib, hashlib, readline; "+ "import cli, run_agent, tui_gateway.server; "+ "from hermes_cli.config import detect_install_method; "+ "assert detect_install_method() == 'apt'; "+ "print('CLI_AND_STDLIB_IMPORTS_OK')",+ ], env, home)+ natives = json.loads((root / "native-wheels.json").read_text(encoding="utf-8"))+ run([+ str(python), str(root / "app/scripts/termux/build_wheels.py"),+ "--import-modules", *natives,+ ], env, home)+ node = root / "tools/node" / prefix.relative_to("/") / "bin/node"+ run([str(node), "--version"], env, home)+ run([str(node), str(root / "tools/npm/lib/node_modules/npm/bin/npm-cli.js"), "--version"], env, home)+ run([str(root / "tools/ripgrep/rg"), "--version"], env, home)+ ffmpeg = root / "tools/ffmpeg" / prefix.relative_to("/") / "bin/ffmpeg"+ output = home / "silence.wav"+ run([str(ffmpeg), "-hide_banner", "-f", "lavfi", "-i", "anullsrc=r=16000:cl=mono", "-t", "0.1", str(output)], env, home)+ import wave+ with wave.open(str(output), "rb") as audio:+ assert audio.getnframes() > 0 and audio.getframerate() == 16000+ print("FFMPEG_MEDIA_CONVERSION_OK", flush=True)+ run([+ str(python), "-c",+ "import pm; import subprocess; from pathlib import Path; "+ "p,e=pm.uv(realize=False); assert p and Path(p).is_file(), p; "+ "subprocess.run([p, '--version'],env=e,check=True); "+ "assert not pm.check(), pm.check(); print('PM_RUNTIME_TOOLS_OK')",+ ], env, home)+ result = subprocess.run([str(launcher), "update"], env=env, cwd=home, capture_output=True, text=True, timeout=60)+ if result.returncode == 0 or "pkg upgrade hermes-agent" not in result.stdout + result.stderr:+ raise RuntimeError(f"wrong updater refusal ({result.returncode}): {result.stdout}\n{result.stderr}")+ print("APT_UPDATE_REFUSAL_OK", flush=True)+ tui_smoke(launcher, env, home)+ print("INSTALLED_BUNDLE_VALIDATION_OK", flush=True)+++if __name__ == "__main__":+ main()diff --git a/scripts/termux/wheelhouse_cache.py b/scripts/termux/wheelhouse_cache.pynew file mode 100644index 00000000000..80271750094--- /dev/null+++ b/scripts/termux/wheelhouse_cache.py@@ -0,0 +1,98 @@+"""The wheelhouse manifest is the proof used to admit restored build output."""+from __future__ import annotations++import argparse+import hashlib+import json+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",+ "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/termux-builder.Dockerfile",+ )+ return {+ "builder": builder,+ "platformTag": platform_tag,+ "pythonAbi": python_abi,+ **{name: _sha256(repo / name) for name in files},+ }+++def _sha256(path: Path) -> str:+ with path.open("rb") as stream:+ return hashlib.file_digest(stream, "sha256").hexdigest()+++def write_manifest(payload: Path, identity: dict[str, str], **metadata: str) -> None:+ wheels = sorted((payload / "wheelhouse").glob("*.whl"))+ if not wheels:+ raise ValueError("cannot cache an empty wheelhouse")+ index = {+ **metadata,+ "schemaVersion": 2,+ "inputs": identity,+ "resolvedSha256": _sha256(payload / ".work/resolved.txt"),+ "buildSetSha256": _sha256(payload / ".work/build_set.txt"),+ "wheels": [{"name": w.name, "sha256": _sha256(w)} for w in wheels],+ }+ (payload / "index.json").write_text(json.dumps(index, indent=2) + "\n", encoding="utf-8")+ (payload / "SHA256SUMS").write_text(+ "".join(f"{w['sha256']} {w['name']}\n" for w in index["wheels"]),+ encoding="utf-8",+ )+++def is_usable(payload: Path, identity: dict[str, str]) -> bool:+ try:+ index = json.loads((payload / "index.json").read_text(encoding="utf-8"))+ if index["schemaVersion"] != 2 or index["inputs"] != identity:+ return False+ if index["resolvedSha256"] != _sha256(payload / ".work/resolved.txt"):+ return False+ if index["buildSetSha256"] != _sha256(payload / ".work/build_set.txt"):+ return False+ wheels = index["wheels"]+ names = [w["name"] for w in wheels]+ actual = {w.name for w in (payload / "wheelhouse").glob("*.whl")}+ if not names or len(names) != len(set(names)) or set(names) != actual:+ return False+ for wheel in wheels:+ name = wheel["name"]+ if "/" in name or "\\" in name or name in (".", ".."):+ return False+ path = payload / "wheelhouse" / name+ if path.is_symlink() or _sha256(path) != wheel["sha256"]:+ return False+ return True+ except (OSError, ValueError, KeyError, TypeError):+ return False+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("action", choices=("check", "write"))+ parser.add_argument("--payload", type=Path, required=True)+ parser.add_argument("--repo", type=Path, required=True)+ parser.add_argument("--builder", required=True)+ parser.add_argument("--platform-tag", required=True)+ parser.add_argument("--python-abi", required=True)+ parser.add_argument("--tag", default="")+ args = parser.parse_args()+ identity = build_identity(args.repo, args.builder, args.platform_tag, args.python_abi)+ if args.action == "check":+ return 0 if is_usable(args.payload, identity) else 1+ write_manifest(+ args.payload, identity, tag=args.tag,+ platformTag=args.platform_tag, pythonAbi=args.python_abi,+ )+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tests/pm/test_deb_safety.py b/tests/pm/test_deb_safety.pynew file mode 100644index 00000000000..17b4303c72f--- /dev/null+++ b/tests/pm/test_deb_safety.py@@ -0,0 +1,122 @@+"""DebPackage._safe_untar containment regressions.++A safe extractor must forbid ANY write or chmod outside the staged tree.+The malicious .deb fixtures are real ar+tars built in a temp sandbox and+pointed at an outside SENTINEL file/dir inside the sandbox — never real+user or /etc data. Absolute-symlink rejection runs everywhere; the+symlink-privilege-dependent shapes are host-gated because Windows may lack+symlink privilege (validator-checked before the test bodies create links).+"""++from __future__ import annotations++import io+import os+import tarfile+from pathlib import Path++import pytest++from pm.package import DebPackage, InstallError+++class _P(DebPackage):+ name = "evil-deb"+++def _ar_member(name: str, data: bytes) -> bytes:+ hdr = (+ name.ljust(16).encode()+ + b"0".ljust(12)+ + b"0".ljust(6)+ + b"0".ljust(6)+ + b"100644".ljust(8)+ + str(len(data)).encode().ljust(10)+ + b"`\n"+ )+ pad = b"\n" if len(data) % 2 else b""+ return hdr + data + pad+++def _build_deb(path: Path, members: list[tarfile.TarInfo | tuple[str, bytes]]) -> None:+ """A real ar archive with one data.tar (uncompressed) holding `members`."""+ buf = io.BytesIO()+ with tarfile.open(fileobj=buf, mode="w") as tf:+ for item in members:+ if isinstance(item, tuple):+ name, content = item+ info = tarfile.TarInfo(name)+ info.size = len(content)+ tf.addfile(info, io.BytesIO(content))+ else:+ tf.addfile(item)+ path.write_bytes(+ b"!<arch>\n"+ + _ar_member("debian-binary", b"2.0\n")+ + _ar_member("data.tar", buf.getvalue())+ )+++def _symlink_member(name: str, linkname: str) -> tarfile.TarInfo:+ info = tarfile.TarInfo(name)+ info.type = tarfile.SYMTYPE+ info.linkname = linkname+ info.mode = 0o777+ return info+++def test_absolute_symlink_target_rejected(tmp_path: Path):+ """A member whose symlink target is ABSOLUTE must be refused outright:+ the link points outside the staged tree the moment it is created."""+ deb = tmp_path / "abs-link.deb"+ _build_deb(+ deb,+ [+ _symlink_member("data/data/com.termux/files/usr/bin/tool", "/etc/shadow"),+ ],+ )+ staged = tmp_path / "staged"+ staged.mkdir()+ with pytest.raises(InstallError):+ _P().unpack(deb, staged, "linux-arm64-bionic")+ assert not (staged / "data").exists()++[email protected]("posix")+ "shape",+ ["write-through", "chmod-follow"],+)+def test_symlink_escape_forbidden(tmp_path: Path, shape: str):+ """A symlink planted in the staged tree must never become a path OUT:+ not for a later data member written through it (write-through), and not+ for the final mode-normalization walk following it (chmod-follow)."""+ outside = tmp_path / "outside"+ outside.mkdir()+ sentinel = outside / "sentinel.txt"+ sentinel.write_text("do not touch")+ os.chmod(sentinel, 0o600)++ linkname = str(sentinel if shape == "chmod-follow" else outside)+ members: list = [_symlink_member("link", linkname)]+ if shape == "write-through":+ members.append(("link/evil.txt", b"escaped"))+ else:+ members.append(("regular.txt", b"payload"))+ deb = tmp_path / f"escape-{shape}.deb"+ _build_deb(deb, members)++ staged = tmp_path / "staged"+ staged.mkdir()+ with pytest.raises(InstallError):+ _P().unpack(deb, staged, "linux-arm64-bionic")++ assert sentinel.read_text() == "do not touch", (+ f"{shape}: a staged symlink was followed outside the tree"+ )+ if shape == "chmod-follow":+ assert os.stat(sentinel).st_mode & 0o777 == 0o600, (+ "the mode walk chmod'd a file outside the staged tree"+ )+ if shape == "write-through":+ assert not (outside / "evil.txt").exists()diff --git a/tests/pm/test_stage_only.py b/tests/pm/test_stage_only.pynew file mode 100644index 00000000000..b037a9ca51d--- /dev/null+++ b/tests/pm/test_stage_only.py@@ -0,0 +1,170 @@+"""stage_only / _install regressions: a VALID published entry must never be+deleted (verify() returns '' on success), and stage_only must honor a+same-version hash repin (the entry marker design, like facts' identity).++Everything runs inside a temp HERMES_RUNTIME_DIR sandbox: the store and+facts live under tmp_path, and the lockfile + package registry are faked,+so no network and no real install state is touched.+"""++from __future__ import annotations++import hashlib+import importlib+import json+from pathlib import Path++import pytest++from pm.package import InstallError, Package+from pm.store import Store++ensure_mod = importlib.import_module("pm.ensure")+++class _FakeLockfile:+ def __init__(self, version: str, artifacts: list[dict]):+ self._version = version+ self._artifacts = artifacts++ def version(self, name: str):+ return self._version++ def artifacts(self, name: str, target: str):+ return self._artifacts+++class _FakePackage(Package):+ """unpack() turns the verified archive bytes into one binary file."""++ name = "stage-test"++ def missing_reason(self, target: str):+ return None++ def unpack(self, archive: Path, staged: Path, target: str) -> None:+ staged.mkdir(parents=True, exist_ok=True)+ (staged / "bin").mkdir(exist_ok=True)+ (staged / "bin" / "tool").write_bytes(archive.read_bytes())++ def verify(self, entry: Path, target: str) -> str:+ return "" if (entry / "bin" / "tool").is_file() else "bin/tool missing"+++def _sha(data: bytes) -> str:+ return hashlib.sha256(data).hexdigest()+++def _seed_fetch_cache(store: Store, payload: bytes) -> None:+ """Pre-populate the store's download cache so store.fetch() proves the+ digest from local bytes instead of touching the network."""+ entry = store.entry(f"fetch-{_sha(payload)}")+ entry.mkdir(parents=True)+ (entry / "payload.bin").write_bytes(payload)+++def sandbox(tmp_path, monkeypatch):+ runtime = tmp_path / "runtime"+ monkeypatch.setenv("HERMES_RUNTIME_DIR", str(runtime))+ store = Store(runtime)+ package = _FakePackage()+ monkeypatch.setattr(ensure_mod, "get_package", lambda name: package)+ monkeypatch.setattr(ensure_mod, "_store", lambda: store)+ return store+++def _arm_lock(monkeypatch, artifacts: list[dict]):+ lock = _FakeLockfile("1.0", artifacts)+ monkeypatch.setattr(ensure_mod, "_lockfile", lambda: lock)+ return lock+++TARGET = "linux-arm64-bionic"+ENTRY = "stage-test-1.0-linux-arm64-bionic"+++def test_stage_only_keeps_valid_entry(tmp_path, sandbox, monkeypatch):+ """A published entry that verifies must be returned as-is: the+ verify contract is '' on success, so an inverted predicate here would+ delete and re-fetch a perfectly good entry on every call."""+ payload_a = b"tool-bytes-a"+ _arm_lock(+ monkeypatch,+ [{"url": "https://example.test/tool.deb", "sha256": _sha(payload_a)}],+ )+ _seed_fetch_cache(sandbox, payload_a)++ first = ensure_mod.stage_only("stage-test", TARGET)+ assert (first / "bin" / "tool").read_bytes() == payload_a++ # Mark the published entry: a delete-and-rebuild loses this file.+ (first / "sentinel").write_text("published")++ again = ensure_mod.stage_only("stage-test", TARGET)+ assert again == first+ assert (again / "sentinel").read_text() == "published", (+ "stage_only deleted and rebuilt a VALID published entry"+ )+++def test_install_repairs_unproven_entry_and_records_facts(tmp_path, sandbox, monkeypatch):+ """_install with no matching facts must RE-REALIZE the entry: an+ unproven entry (nothing vouches its bytes came from this pin) is+ fail-closed rebuilt, then facts are recorded. Same shape as the+ test_pm_authority repin repair, driven through _install directly."""+ payload_a = b"tool-bytes-a"+ _arm_lock(+ monkeypatch,+ [{"url": "https://example.test/tool.deb", "sha256": _sha(payload_a)}],+ )+ _seed_fetch_cache(sandbox, payload_a)++ package = ensure_mod.get_package("stage-test")+ facts = ensure_mod._facts()+ store = sandbox+ entry_name = package.store_entry("1.0", TARGET)+ sandbox.entry(entry_name).mkdir(parents=True)+ (sandbox.entry(entry_name) / "bin").mkdir()+ (sandbox.entry(entry_name) / "bin" / "tool").write_bytes(b"stale-bytes")+ (sandbox.entry(entry_name) / "sentinel").write_text("unproven")++ ensure_mod._install(package, ensure_mod._lockfile(), facts, store, TARGET)++ assert (sandbox.entry(entry_name) / "bin" / "tool").read_bytes() == payload_a, (+ "_install kept an entry nothing proved against the pin"+ )+ assert not (sandbox.entry(entry_name) / "sentinel").exists()+ recorded = facts.get("stage-test")+ assert recorded and recorded["version"] == "1.0"+++def test_stage_only_repin_same_version_rebuilds(tmp_path, sandbox, monkeypatch):+ """Repinning the SAME version to a different sha256 must rebuild the+ staged entry: without an entry marker the stale bytes are handed back."""+ payload_a = b"tool-bytes-a"+ payload_b = b"tool-bytes-b-repin"+ assert payload_a != payload_b++ _arm_lock(+ monkeypatch,+ [{"url": "https://example.test/tool.deb", "sha256": _sha(payload_a)}],+ )+ _seed_fetch_cache(sandbox, payload_a)+ first = ensure_mod.stage_only("stage-test", TARGET)+ assert (first / "bin" / "tool").read_bytes() == payload_a++ # Repin: same version, new digest.+ _arm_lock(+ monkeypatch,+ [{"url": "https://example.test/tool.deb", "sha256": _sha(payload_b)}],+ )+ _seed_fetch_cache(sandbox, payload_b)+ repinned = ensure_mod.stage_only("stage-test", TARGET)+ assert (repinned / "bin" / "tool").read_bytes() == payload_b, (+ "stage_only returned stale bytes after a same-version hash repin"+ )++ # And the rebuilt entry is again idempotent.+ stable = ensure_mod.stage_only("stage-test", TARGET)+ assert (stable / "bin" / "tool").read_bytes() == payload_bdiff --git a/tests/test_pm_bionic.py b/tests/test_pm_bionic.pyindex a99d36d6e02..94e1b962304 100644--- a/tests/test_pm_bionic.py+++ b/tests/test_pm_bionic.py@@ -174,6 +174,28 @@ def test_python_bionic_verify_is_file_evidence(tmp_path: Path):assert "missing" in py.verify(empty, "linux-arm64-bionic")+def test_bionic_binary_and_env_contract(tmp_path: Path):+ """On bionic, _BionicDebArm.binary() must return the staged deb's main+ binary path (file evidence, no exec), so the base Package.env contract+ exposes the tool through PATH like every other pm package."""+ from pm.registry import get_package++ for name in ("uv", "python", "node"):+ pkg = get_package(name)+ entry = tmp_path / name+ main = entry / pkg.prefix_rel / pkg.main_rel("linux-arm64-bionic")+ main.parent.mkdir(parents=True)+ main.write_bytes(b"bionic-elf")++ binary = pkg.binary(entry, "linux-arm64-bionic")+ assert binary == main, f"{name}.binary() on bionic: {binary}"++ env = pkg.env(entry, "linux-arm64-bionic")+ assert env.get("PATH") == [str(main.parent)], (+ f"{name}.env() on bionic does not follow the Package.env PATH contract"+ )++def test_stage_only_does_not_record_host_facts(tmp_path, monkeypatch):"""stage_only publishes the entry but must not touch this machine'sinstalled facts -- the fact slot belongs to the HOST target."""diff --git a/tests/test_stage_apt_repo.py b/tests/test_stage_apt_repo.pyindex 4326c8511e5..b3a9b0451c9 100644--- a/tests/test_stage_apt_repo.py+++ b/tests/test_stage_apt_repo.py@@ -1,9 +1,18 @@-"""Tests for scripts/termux/stage_apt_repo.py — stdlib + pytest, no network, no gpg."""+"""Tests for scripts/termux/stage_apt_repo.py — stdlib + pytest, no network.++GPG tests generate a throwaway key inside a temp GNUPGHOME and never touch+the invoking user's keyring; passphrase material never appears in test+output (no secret logging).+"""import gzipimport io+import os+import shutil+import subprocessimport sysimport tarfile+import tempfilefrom pathlib import Pathimport pytest@@ -14,6 +23,8 @@ sys.path.insert(0, str(SCRIPTS))import stage_apt_repo # noqa: E402+GPG_PRESENT = shutil.which("gpg") is not None+def make_deb(path: Path, package: str, version: str, arch: str = "aarch64", compression: str = "gz") -> None:"""Build a minimal .deb (ar archive with control.tar.gz) using stdlib only."""@@ -206,3 +217,272 @@ def test_signing_invoked_when_gpg_and_key_present(tmp_path, monkeypatch):assert release_path == str(out / "dists" / "hermes-stable" / "Release")assert kf == str(keyfile)assert (out / "dists" / "hermes-stable" / "InRelease").exists()+++# ---------------------------------------------------------------------------+# deb822 record separation (multiversion Packages correctness)+# ---------------------------------------------------------------------------++def _stanza_count(packages_text: str) -> int:+ return len([s for s in packages_text.split("\n\n") if s.strip()])+++def test_multiversion_packages_records_are_blank_line_separated(tmp_path):+ """Multiple versions of one package must be separate deb822 records:+ apt splits records on blank lines, so a missing blank line merges two+ versions into one garbled stanza and drops the later one."""+ pool = tmp_path / "pool-in"+ pool.mkdir()+ make_deb(pool / "a.deb", "hermes-agent", "1.2.3~canary.20260901000000-1")+ make_deb(pool / "b.deb", "hermes-agent", "1.2.3-1")+ out = tmp_path / "repo"+ assert stage_apt_repo.main(+ ["--pool", str(pool), "--out", str(out), "--suite", "hermes-canary"]+ ) == 3 # staged unsigned++ text = (out / "dists" / "hermes-canary" / "main" / "binary-aarch64" / "Packages").read_text()+ assert _stanza_count(text) == 2+ assert "Version: 1.2.3~canary.20260901000000-1\n" in text+ assert "Version: 1.2.3-1\n" in text+ # each stanza carries its own checksum+ assert text.count("SHA256: ") == 2+ # the repo's own published-set parser agrees (it feeds immutability)+ published = stage_apt_repo.existing_published(out, "hermes-canary")+ assert published == {+ ("hermes-agent", "1.2.3~canary.20260901000000-1"),+ ("hermes-agent", "1.2.3-1"),+ }+++# ---------------------------------------------------------------------------+# Real-GPG behavioral tests (throwaway key in a temp GNUPGHOME)+# ---------------------------------------------------------------------------++def _generate_test_key(home: Path, passphrase: str = "") -> str:+ """Generate a throwaway ed25519 signing key inside `home` and return+ its fingerprint. Uses the production _gpg_run wrapper."""+ stage_apt_repo._gpg_run(+ home,+ ["--quick-generate-key", "Hermes APT Test <[email protected]>",+ "ed25519", "sign", "never"],+ passphrase=passphrase,+ )+ listing = stage_apt_repo._gpg_run(+ home, ["--with-colons", "--list-secret-keys"]+ ).stdout.decode("utf-8", "replace")+ fprs = [line.split(":")[9] for line in listing.splitlines() if line.startswith("fpr:")]+ assert len(set(fprs)) == 1+ return fprs[0]+++def _export_secret_key(home: Path, fpr: str, passphrase: str = "") -> bytes:+ return stage_apt_repo._gpg_run(+ home, ["--armor", "--export-secret-keys", fpr], passphrase=passphrase+ ).stdout+++def _independent_gpgv_verify(keyring_home: Path, *args: Path) -> subprocess.CompletedProcess:+ """Verify with gpgv in a SEPARATE keyring that holds only the published+ public key — the same position a real device is in."""+ kr = stage_apt_repo._gpg_homedir_arg(keyring_home)+ return subprocess.run(+ ["gpgv", "--homedir", kr, "--keyring", f"{kr}/pubring.kbx",+ *[str(a) for a in args]],+ capture_output=True,+ )+++def short_home():+ """gpg homedirs must be SHORT: the agent's AF_UNIX socket lives inside+ the homedir and Windows AF_UNIX paths cap around ~107 chars — pytest's+ tmp_path tree is longer than that, so key/verify homes get their own+ mkdtemp at the temp root (this is also how production creates its+ staging home)."""+ made = []+ def make(prefix: str = "apt-test-gnupg-") -> Path:+ d = Path(tempfile.mkdtemp(prefix=prefix))+ made.append(d)+ return d+ yield make+ for d in made:+ shutil.rmtree(d, ignore_errors=True)+++def tracked_gpg_argv(monkeypatch):+ """Record every argv the stager hands to subprocess.run so tests can+ assert isolation (explicit --homedir) and no secret in argv."""+ real_run = stage_apt_repo.subprocess.run+ argvs = []+ def spy(args, **kwargs):+ argvs.append([str(a) for a in args])+ return real_run(args, **kwargs)+ monkeypatch.setattr(stage_apt_repo.subprocess, "run", spy)+ return argvs++[email protected](not GPG_PRESENT, reason="gpg binary not available")+def test_real_gpg_signs_and_published_public_key_verifies(tmp_path, monkeypatch, tracked_gpg_argv, short_home):+ """Full behavior: a staged repo signs in an isolated temp GNUPGHOME, and+ InRelease + detached Release.gpg verify as GOOD signatures using ONLY+ the published key.asc (independent gpgv keyring)."""+ monkeypatch.delenv("TERMUX_APT_GPG_PASSPHRASE", raising=False)+ kh = short_home()+ fpr = _generate_test_key(kh)+ stage_apt_repo._gpg_run(+ kh, ["--quick-add-key", fpr, "ed25519", "sign", "never"], passphrase="",+ )+ keyfile = tmp_path / "signing.asc"+ keyfile.write_bytes(_export_secret_key(kh, fpr))++ pool = tmp_path / "pool-in"+ pool.mkdir()+ make_deb(pool / "h.deb", "hermes-agent", "1.2.3-1")+ out = tmp_path / "repo"+ assert stage_apt_repo.main(+ ["--pool", str(pool), "--out", str(out),+ "--suite", "hermes-nightly", "--gpg-key-file", str(keyfile)]+ ) == 0++ dists = out / "dists" / "hermes-nightly"+ assert (dists / "InRelease").exists()+ assert (dists / "Release.gpg").exists()++ # Isolation: every gpg invocation carried an explicit --homedir inside+ # the system temp dir, never the user's default keyring.+ temp_root = stage_apt_repo._gpg_homedir_arg(Path(tempfile.gettempdir()))+ for argv in tracked_gpg_argv:+ assert "--homedir" in argv, f"gpg called without --homedir: {argv}"+ homedir = argv[argv.index("--homedir") + 1]+ assert homedir.startswith(temp_root), homedir++ vr = short_home(prefix="apt-test-verify-")+ stage_apt_repo._gpg_run(+ vr, ["--import"], stdin=(out / "key.asc").read_bytes()+ )+ r = _independent_gpgv_verify(vr, dists / "InRelease")+ assert r.returncode == 0, r.stderr.decode()+ assert b"Good signature" in r.stderr+ r = _independent_gpgv_verify(vr, dists / "Release.gpg", dists / "Release")+ assert r.returncode == 0, r.stderr.decode()+ assert b"Good signature" in r.stderr++ # The staging keyring was deleted afterwards.+ staging_homes = {+ argv[argv.index("--homedir") + 1]+ for argv in tracked_gpg_argv+ if "apt-stage-gnupg-" in argv[argv.index("--homedir") + 1]+ }+ assert staging_homes+ for home in staging_homes:+ native = Path(home)+ if os.name == "nt" and home.startswith("/") and home[2:3] == "/":+ native = Path(home[1] + ":/" + home[3:])+ assert not native.exists()++[email protected](not GPG_PRESENT, reason="gpg binary not available")+def test_real_gpg_passphrase_reaches_gpg_via_stdin_never_argv(tmp_path, monkeypatch, tracked_gpg_argv, short_home):+ """A passphrase-protected signing key works (env var -> stdin fd), and+ the passphrase never appears in any spawned argv."""+ secret_pass = "correct-horse-battery-staple"+ monkeypatch.setenv("TERMUX_APT_GPG_PASSPHRASE", secret_pass)+ kh = short_home()+ fpr = _generate_test_key(kh, passphrase=secret_pass)+ keyfile = tmp_path / "signing.asc"+ keyfile.write_bytes(_export_secret_key(kh, fpr, passphrase=secret_pass))++ pool = tmp_path / "pool-in"+ pool.mkdir()+ make_deb(pool / "h.deb", "hermes-agent", "1.2.3-1")+ out = tmp_path / "repo"+ assert stage_apt_repo.main(+ ["--pool", str(pool), "--out", str(out),+ "--suite", "hermes-canary", "--gpg-key-file", str(keyfile)]+ ) == 0++ for argv in tracked_gpg_argv:+ assert secret_pass not in " ".join(argv), "passphrase leaked into argv"++ dists = out / "dists" / "hermes-canary"+ vr = short_home(prefix="apt-test-verify-")+ stage_apt_repo._gpg_run(vr, ["--import"], stdin=(out / "key.asc").read_bytes())+ r = _independent_gpgv_verify(vr, dists / "InRelease")+ assert r.returncode == 0, r.stderr.decode()+ r = _independent_gpgv_verify(vr, dists / "Release.gpg", dists / "Release")+ assert r.returncode == 0, r.stderr.decode()++[email protected](not GPG_PRESENT, reason="gpg binary not available")+def test_real_gpg_tampered_metadata_fails_closed(tmp_path, monkeypatch, short_home):+ """Fail-closed contract: verification of the signed artifacts is done+ with the signing key, and any post-sign mutation of the Release is+ rejected instead of published."""+ monkeypatch.delenv("TERMUX_APT_GPG_PASSPHRASE", raising=False)+ kh = short_home()+ fpr = _generate_test_key(kh)+ stage_apt_repo._gpg_run(+ kh, ["--quick-add-key", fpr, "ed25519", "sign", "never"], passphrase="",+ )+ keyfile = tmp_path / "signing.asc"+ keyfile.write_bytes(_export_secret_key(kh, fpr))++ pool = tmp_path / "pool-in"+ pool.mkdir()+ make_deb(pool / "h.deb", "hermes-agent", "1.2.3-1")+ out = tmp_path / "repo"+ assert stage_apt_repo.main(+ ["--pool", str(pool), "--out", str(out),+ "--suite", "hermes-stable", "--gpg-key-file", str(keyfile)]+ ) == 0++ dists = out / "dists" / "hermes-stable"+ # untouched artifacts verify with the exact signing fingerprint+ stage_apt_repo._verify_signature(kh, fpr, dists / "InRelease", None)+ stage_apt_repo._verify_signature(kh, fpr, dists / "Release.gpg", dists / "Release")++ # tamper with the signed Release -> detached sig no longer validates+ # (gpg exits non-zero during re-verification -> fail closed)+ release_path = dists / "Release"+ release_path.write_text(release_path.read_text() + "Architectures: amd64\n")+ with pytest.raises(stage_apt_repo.StageError):+ stage_apt_repo._verify_signature(kh, fpr, dists / "Release.gpg", release_path)++ # and gpgv agrees independently+ vr = short_home(prefix="apt-test-verify-")+ stage_apt_repo._gpg_run(vr, ["--import"], stdin=(out / "key.asc").read_bytes())+ assert _independent_gpgv_verify(vr, dists / "Release.gpg", release_path).returncode != 0++[email protected](not GPG_PRESENT, reason="gpg binary not available")+def test_multi_key_import_is_rejected_not_first_key_used(tmp_path, monkeypatch, capsys, short_home):+ """A supplied key file containing MORE THAN ONE secret key must fail+ closed — the stager must never silently sign with the first key."""+ monkeypatch.delenv("TERMUX_APT_GPG_PASSPHRASE", raising=False)+ kh = short_home()+ fpr1 = _generate_test_key(kh)+ kh2 = short_home()+ fpr2 = _generate_test_key(kh2)+ assert fpr1 != fpr2+ keyfile = tmp_path / "two-keys.asc"+ keyfile.write_bytes(+ _export_secret_key(kh, fpr1) + _export_secret_key(kh2, fpr2)+ )++ pool = tmp_path / "pool-in"+ pool.mkdir()+ make_deb(pool / "h.deb", "hermes-agent", "1.2.3-1")+ out = tmp_path / "repo"+ with pytest.raises(SystemExit) as ei:+ stage_apt_repo.main(+ ["--pool", str(pool), "--out", str(out),+ "--suite", "hermes-stable", "--gpg-key-file", str(keyfile)]+ )+ assert ei.value.code == 2+ assert "secret keys" in capsys.readouterr().err+ # nothing was signed or published+ dists = out / "dists" / "hermes-stable"+ if dists.exists():+ assert not (dists / "InRelease").exists()+ assert not (dists / "Release.gpg").exists()diff --git a/tests/test_termux_launchers.py b/tests/test_termux_launchers.pynew file mode 100644index 00000000000..033425a3f96--- /dev/null+++ b/tests/test_termux_launchers.py@@ -0,0 +1,72 @@+"""Run generated launchers with a real interpreter and captured entrypoint."""+from __future__ import annotations++import json+import os+from pathlib import Path+import shutil+import subprocess+import sys++import pytest++from scripts.termux.launchers import write_launchers++[email protected]("posix")+def test_launchers_forward_arguments_and_export_payload_environment(tmp_path):+ payload = tmp_path / "payload with spaces"+ (payload / "venv/bin").mkdir(parents=True)+ (payload / "venv/bin/python").symlink_to(sys.executable)+ (payload / "app").mkdir()+ (payload / "app/capture_entry.py").write_text(+ "import json, os, sys\n"+ "def main():\n"+ " print(json.dumps({'argv': sys.argv[1:], 'env': {k: os.environ.get(k) for k in "+ "['HERMES_NODE', 'HERMES_PYTHON', 'HERMES_RUNTIME_DIR', 'PYTHONPATH', 'PYTHONHOME', 'PYTHONPYCACHEPREFIX']}}))\n",+ encoding="utf-8",+ )+ entries = {name: "capture_entry:main" for name in ("hermes", "hermes-agent", "hermes-acp")}+ write_launchers(payload, entries)+ bin_dir = tmp_path / "prefix/bin"+ bin_dir.mkdir(parents=True)+ for name in entries:+ link = bin_dir / name+ link.symlink_to(os.path.relpath(payload / "bin" / name, bin_dir))+ result = subprocess.run(+ [shutil.which("sh"), str(link), "one two", "$(not-executed)", ""],+ cwd=tmp_path, check=True, capture_output=True, text=True,+ env={**os.environ, "PYTHONHOME": "/does-not-exist", "PYTHONPATH": "/foreign"},+ )+ data = json.loads(result.stdout)+ assert data["argv"] == ["one two", "$(not-executed)", ""]+ env = data["env"]+ assert Path(env["HERMES_PYTHON"]).resolve() == Path(sys.executable).resolve()+ assert Path(env["HERMES_NODE"]) == payload / "tools/node/data/data/com.termux/files/usr/bin/node"+ assert Path(env["HERMES_RUNTIME_DIR"]) == payload / "tools"+ assert Path(env["PYTHONPATH"]) == payload / "app"+ assert env["PYTHONHOME"] is None+ assert not Path(env["PYTHONPYCACHEPREFIX"]).is_relative_to(payload)++[email protected]("posix")+def test_postinst_refuses_foreign_path_and_prerm_preserves_it(tmp_path):+ from scripts.termux.launchers import write_maintainer_scripts++ control = tmp_path / "DEBIAN"+ control.mkdir()+ write_maintainer_scripts(control, ["hermes"])+ prefix = tmp_path / "prefix"+ bin_dir = prefix / "bin"+ bin_dir.mkdir(parents=True)+ link = bin_dir / "hermes"+ env = {**os.environ, "PREFIX": str(prefix)}+ command = [shutil.which("sh"), str(control / "postinst"), "configure"]+ subprocess.run(command, check=True, env=env)+ assert os.readlink(link) == "../lib/hermes-agent/bin/hermes"+ subprocess.run(command, check=True, env=env)+ link.unlink()+ link.write_text("foreign launcher", encoding="utf-8")+ assert subprocess.run(command, env=env).returncode != 0+ subprocess.run([shutil.which("sh"), str(control / "prerm"), "remove"], check=True, env=env)+ assert link.read_text(encoding="utf-8") == "foreign launcher"diff --git a/tests/test_termux_python_linkage.py b/tests/test_termux_python_linkage.pyindex 00de9bbbaba..11c76e1e730 100644--- a/tests/test_termux_python_linkage.py+++ b/tests/test_termux_python_linkage.py@@ -14,7 +14,6 @@ from scripts.termux import python_linkage@pytest.mark.platforms("linux")def test_python_symbols_gain_an_explicit_library_dependency(tmp_path):- from ctypes import _endianimport _ctypeslibrary = Path(sysconfig.get_config_var("LIBDIR")) / sysconfig.get_config_var("LDLIBRARY")diff --git a/tests/test_termux_runtime_libs.py b/tests/test_termux_runtime_libs.pynew file mode 100644index 00000000000..63e42bfa10c--- /dev/null+++ b/tests/test_termux_runtime_libs.py@@ -0,0 +1,215 @@+"""Tests for scripts/termux/stage_runtime_libs.py — cache correctness.++No filesystem mocks: a real tiny .deb fixture (ar archive + data.tar) is+served over loopback HTTP and fetched through pm's hardened Download,+then unpacked through pm's DebPackage — the same production path.+"""+from __future__ import annotations++import hashlib+import io+import json+import tarfile+import threading+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from pathlib import Path++import pytest++import sys++REPO_ROOT = Path(__file__).resolve().parent.parent+sys.path.insert(0, str(REPO_ROOT))+sys.path.insert(0, str(REPO_ROOT / "scripts" / "termux"))++import stage_runtime_libs as srl # noqa: E402++PREFIX = srl.PREFIX_REL+++# ---------------------------------------------------------------- fixtures++def _ar_header(name: str, size: int) -> bytes:+ hdr = name.ljust(16).encode()+ hdr += b"0".ljust(12) # mtime+ hdr += b"0".ljust(6) # uid+ hdr += b"0".ljust(6) # gid+ hdr += b"644".ljust(8) # mode+ hdr += str(size).ljust(10).encode()+ hdr += b"`\n"+ assert len(hdr) == 60+ return hdr+++def _build_deb(path: Path, lib_name: str, content: bytes) -> None:+ """A minimal but real .deb: ar{debian-binary, control.tar.gz, data.tar}+ with data.tar carrying <PREFIX>/lib/<lib_name>."""+ data = io.BytesIO()+ with tarfile.open(fileobj=data, mode="w") as tf:+ lib_dir = f"{PREFIX}/lib/"+ ti = tarfile.TarInfo(lib_dir)+ ti.type = tarfile.DIRTYPE+ ti.mode = 0o755+ tf.addfile(ti)+ payload = f"FAKE-ELF {lib_name}\n".encode() + content+ ti = tarfile.TarInfo(lib_dir + lib_name)+ ti.size = len(payload)+ ti.mode = 0o755+ tf.addfile(ti, io.BytesIO(payload))++ control = io.BytesIO()+ with tarfile.open(fileobj=control, mode="w") as tf:+ stanza = f"Package: pkg-{lib_name}\nVersion: 1.0\n".encode()+ ti = tarfile.TarInfo("control")+ ti.size = len(stanza)+ tf.addfile(ti, io.BytesIO(stanza))++ members = [+ (b"debian-binary/", b"2.0\n"),+ (b"control.tar.gz/", control.getvalue()),+ (b"data.tar/", data.getvalue()),+ ]+ out = b"!<arch>\n"+ for name, body in members:+ out += _ar_header(name.decode().rstrip("/"), len(body))+ out += body+ if len(body) % 2:+ out += b"\n"+ path.write_bytes(out)+++class _Server:+ """Serves files from a dir over loopback HTTP."""++ def __init__(self, root: Path) -> None:+ self.root = root++ class H(BaseHTTPRequestHandler):+ def do_GET(self):+ f = self.server.root / self.path.lstrip("/") # type: ignore[attr-defined]+ if not f.is_file():+ self.send_error(404)+ return+ body = f.read_bytes()+ self.send_response(200)+ self.send_header("Content-Length", str(len(body)))+ self.send_header("Accept-Ranges", "none")+ self.end_headers()+ self.wfile.write(body)++ def log_message(self, *a):+ pass++ self.httpd = ThreadingHTTPServer(("127.0.0.1", 0), H)+ self.httpd.root = root # type: ignore[attr-defined]+ self.thread = threading.Thread(target=self.httpd.serve_forever, daemon=True)+ self.thread.start()++ @property+ def url(self) -> str:+ host, port = self.httpd.server_address[:2]+ return f"http://{host}:{port}"++ def stop(self):+ self.httpd.shutdown()+ self.httpd.server_close()+++def lib_source(tmp_path: Path):+ """Two packages; libb.so shared by both (identical bytes). Returns+ (server, table, files) where files maps staged soname -> bytes."""+ src = tmp_path / "debs"+ src.mkdir()+ shared = b"shared-impl-v1"+ _build_deb(src / "liba.deb", "liba.so", b"impl-a")+ _build_deb(src / "libb.deb", "libb.so", shared)+ _build_deb(src / "libc.deb", "libb.so", shared) # identical collision++ server = _Server(src)+ table = {+ "liba": {"url": f"{server.url}/liba.deb",+ "sha256": hashlib.sha256((src / "liba.deb").read_bytes()).hexdigest(),+ "version": "1.0"},+ "libb": {"url": f"{server.url}/libb.deb",+ "sha256": hashlib.sha256((src / "libb.deb").read_bytes()).hexdigest(),+ "version": "2.0"},+ "libc": {"url": f"{server.url}/libc.deb",+ "sha256": hashlib.sha256((src / "libc.deb").read_bytes()).hexdigest(),+ "version": "3.0"},+ }+ yield server, table+ server.stop()+++def _stage(tmp_path: Path, table: dict) -> Path:+ return srl.stage(tmp_path / "payload", table)+++# ------------------------------------------------------------------ tests+[email protected]("corruption", ["missing", "extra", "stale"])+def test_stage_cache_correctness(tmp_path, lib_source, corruption):+ """Initial stage, true cache hit with the source gone, and rebuild on+ missing / extra / corrupted output."""+ server, table = lib_source+ out = _stage(tmp_path, table)+ names = {"liba.so", "libb.so"}+ assert {p.name for p in out.glob("*.so*")} == names+ manifest = json.loads(out.parent.joinpath("manifest.json").read_text())++ # True cache hit: source deleted, no downloads possible.+ server.stop()+ for p in (tmp_path / "payload" / ".work").rglob("*"):+ pass+ import shutil+ shutil.rmtree(tmp_path / "payload" / ".work")+ assert srl.stage(tmp_path / "payload", table) == out+ assert {p.name for p in out.glob("*.so*")} == names++ # Corrupt the cache and restore the source so a rebuild is possible.+ if corruption == "missing":+ (out / "liba.so").unlink()+ elif corruption == "extra":+ (out / "libjunk.so").write_bytes(b"bogus")+ else:+ (out / "libb.so").write_bytes(b"corrupted bytes")++ src = tmp_path / "debs"+ server2 = _Server(src)+ for name in table:+ table[name]["url"] = f"{server2.url}/{name}.deb"+ try:+ result = srl.stage(tmp_path / "payload", table)+ assert result == out+ finally:+ server2.stop()+ assert {p.name for p in out.glob("*.so*")} == names+ for name in names:+ assert hashlib.sha256((out / name).read_bytes()).hexdigest() == \+ manifest["files"][name]+++def test_collision_identical_ok_conflicting_raises(tmp_path, lib_source):+ """Co-installed packages may share a soname only with identical bytes."""+ server, table = lib_source+ out = _stage(tmp_path, table)+ # libb + libc both ship libb.so with identical bytes: merged once.+ assert (out / "libb.so").read_bytes().startswith(b"FAKE-ELF libb.so")++ # Now a conflicting rebuild: same soname, different bytes.+ _build_deb(tmp_path / "debs" / "libc.deb", "libb.so", b"DIFFERENT-IMPL")+ table["libc"]["sha256"] = hashlib.sha256(+ (tmp_path / "debs" / "libc.deb").read_bytes()).hexdigest()++ # Force a miss: current manifest no longer validates for libc's bytes.+ with pytest.raises(Exception):+ srl.stage(tmp_path / "payload", table)+++def test_main_thin_caller(tmp_path):+ """main() is a thin wrapper over stage() reading runtime_libs.json."""+ import importlib+ mod = importlib.reload(srl)+ assert callable(mod.stage)+ assert callable(mod.main)diff --git a/tests/test_termux_wheelhouse_cache.py b/tests/test_termux_wheelhouse_cache.pynew file mode 100644index 00000000000..547d1c8887f--- /dev/null+++ b/tests/test_termux_wheelhouse_cache.py@@ -0,0 +1,58 @@+"""A restored cache is usable only for the exact proven build inputs."""+from __future__ import annotations++import json+from pathlib import Path++import pytest++from scripts.termux import wheelhouse_cache+++def cache_tree(tmp_path: Path) -> tuple[Path, dict[str, str]]:+ payload = tmp_path / "payload"+ wheelhouse = payload / "wheelhouse"+ work = payload / ".work"+ wheelhouse.mkdir(parents=True)+ work.mkdir()+ (wheelhouse / "example-1.0-py3-none-any.whl").write_bytes(b"cache artifact")+ (work / "resolved.txt").write_text("example\t==1.0\t\n", encoding="utf-8")+ (work / "build_set.txt").write_text("example\n", encoding="utf-8")+ identity = {"lock": "lock-a", "python": "python-a", "builder": "image-a"}+ return payload, identity+++def test_cache_rejects_changed_inputs_and_modified_outputs(tmp_path):+ payload, identity = cache_tree(tmp_path)+ wheelhouse_cache.write_manifest(payload, identity)+ assert wheelhouse_cache.is_usable(payload, identity)+ for key in identity:+ assert not wheelhouse_cache.is_usable(payload, {**identity, key: "changed"})+ artifact = next((payload / "wheelhouse").glob("*.whl"))+ artifact.write_bytes(b"corrupt artifact")+ assert not wheelhouse_cache.is_usable(payload, identity)++[email protected]("damage", ["empty", "missing", "extra", "requirements", "build-set", "traversal", "malformed"])+def test_cache_rejects_incomplete_or_inconsistent_manifests(tmp_path, damage):+ payload, identity = cache_tree(tmp_path)+ wheelhouse_cache.write_manifest(payload, identity)+ manifest_path = payload / "index.json"+ manifest = json.loads(manifest_path.read_text(encoding="utf-8"))+ if damage == "empty":+ manifest["wheels"] = []+ manifest_path.write_text(json.dumps(manifest), encoding="utf-8")+ elif damage == "missing":+ next((payload / "wheelhouse").glob("*.whl")).unlink()+ elif damage == "extra":+ (payload / "wheelhouse/foreign-9.0-py3-none-any.whl").write_bytes(b"foreign")+ elif damage == "requirements":+ (payload / ".work/resolved.txt").write_text("other\t==9.0\t\n", encoding="utf-8")+ elif damage == "build-set":+ (payload / ".work/build_set.txt").unlink()+ elif damage == "traversal":+ manifest["wheels"][0]["name"] = "../outside.whl"+ manifest_path.write_text(json.dumps(manifest), encoding="utf-8")+ else:+ manifest_path.write_text("{broken", encoding="utf-8")+ assert not wheelhouse_cache.is_usable(payload, identity)