Skip to content

The agent that grows with you

fix(pm): give text that leaves PM the ordinary spelling of store paths

alt-glitch953a598860e6
diff --git a/pm/build_operations.py b/pm/build_operations.py
index c468a4d481b..a41b49d6b00 100644
--- a/pm/build_operations.py
+++ b/pm/build_operations.py
@@ -7,6 +7,7 @@ from pathlib import Path
import sys
from types import MappingProxyType
+from pm.filesystem import native
from pm.install import InstalledPackage
from pm.lock import Lockfile
from pm.package import InstallError
@@ -127,7 +128,7 @@ def _copy_links(package, entry: Path) -> None:
if path.is_symlink() or is_junction(path):
if (Path(os.readlink(path)).is_absolute() or not path.exists()
or not path.resolve().is_relative_to(entry)):
- raise InstallError(package.name, f"tool copy link escapes entry: {path}")
+ raise InstallError(package.name, f"tool copy link escapes entry: {native(path)}")
@dataclass(frozen=True)
@@ -187,7 +188,9 @@ def verified_tools(names: Sequence[str], *, source_store: Path, target: str,
if ((binary is not None and (not binary.is_file() or not binary.resolve().is_relative_to(entry)))
or facts.env_for(package.name, source_store) != env):
raise InstallError(package.name, "tool source failed verification: binary or environment")
- entries[package.name] = InstalledPackage(entry, version, binary)
+ # The selection leaves PM (bundle scripts compare and execute it): ordinary spelling.
+ entries[package.name] = InstalledPackage(Path(native(entry)), version,
+ Path(native(binary)) if binary is not None else None)
envs.append(env)
return VerifiedTools(MappingProxyType(entries), tuple(envs))
diff --git a/pm/environment.py b/pm/environment.py
index 076ebd8c9b7..ea2f856517d 100644
--- a/pm/environment.py
+++ b/pm/environment.py
@@ -19,6 +19,7 @@ import tempfile
import time
from typing import TextIO
+from pm.filesystem import native
from pm.package import InstallError
from pm.progress import LiveTail, TextSink, verbose_output
@@ -142,7 +143,7 @@ def _run_streaming(command: list[str], *, cwd: Path, env: dict[str, str],
timeout: int, output: TextSink) -> subprocess.CompletedProcess:
"""Keep CI progress live, a bounded diagnostic tail, and a wall-clock timeout."""
deadline = time.monotonic() + timeout
- proc = subprocess.Popen(command, cwd=str(cwd), env=env, stdout=subprocess.PIPE,
+ proc = subprocess.Popen(command, cwd=native(cwd), env=env, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, text=True, encoding="utf-8", errors="replace", bufsize=0)
pipe = proc.stdout
assert isinstance(pipe, io.TextIOWrapper) # Popen was given stdout=PIPE and text=True.
@@ -284,11 +285,13 @@ class PythonEnvironment:
from pm.index_config import is_index_redirect
env = {key: value for key, value in env.items() if not is_index_redirect(key)}
- env.update(UV_PYTHON=str(self.python), UV_PROJECT_ENVIRONMENT=str(self.destination),
- UV_CACHE_DIR=str(self.cache), UV_PYTHON_DOWNLOADS="never")
+ # uv is a child: it gets the ordinary spelling of store paths (pm.filesystem.native),
+ # or the venv it writes would record the extended-length one in pyvenv.cfg.
+ env.update(UV_PYTHON=native(self.python), UV_PROJECT_ENVIRONMENT=native(self.destination),
+ UV_CACHE_DIR=native(self.cache), UV_PYTHON_DOWNLOADS="never")
with tempfile.TemporaryDirectory(prefix="pm-uv-config-") as config:
env.update(XDG_CONFIG_HOME=config, XDG_CONFIG_DIRS=config)
- command = [str(self.uv), *args]
+ command = [native(self.uv), *map(native, args)]
if self.no_config and "--no-config" not in command:
command.append("--no-config")
if self.offline:
@@ -314,7 +317,7 @@ class PythonEnvironment:
raise
tail.close(result.returncode == 0)
return result
- return subprocess.run(command, cwd=str(cwd), env=env, capture_output=True,
+ return subprocess.run(command, cwd=native(cwd), env=env, capture_output=True,
text=True, encoding="utf-8", errors="replace", timeout=timeout)
except subprocess.TimeoutExpired as exc:
from pm.index_config import TIMEOUT_HINT
diff --git a/pm/install.py b/pm/install.py
index fe83afe86ad..e4648feabda 100644
--- a/pm/install.py
+++ b/pm/install.py
@@ -15,7 +15,7 @@ from typing import Optional
from pm import paths
from pm.downloader import DownloadPaused, ProgressFn
-from pm.filesystem import remove_tree, retry_held
+from pm.filesystem import native, remove_tree, retry_held
from pm.lock import Facts, Lockfile
from pm.package import InstallError, Package, Runner, StatePackage, compose_env
from pm.plugin_inputs import Candidates, Members, PluginInput, Selection, StagedUpdate
@@ -128,7 +128,10 @@ def installed_package(name: str, *, allow_outdated: bool = False) -> InstalledPa
facts, store = location
fact = facts.get(name)
entry = store.entry(fact["entry"])
- return InstalledPackage(entry, fact["version"], package.binary(entry, target))
+ binary = package.binary(entry, target)
+ # Callers execute and compare these paths outside PM: the ordinary spelling, not the store's.
+ return InstalledPackage(Path(native(entry)), fact["version"],
+ Path(native(binary)) if binary is not None else None)
def uv_launcher(name: str) -> Path | None:
@@ -145,7 +148,7 @@ def uv_launcher(name: str) -> Path | None:
facts, store = location
binary = package.binary(store.entry(facts.get("uv")["entry"]), target)
launcher = binary.with_name(name + binary.suffix) if binary is not None else None
- return launcher if launcher is not None and launcher.is_file() else None
+ return Path(native(launcher)) if launcher is not None and launcher.is_file() else None
def _identity(lockfile: Lockfile, name: str, target: str):
@@ -936,8 +939,8 @@ def _store_path_dirs() -> list[str]:
if isinstance(path_dirs, str):
path_dirs = [path_dirs]
for directory in path_dirs:
- if directory and directory not in dirs:
- dirs.append(str(directory))
+ if directory and native(directory) not in dirs:
+ dirs.append(native(directory))
return dirs
diff --git a/pm/operations.py b/pm/operations.py
index f25421b7ccf..f92507c4ed9 100644
--- a/pm/operations.py
+++ b/pm/operations.py
@@ -254,7 +254,7 @@ def _ensure_generation(
Build at the final path: Windows launchers and scripts embed that path.
The prior generation survives both successful replacement and failed builds.
"""
- from pm.filesystem import lock_fd
+ from pm.filesystem import lock_fd, native
from pm._uv import _toolchain
from pm.install import _refuse_lazy, lazy_installs_allowed
from pm.lock import Lockfile, _write
@@ -273,7 +273,8 @@ def _ensure_generation(
def identity(base_python: Path) -> str:
# The same pinned artifact can live in different stores. A venv's
# pyvenv.cfg keeps the original interpreter path, not just its version.
- return hashlib.sha256(json.dumps({**inputs, "interpreter": str(base_python)},
+ # The store spells its root extended-length on Windows; the identity must not.
+ return hashlib.sha256(json.dumps({**inputs, "interpreter": native(base_python)},
sort_keys=True).encode()).hexdigest()
def current(base_python: Path | None) -> Path | None:
diff --git a/pm/package.py b/pm/package.py
index 600cb1f461e..da459d963f6 100644
--- a/pm/package.py
+++ b/pm/package.py
@@ -8,6 +8,8 @@ import subprocess
from pathlib import Path, PurePosixPath
from typing import TYPE_CHECKING, Optional
+from pm.filesystem import native
+
if TYPE_CHECKING:
from pm.store import Store
@@ -24,18 +26,21 @@ def compose_env(diffs: list[dict], base: Optional[dict] = None) -> dict[str, str
"""Dependents win over their dependencies for every key: diffs arrive
deps-first, later ones take precedence — npm's pinned shim must shadow
the npm bundled inside node, and a package's exports beat inherited env.
- 'PATH' values are lists of dirs, prepended."""
+ 'PATH' values are lists of dirs, prepended.
+
+ Diff values are paths under a store root, which PM spells extended-length
+ on Windows; a child environment gets their ordinary spelling."""
env = dict(os.environ if base is None else base)
path_dirs: list[str] = []
for diff in reversed(diffs):
for key, value in diff.items():
if key == "PATH":
dirs = value if isinstance(value, list) else [value]
- path_dirs.extend(str(d) for d in dirs if str(d) not in path_dirs)
+ path_dirs.extend(native(d) for d in dirs if native(d) not in path_dirs)
for diff in diffs:
for key, value in diff.items():
if key != "PATH":
- env[key] = str(value)
+ env[key] = native(str(value))
if path_dirs:
key = next((k for k in env if k.upper() == "PATH"), "PATH")
existing = env.get(key, "")
@@ -209,7 +214,7 @@ class DebPackage(Package):
the digest already proved the bytes."""
expected = entry / self.prefix_rel / self.main_rel(target)
if not expected.is_file() and not expected.is_symlink():
- return f"{expected.relative_to(entry)} missing under {entry}"
+ return f"{expected.relative_to(entry)} missing under {native(entry)}"
return ""
def main_rel(self, target: str) -> str:
@@ -355,14 +360,14 @@ def _missing_reason(binary: Path, entry: Path) -> str:
"""Why a package's expected binary is not where it should be — the
diagnosis that tells you whether the pin's layout is wrong."""
rel = binary.relative_to(entry).as_posix()
- return f"{rel} missing under {entry}; {_entry_listing(entry)}"
+ return f"{rel} missing under {native(entry)}; {_entry_listing(entry)}"
def _probe_reason(binary: Path, proc: "subprocess.CompletedProcess") -> str:
"""Why a --version probe failed: the exit code plus output tail."""
out = (proc.stdout or b"") + (proc.stderr or b"")
tail = out.decode(errors="replace").strip()[-300:]
- return f"{binary} --version exited {proc.returncode}" + (f": {tail}" if tail else "")
+ return f"{native(binary)} --version exited {proc.returncode}" + (f": {tail}" if tail else "")
class Runner:
diff --git a/pm/packages.py b/pm/packages.py
index 6ea498ad2ad..e6308ee51ef 100644
--- a/pm/packages.py
+++ b/pm/packages.py
@@ -12,6 +12,7 @@ import tempfile
from pathlib import Path
from typing import Optional
+from pm.filesystem import native
from pm.package import (
DebPackage,
InstallError,
@@ -101,16 +102,16 @@ class BinaryPackage(Package):
return ""
try:
proc = subprocess.run(
- [str(binary), *self.probe_args],
+ [native(binary), *self.probe_args],
capture_output=True,
timeout=60,
- cwd=str(binary.parent) if self.probe_cwd else None,
+ cwd=native(binary.parent) if self.probe_cwd else None,
env=self._probe_env(),
)
except OSError as e:
- return f"could not exec {binary} {' '.join(self.probe_args)}: {e}"
+ return f"could not exec {native(binary)} {' '.join(self.probe_args)}: {e}"
except subprocess.TimeoutExpired:
- return f"{binary} {' '.join(self.probe_args)} timed out after 60s"
+ return f"{native(binary)} {' '.join(self.probe_args)} timed out after 60s"
if proc.returncode != 0:
return _probe_reason(binary, proc)
return ""
@@ -614,9 +615,9 @@ class Npm(BinaryPackage):
with tempfile.TemporaryDirectory(prefix="hermes-npm-cache-", ignore_cleanup_errors=True) as cache:
proc = subprocess.run(
[
- str(node_bin), str(bundled_cli), "install", "--global",
- "--prefix", str(staged), "--offline", "--ignore-scripts",
- "--no-audit", "--no-fund", str(archive),
+ native(node_bin), native(bundled_cli), "install", "--global",
+ "--prefix", native(staged), "--offline", "--ignore-scripts",
+ "--no-audit", "--no-fund", native(archive),
],
capture_output=True,
text=True,
@@ -699,7 +700,7 @@ class Git(BinaryPackage):
# open past the stub's exit. Under -y the stub prints nothing anyway.
try:
proc = subprocess.run(
- [str(exe), f"-o{staged}", "-y"],
+ [native(exe), f"-o{native(staged)}", "-y"],
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
@@ -1040,16 +1041,16 @@ class Chromium(Package):
def verify(self, entry: Path, target: str) -> str:
marker = entry / "INSTALLATION_COMPLETE"
if not marker.is_file():
- return f"INSTALLATION_COMPLETE missing under {entry}; {_entry_listing(entry)}"
+ return f"INSTALLATION_COMPLETE missing under {native(entry)}; {_entry_listing(entry)}"
binary = self.binary(entry, target)
if binary is None:
- return f"Chromium executable missing under {entry}"
+ return f"Chromium executable missing under {native(entry)}"
return self._binary_reason(binary, entry, target)
def env(self, entry: Path, target: str) -> dict:
binary = self.binary(entry, target)
if binary is None:
- raise InstallError(self.name, f"Chromium executable missing under {entry}")
+ raise InstallError(self.name, f"Chromium executable missing under {native(entry)}")
return {
"PLAYWRIGHT_BROWSERS_PATH": str(entry.parent),
"AGENT_BROWSER_EXECUTABLE_PATH": str(binary),
diff --git a/pm/plugin_eviction.py b/pm/plugin_eviction.py
index 512b029f19f..093ea88c903 100644
--- a/pm/plugin_eviction.py
+++ b/pm/plugin_eviction.py
@@ -27,7 +27,7 @@ from pathlib import Path
from pm.environment import BuildFailure, ResolutionConflict
from pm.environments import install_state_dir, runtime_facts_path
-from pm.filesystem import durable_write_bytes, file_digest, read_bytes_or_none
+from pm.filesystem import durable_write_bytes, file_digest, native, read_bytes_or_none
from pm.package import InstallError
Entry = tuple[Path, str, Path] # (home plugins dir, selection key, plugin dir)
@@ -40,7 +40,7 @@ def _interpreter_version() -> str:
tools = _toolchain(explicit=True)
if tools is None:
raise InstallError("venv", "PM's pinned toolchain is unavailable")
- probe = subprocess.run([str(tools[1]), "-I", "-c", "import platform; print(platform.python_version())"],
+ probe = subprocess.run([native(tools[1]), "-I", "-c", "import platform; print(platform.python_version())"],
capture_output=True, text=True, check=True, timeout=60)
return probe.stdout.strip()
diff --git a/pm/runtime.py b/pm/runtime.py
index ec8205d07f8..e1e5399221e 100644
--- a/pm/runtime.py
+++ b/pm/runtime.py
@@ -15,6 +15,7 @@ import sys
from typing import Callable
import uuid
+from pm.filesystem import native
from pm.package import InstallError
@@ -27,7 +28,7 @@ def runtime_environment() -> dict[str, str]:
env = _base_environment()
env["HERMES_HOME"] = str(get_hermes_home())
- env["HERMES_RUNTIME_DIR"] = str(store_root())
+ env["HERMES_RUNTIME_DIR"] = native(store_root())
return env
@@ -46,7 +47,8 @@ def _inputs(project: Path, python: Path, *, as_spelled: bool = False) -> str:
# the same one reached through a symlinked store (a per-task HERMES_HOME whose
# tools/ links back) must. Only the directories resolve: the pinned
# bin/python3 is itself a symlink, so resolving it would re-key every install.
- python = python.absolute()
+ # A store spells its root extended-length on Windows; the identity must not.
+ python = Path(native(python)).absolute()
digest.update(str(python if as_spelled else python.parent.resolve() / python.name).encode())
return digest.hexdigest()
diff --git a/pm/security_packages.py b/pm/security_packages.py
index 871e5c0b2de..aa58ca48384 100644
--- a/pm/security_packages.py
+++ b/pm/security_packages.py
@@ -9,6 +9,7 @@ from pathlib import Path
from urllib.parse import urlparse
from pm import paths
+from pm.filesystem import native
from pm.lock import Lockfile
from pm.package import InstallError
from pm.packages import BinaryPackage, _RUST_TRIPLE
@@ -120,12 +121,12 @@ class IronProxy(_SignedBinary):
key = directory / "public-key.asc"
if not signature.is_file() or not key.is_file():
raise InstallError(self.name, "pinned signature assets missing")
- imported = subprocess.run([*args, "--import", str(key)], stdin=subprocess.DEVNULL,
+ imported = subprocess.run([*args, "--import", native(key)], stdin=subprocess.DEVNULL,
capture_output=True, timeout=60, check=False)
if imported.returncode:
logging.getLogger(__name__).warning("Could not import iron-proxy signing key; archive checksum remains enforced")
return
- verified = subprocess.run([*args, "--verify", str(signature), str(directory / "checksums.txt")],
+ verified = subprocess.run([*args, "--verify", native(signature), native(directory / "checksums.txt")],
stdin=subprocess.DEVNULL, capture_output=True, timeout=60, check=False)
if verified.returncode:
raise InstallError(self.name, "GPG signature verification failed")
\ No newline at end of file
diff --git a/tests/pm/test_long_path_exits.py b/tests/pm/test_long_path_exits.py
new file mode 100644
index 00000000000..e5a80c960e3
--- /dev/null
+++ b/tests/pm/test_long_path_exits.py
@@ -0,0 +1,54 @@
+"""A store root spelled in Windows' extended-length form (``\\\\?\\C:\\...``) stays inside PM.
+
+The spelling exists only so PM's own file calls beneath the root pass MAX_PATH. Text that
+leaves PM must carry the ordinary spelling: the same folder spelled two ways hashes and
+compares differently, and child tools (cmd.exe, gpg, installers) may refuse the prefix.
+The roots below are plain text, so both invariants hold on every OS.
+"""
+import subprocess
+from pathlib import Path
+
+from pm import environment as environment_module
+from pm.environment import PythonEnvironment
+from pm.lock import Facts
+from pm.package import compose_env
+from pm.runtime import _inputs
+from pm.store import Store
+
+VERBATIM = "\\\\?\\"
+ROOT = Path(VERBATIM + r"C:\Program Files\WindowsApps\Hermes\agent-payload\tools")
+
+
+def test_identity_does_not_depend_on_the_root_spelling(tmp_path):
+ for name in ("pyproject.toml", "uv.lock"):
+ (tmp_path / name).write_text(name, encoding="utf-8")
+ plain = Path(r"C:\Program Files\WindowsApps\Hermes\agent-payload\tools\python-3.12\python.exe")
+
+ assert _inputs(tmp_path, Path(VERBATIM + str(plain))) == _inputs(tmp_path, plain)
+
+
+def test_no_verbatim_spelling_leaves_through_records_environment_or_uv(tmp_path, monkeypatch):
+ store = Store(ROOT)
+ facts = Facts(tmp_path / "facts.json")
+ facts.record("git", "1", "git-1", {"PATH": [str(store.entry("git-1") / "cmd")]}, store.root)
+ facts.record("chromium", "1", "chromium-1",
+ {"AGENT_BROWSER_EXECUTABLE_PATH": str(store.entry("chromium-1") / "chrome.exe")}, store.root)
+ record = (tmp_path / "facts.json").read_text(encoding="utf-8")
+
+ env = compose_env([facts.env_for("git", store.root), facts.env_for("chromium", store.root)], base={})
+
+ calls = []
+
+ def run(command, **kwargs):
+ calls.append((command, kwargs))
+ return subprocess.CompletedProcess(command, 0, "", "")
+
+ monkeypatch.setattr(environment_module.subprocess, "run", run)
+ PythonEnvironment(uv=store.entry("uv-1") / "uv.exe", python=store.entry("python-1") / "python.exe",
+ destination=tmp_path / "venv", cache=tmp_path / "cache",
+ env={}).sync(store.entry("source"))
+ (command, kwargs), = calls
+
+ leaving = [record, *env.values(), *command, kwargs["cwd"], *kwargs["env"].values()]
+ assert [text for text in leaving if VERBATIM in text] == []
+ assert env["AGENT_BROWSER_EXECUTABLE_PATH"].endswith("chrome.exe")