The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(pm): repair Node libatomic at install boundary
JoaoMarcos44ad6760a4169f
diff --git a/pm/install.py b/pm/install.pyindex 434fc812e1e..50208660424 100644--- a/pm/install.py+++ b/pm/install.py@@ -448,6 +448,8 @@ def _install(if progress is not None:progress("verify", 0, 0, "")reason = package.verify(staged, target)+ if reason:+ reason = package.repair_staged_verification(staged, target, reason)if reason:raise InstallError(package.name, f"staged entry failed verification: {reason}")if facts is None:diff --git a/pm/libatomic.py b/pm/libatomic.pynew file mode 100644index 00000000000..752fcef061b--- /dev/null+++ b/pm/libatomic.py@@ -0,0 +1,126 @@+"""Install the host libatomic package required by official Linux Node.++This module is intentionally called only from PM's staged-install repair hook.+Package verification itself remains diagnostic and side-effect free.+"""++from __future__ import annotations++import os+import shlex+import shutil+import subprocess+from pathlib import Path+++_INSTALLERS: dict[str, tuple[str, ...]] = {+ "apt-get": ("apt-get", "install", "-y", "libatomic1"),+ "dnf": ("dnf", "install", "-y", "libatomic"),+ "yum": ("yum", "install", "-y", "libatomic"),+ "zypper": ("zypper", "--non-interactive", "install", "libatomic1"),+ "pacman": ("pacman", "-S", "--needed", "--noconfirm", "gcc-libs"),+ "apk": ("apk", "add", "libatomic"),+}++_DEBIAN = {"debian", "ubuntu", "linuxmint", "pop", "raspbian", "kali", "elementary"}+_RPM = {"rhel", "fedora", "centos", "rocky", "almalinux", "ol", "oracle", "amzn"}+_ARCH = {"arch", "manjaro", "endeavouros", "garuda", "artix"}+++def _release_tokens() -> set[str]:+ fields: dict[str, str] = {}+ for path in (Path("/etc/os-release"), Path("/usr/lib/os-release")):+ try:+ text = path.read_text(encoding="utf-8-sig")+ except OSError:+ continue+ for raw in text.splitlines():+ line = raw.strip()+ if not line or line.startswith("#") or "=" not in line:+ continue+ key, value = line.split("=", 1)+ fields[key] = value.strip().strip('"').strip("'")+ break+ blob = f"{fields.get('ID', '')} {fields.get('ID_LIKE', '')}".lower()+ return set(blob.replace(",", " ").split())+++def _manager_order(tokens: set[str]) -> tuple[str, ...]:+ if tokens & _DEBIAN:+ return ("apt-get",)+ if tokens & _RPM:+ return ("dnf", "yum")+ if any("suse" in token or token.startswith("sles") for token in tokens):+ return ("zypper",)+ if tokens & _ARCH:+ return ("pacman",)+ if "alpine" in tokens:+ return ("apk",)+ return ("dnf", "yum", "apt-get", "zypper", "pacman", "apk")+++def _host_install_command() -> tuple[str, ...] | None:+ for manager in _manager_order(_release_tokens()):+ if shutil.which(manager):+ return _INSTALLERS[manager]+ return None+++def _is_root() -> bool:+ return bool(hasattr(os, "geteuid") and os.geteuid() == 0)+++def _command_plan(command: tuple[str, ...]) -> tuple[list[str] | None, str, str]:+ """Return auto-repair argv, its display form, and a runnable manual remedy.++ Host-package repair runs while PM owns its publication lock, so it must never+ wait on an interactive privilege prompt. Non-root repair therefore uses+ ``sudo -n`` even on a TTY. The manual remedy may use normal ``sudo``+ outside that lock. If sudo is unavailable, don't advertise it at all.+ """+ if _is_root():+ argv = list(command)+ shown = shlex.join(argv)+ return argv, shown, shown+ sudo = shutil.which("sudo")+ if sudo:+ argv = [sudo, "-n", *command]+ return argv, shlex.join(["sudo", "-n", *command]), shlex.join(["sudo", *command])+ return None, "", f"as root: {shlex.join(command)}"+++def try_install_libatomic() -> tuple[bool, str]:+ """Try the distro-native libatomic package; return (attempt_succeeded, hint).++ Success means the package-manager command completed successfully. The Node+ smoke probe remains the authority and is always repeated by the caller.+ """+ command = _host_install_command()+ if command is None:+ return (+ False,+ "official Node needs libatomic.so.1; install the distro package that provides it and rerun",+ )++ argv, attempt_display, remedy_display = _command_plan(command)+ remedy = f"install the missing runtime library with {remedy_display} and rerun"+ if argv is None:+ return False, remedy++ env = dict(os.environ)+ env.setdefault("DEBIAN_FRONTEND", "noninteractive")+ print(+ f"→ Node needs libatomic.so.1; trying non-interactive {attempt_display}",+ flush=True,+ )+ try:+ result = subprocess.run(+ argv,+ stdin=subprocess.DEVNULL,+ env=env,+ timeout=300,+ check=False,+ )+ except (OSError, subprocess.TimeoutExpired):+ return False, remedy+ return result.returncode == 0, remedydiff --git a/pm/package.py b/pm/package.pyindex a94c0730120..bb8fa8e2902 100644--- a/pm/package.py+++ b/pm/package.py@@ -150,6 +150,17 @@ class Package:return ""return self._binary_reason(binary, entry, target)+ def repair_staged_verification(self, entry: Path, target: str, reason: str) -> str:+ """Install-time remediation for a failed staged verification.++ verify() is also used by read-only inspection paths such as+ hermes pm doctor and must stay side-effect free. The installer+ calls this hook only after a freshly staged entry fails verification.+ Return the remaining failure reason, or an empty string when+ remediation made the staged entry usable.+ """+ return reason+def _binary_reason(self, binary: Path, entry: Path, target: str) -> str:"""'' when the binary is present and arch-plausible on target."""if not binary.is_file():diff --git a/pm/packages.py b/pm/packages.pyindex a8fcfce6c58..1cb4422cab2 100644--- a/pm/packages.py+++ b/pm/packages.py@@ -483,6 +483,24 @@ class Nodejs(_BionicDebArm, BinaryPackage, DebPackage):# lockfile is written rather than selecting glibc bytes on musl.return node_latest_versions()+ def repair_staged_verification(self, entry: Path, target: str, reason: str) -> str:+ """Repair the host library needed by official Linux Node, then re-probe.++ Keep this out of verify(): doctor/status checks call verify and must+ never gain permission to install host packages.+ """+ if target != current_target() or not target.startswith("linux") or "libatomic.so.1" not in reason:+ return reason+ from pm.libatomic import try_install_libatomic++ installed, remedy = try_install_libatomic()+ if installed:+ retried = self.verify(entry, target)+ if "libatomic.so.1" not in retried:+ return retried+ reason = retried+ return reason if not remedy or remedy in reason else f"{reason} — {remedy}"+@registerclass TermuxDocker(Package):diff --git a/tests/pm/test_node_libatomic_install_boundary.py b/tests/pm/test_node_libatomic_install_boundary.pynew file mode 100644index 00000000000..958a93798ab--- /dev/null+++ b/tests/pm/test_node_libatomic_install_boundary.py@@ -0,0 +1,154 @@+"""Regression tests for #124926: libatomic repair belongs to install, not verify."""++from pathlib import Path++import pytest++from pm.packages import Nodejs+++_LOADER = (+ "node: error while loading shared libraries: libatomic.so.1: "+ "cannot open shared object file: No such file or directory"+)+++def _node_script(path: Path, body: str) -> None:+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(body, encoding="utf-8")+ path.chmod(0o755)++[email protected]("posix")+def test_node_verify_remains_read_only_when_libatomic_is_missing(tmp_path, monkeypatch):+ """A diagnostic verify, including pm doctor, must never install host packages."""+ node = tmp_path / "bin" / "node"+ _node_script(node, f'#!/bin/sh\necho "{_LOADER}" >&2\nexit 127\n')+ monkeypatch.setattr("pm.packages.current_target", lambda: "linux-x64")++ def forbidden():+ raise AssertionError("verify() attempted host mutation")++ monkeypatch.setattr("pm.libatomic.try_install_libatomic", forbidden)+ reason = Nodejs().verify(tmp_path, "linux-x64")++ assert "libatomic.so.1" in reason+ assert "exited 127" in reason++[email protected]("posix")+def test_staged_repair_installs_libatomic_then_reprobes(tmp_path, monkeypatch):+ node = tmp_path / "bin" / "node"+ _node_script(node, f'#!/bin/sh\necho "{_LOADER}" >&2\nexit 127\n')+ monkeypatch.setattr("pm.packages.current_target", lambda: "linux-x64")++ calls = {"n": 0}++ def install():+ calls["n"] += 1+ _node_script(node, "#!/bin/sh\necho v26.7.0\n")+ return True, "install with sudo dnf install -y libatomic"++ monkeypatch.setattr("pm.libatomic.try_install_libatomic", install)+ package = Nodejs()+ first = package.verify(tmp_path, "linux-x64")+ repaired = package.repair_staged_verification(tmp_path, "linux-x64", first)++ assert calls["n"] == 1+ assert repaired == ""+++def test_cross_target_staging_never_installs_host_libatomic(tmp_path, monkeypatch):+ monkeypatch.setattr("pm.packages.current_target", lambda: "linux-x64")++ def forbidden():+ raise AssertionError("cross-target stage attempted host mutation")++ monkeypatch.setattr("pm.libatomic.try_install_libatomic", forbidden)+ reason = Nodejs().repair_staged_verification(+ tmp_path,+ "linux-arm64",+ f"bin/node --version exited 127: {_LOADER}",+ )+ assert "libatomic.so.1" in reason++[email protected]("posix")+def test_successful_libatomic_install_does_not_mask_a_new_probe_error(tmp_path, monkeypatch):+ node = tmp_path / "bin" / "node"+ _node_script(node, f'#!/bin/sh\necho "{_LOADER}" >&2\nexit 127\n')+ monkeypatch.setattr("pm.packages.current_target", lambda: "linux-x64")++ def install():+ _node_script(node, "#!/bin/sh\necho different-failure >&2\nexit 23\n")+ return True, "install with sudo dnf install -y libatomic"++ monkeypatch.setattr("pm.libatomic.try_install_libatomic", install)+ package = Nodejs()+ first = package.verify(tmp_path, "linux-x64")+ repaired = package.repair_staged_verification(tmp_path, "linux-x64", first)++ assert "different-failure" in repaired+ assert "libatomic" not in repaired+++def test_almalinux_prefers_dnf_package(monkeypatch):+ from pm import libatomic++ monkeypatch.setattr(libatomic, "_release_tokens", lambda: {"almalinux", "rhel"})+ monkeypatch.setattr(+ libatomic.shutil,+ "which",+ lambda name: f"/usr/bin/{name}" if name in {"dnf", "apt-get"} else None,+ )+ assert libatomic._host_install_command() == ("dnf", "install", "-y", "libatomic")+++def test_nonroot_sudo_is_always_noninteractive(monkeypatch):+ from pm import libatomic++ monkeypatch.setattr(libatomic, "_is_root", lambda: False)+ monkeypatch.setattr(libatomic.shutil, "which", lambda name: "/usr/bin/sudo" if name == "sudo" else None)++ argv, attempt, remedy = libatomic._command_plan(("dnf", "install", "-y", "libatomic"))++ assert argv == ["/usr/bin/sudo", "-n", "dnf", "install", "-y", "libatomic"]+ assert attempt == "sudo -n dnf install -y libatomic"+ assert remedy == "sudo dnf install -y libatomic"+++def test_missing_sudo_remedy_never_advertises_sudo(monkeypatch):+ from pm import libatomic++ monkeypatch.setattr(libatomic, "_is_root", lambda: False)+ monkeypatch.setattr(libatomic, "_host_install_command", lambda: ("dnf", "install", "-y", "libatomic"))+ monkeypatch.setattr(libatomic.shutil, "which", lambda _name: None)++ attempted, remedy = libatomic.try_install_libatomic()++ assert attempted is False+ assert "sudo" not in remedy+ assert "as root: dnf install -y libatomic" in remedy+++def test_auto_repair_never_reads_a_tty(monkeypatch):+ from pm import libatomic++ monkeypatch.setattr(libatomic, "_is_root", lambda: False)+ monkeypatch.setattr(libatomic, "_host_install_command", lambda: ("dnf", "install", "-y", "libatomic"))+ monkeypatch.setattr(libatomic.shutil, "which", lambda name: "/usr/bin/sudo" if name == "sudo" else None)++ captured = {}++ def run(argv, **kwargs):+ captured["argv"] = argv+ captured.update(kwargs)+ return type("Result", (), {"returncode": 1})()++ monkeypatch.setattr(libatomic.subprocess, "run", run)++ attempted, _remedy = libatomic.try_install_libatomic()++ assert attempted is False+ assert captured["argv"][:2] == ["/usr/bin/sudo", "-n"]+ assert captured["stdin"] is libatomic.subprocess.DEVNULL