Skip to content

The agent that grows with you

refactor(pm): consolidate private Python environment engine

ethernet01821b8e14db
diff --git a/pm/_uv.py b/pm/_uv.py
new file mode 100644
index 00000000000..37242d72c25
--- /dev/null
+++ b/pm/_uv.py
@@ -0,0 +1,58 @@
+"""Pinned tool acquisition for PM's private Python engine; never worker API."""
+from __future__ import annotations
+
+from pathlib import Path
+
+from pm import paths
+from pm.lock import Facts
+from pm.package import InstallError
+from pm.registry import get_package
+from pm.store import Store, current_target
+
+
+def _toolchain(*, realize: bool = True, explicit: bool = False) -> tuple[Path, Path] | None:
+ """Resolve uv and Python without host discovery or recursive worker dispatch.
+
+ A read-only probe never installs. Windows bundle builds need a verified
+ writable interpreter so their venv redirectors can run outside the MSIX.
+ """
+ from pm.ensure import (
+ _install, _installed_location, _lockfile, _refuse_lazy,
+ ensure, lazy_installs_allowed, sealed,
+ )
+
+ if realize:
+ ensure("uv", explicit=explicit)
+
+ lockfile = _lockfile()
+ target = current_target()
+ binaries = {}
+ for name in ("uv", "python"):
+ package = get_package(name)
+ location = _installed_location(package, lockfile, target)
+ if location is None:
+ if not realize:
+ return None
+ raise InstallError(name, "pinned tool is unavailable", "run `hermes pm install`")
+ if name == "python" and target.startswith("win32") and sealed():
+ writable = paths.writable_store_root()
+ if location[1].root != writable:
+ copied = _installed_location(package, lockfile, target, verify=explicit, roots=(writable,))
+ if copied is None:
+ if not realize:
+ return None
+ if not explicit and not lazy_installs_allowed():
+ raise _refuse_lazy(name, "a writable Python is required for bundled builds")
+ copy_store = Store(writable)
+ copy_facts = Facts(writable / "facts.json")
+ _install(package, lockfile, copy_facts, copy_store, target, copy_from=location)
+ copied = copy_facts, copy_store
+ location = copied
+ facts, store = location
+ binary = package.binary(store.entry(facts.get(name)["entry"]), target)
+ if binary is None or not binary.is_file():
+ if not realize:
+ return None
+ raise InstallError(name, "installed binary is missing", "run `hermes pm install`")
+ binaries[name] = binary
+ return binaries["uv"], binaries["python"]
diff --git a/pm/ensure.py b/pm/ensure.py
index fc9bee4448a..696211274e6 100644
--- a/pm/ensure.py
+++ b/pm/ensure.py
@@ -81,6 +81,8 @@ class InstalledPackage:
def installed_package(name: str, *, allow_outdated: bool = False) -> InstalledPackage | None:
"""Read the selected PM entry without installing or changing its facts."""
package = get_package(name)
+ if package.internal:
+ raise ValueError(f"{name} is internal PM tooling, not an application package")
target = current_target()
location = _installed_location(package, _lockfile(), target, allow_outdated=allow_outdated)
if location is None:
@@ -480,6 +482,8 @@ def env_for(*names: str, base_env: Optional[dict] = None) -> dict[str, str]:
except KeyError:
continue
for package in chain:
+ if package.internal:
+ continue
location = _installed_location(package, lockfile, target)
if location:
facts, store = location
@@ -778,60 +782,3 @@ def activate() -> None:
missing = [d for d in dirs if d.lower() not in existing_lower]
if missing:
os.environ["PATH"] = os.pathsep.join([*missing, existing]) if existing else os.pathsep.join(missing)
-
-
-
-def uv(command: str = "uv", *, venv=None, realize: bool = True, explicit: bool = False, base_env=None):
- """Return uv or uvx with its native suffix and PM's pinned Python.
-
- Probes never install. A command with missing prerequisites realizes the
- package closure or raises; it must not fall back to host Python discovery.
- ``venv`` selects the active project environment. ``uv pip`` callers must
- still pass their destination interpreter explicitly.
- """
- from pm.packages import uv_env
-
- if command not in ("uv", "uvx"):
- raise ValueError(f"unknown uv executable: {command}")
- env = uv_env(base_env)
- if venv is not None:
- env["VIRTUAL_ENV"] = str(venv)
- env.pop("UV_NO_CONFIG", None)
- if realize:
- ensure("uv", explicit=explicit)
-
- lockfile = _lockfile()
- target = current_target()
- binaries = {}
- for name in ("uv", "python"):
- package = get_package(name)
- location = _installed_location(package, lockfile, target)
- if location is None:
- return None, env
- if name == "python" and target.startswith("win32") and sealed():
- # uv creates redirectors outside the MSIX. Their Python must also
- # live outside it; the app keeps its original packaged interpreter.
- writable = paths.writable_store_root()
- if location[1].root != writable:
- copied = _installed_location(package, lockfile, target, verify=explicit, roots=(writable,))
- if copied is None:
- if not realize:
- return None, env
- if not explicit and not lazy_installs_allowed():
- raise _refuse_lazy(name, "a writable Python is required for bundled uv builds")
- copy_store = Store(writable)
- copy_facts = Facts(writable / "facts.json")
- _install(package, lockfile, copy_facts, copy_store, target, copy_from=location)
- copied = copy_facts, copy_store
- location = copied
- facts, store = location
- binary = package.binary(store.entry(facts.get(name)["entry"]), target)
- if name == "uv" and binary is not None:
- binary = binary.with_name(command + binary.suffix)
- if binary is None or not binary.is_file():
- if not realize:
- return None, env
- raise InstallError(name, "installed binary is missing", "run `hermes pm install`")
- binaries[name] = str(binary)
- env["UV_PYTHON"] = binaries["python"]
- return binaries["uv"], env
diff --git a/pm/environment.py b/pm/environment.py
index 80877a6421b..82e1004d02c 100644
--- a/pm/environment.py
+++ b/pm/environment.py
@@ -1,7 +1,7 @@
-"""Explicit uv construction, independent of PM tool discovery and live selection.
+"""PM's private Python engine: tool routing, isolation and command execution.
-Callers own the destination, source/workspace, cache and publication lifecycle.
-This module neither discovers profiles nor modifies the process environment.
+Operations own source, destination and publication. Bootstrap may inject its
+staged toolchain directly without recursing through the worker it is building.
"""
from __future__ import annotations
@@ -93,6 +93,36 @@ def _run_streaming(command: list[str], *, cwd: Path, env: dict[str, str],
return subprocess.CompletedProcess(command, code, "", tail)
+def _base_environment(env: Mapping[str, str] | None = None) -> dict[str, str]:
+ """Ambient UV settings are never policy; explicit build index settings are."""
+ index_settings = {
+ "UV_DEFAULT_INDEX", "UV_EXTRA_INDEX_URL", "UV_NO_INDEX", "UV_FIND_LINKS",
+ "UV_INSECURE_HOST", "UV_KEYRING_PROVIDER", "UV_NATIVE_TLS",
+ }
+ return {key: value for key, value in (os.environ if env is None else env).items()
+ if not key.startswith("PYTHON") and key != "VIRTUAL_ENV"
+ and (not key.startswith("UV_") or
+ (env is not None and (key.startswith("UV_INDEX") or key in index_settings)))}
+
+
+def managed_environment(destination: Path, *, python: Path | None = None,
+ cache: Path | None = None, env: Mapping[str, str] | None = None,
+ offline: bool = False, explicit: bool = False,
+ output: TextIO | None = None) -> PythonEnvironment:
+ from pm._uv import _toolchain
+ from pm.packages import uv_cache_dir
+
+ tools = _toolchain(explicit=explicit)
+ if tools is None:
+ raise InstallError("venv", "PM's pinned toolchain is unavailable")
+ uv, pinned_python = tools
+ return PythonEnvironment(
+ uv=uv, python=pinned_python if python is None else python.absolute(),
+ destination=destination.absolute(), cache=uv_cache_dir() if cache is None else cache.absolute(),
+ env=_base_environment(env), offline=offline, output=output,
+ )
+
+
@dataclass(frozen=True, kw_only=True)
class PythonEnvironment:
uv: Path
@@ -102,25 +132,23 @@ class PythonEnvironment:
env: Mapping[str, str]
offline: bool = False
output: TextIO | None = None
+ no_config: bool = False
@property
def executable(self) -> Path:
return self.destination / ("Scripts/python.exe" if os.name == "nt" else "bin/python")
def _run(self, args: list[str], *, cwd: Path, timeout: int) -> subprocess.CompletedProcess:
- # The caller supplies policy (PM already sanitizes it via pm.ensure.uv).
- # Preserve intentional index credentials/settings; only explicit routing
- # inputs and project-config visibility override this child environment.
- env = {key: value for key, value in self.env.items() if key not in (
- "VIRTUAL_ENV", "PYTHONPATH", "PYTHONHOME", "PYTHONSTARTUP", "PYTHONEXECUTABLE",
- "UV_WORKING_DIR", "UV_PROJECT", "UV_CONFIG_FILE", "UV_NO_CONFIG",
- "UV_MANAGED_PYTHON", "UV_NO_MANAGED_PYTHON", "UV_SYSTEM_PYTHON",
- )}
+ # Explicit index credentials survive, but cannot redirect the project,
+ # interpreter or cache selected by the operation.
+ env = _base_environment(self.env)
env.update(UV_PYTHON=str(self.python), UV_PROJECT_ENVIRONMENT=str(self.destination),
UV_CACHE_DIR=str(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]
+ if self.no_config and "--no-config" not in command:
+ command.append("--no-config")
if self.offline:
command.append("--offline")
if self.output is not None:
@@ -139,8 +167,20 @@ class PythonEnvironment:
if result.returncode:
raise InstallError("venv", f"uv venv failed: {result.stderr[-600:]}")
- def sync(self, source: Path, *, extras: Sequence[str] = (), frozen: bool = True,
- all_extras: bool = False, no_install_project: bool = False) -> None:
+ def lock(self, source: Path, *, upgrade: bool = False, timeout: int = 1800) -> None:
+ from pm.workspace import classify_uv_failure
+
+ command = ["lock", "--python", str(self.python)]
+ if upgrade:
+ command.append("--upgrade")
+ result = self._run(command, cwd=source, timeout=timeout)
+ if result.returncode:
+ raise classify_uv_failure("lock", result.returncode, result.stderr or result.stdout)
+
+ def sync(self, source: Path, *, extras: Sequence[str] = (), groups: Sequence[str] = (),
+ timeout: int = 1800, frozen: bool = True, all_extras: bool = False,
+ no_install_project: bool = False, locked: bool = False,
+ no_default_groups: bool = False) -> None:
"""Install the root and every member; resolve only in a writable workspace.
``frozen=False`` is reserved for the caller-owned generated workspace,
@@ -149,11 +189,12 @@ class PythonEnvironment:
from pm.workspace import classify_uv_failure
if not frozen:
- locked = self._run(["lock", "--python", str(self.python)], cwd=source, timeout=1800)
- if locked.returncode:
- raise classify_uv_failure("lock", locked.returncode, locked.stderr or locked.stdout)
+ self.lock(source, timeout=timeout)
# Locking members alone is insufficient: plain sync only installs root deps.
- command = ["sync", "--frozen", "--all-packages", "--python", str(self.python)]
+ command = ["sync", "--locked" if locked else "--frozen", "--all-packages",
+ "--python", str(self.python)]
+ if no_default_groups:
+ command.append("--no-default-groups")
if all_extras:
command.append("--all-extras")
if no_install_project:
@@ -166,10 +207,30 @@ class PythonEnvironment:
command += ["--no-install-project", "--no-install-package", project["project"]["name"]]
for extra in sorted(set(extras)):
command += ["--extra", extra]
- result = self._run(command, cwd=source, timeout=1800)
+ for group in sorted(set(groups)):
+ command += ["--group", group]
+ result = self._run(command, cwd=source, timeout=timeout)
if result.returncode:
raise classify_uv_failure("sync", result.returncode, result.stderr or result.stdout)
+ def install_wheelhouse(self, source: Path, wheelhouse: Path, *, timeout: int = 1800) -> None:
+ """Install rebuilt wheels whose hashes the bundle manifest owns, not uv.lock."""
+ from pm.workspace import classify_uv_failure
+
+ requirements = source / "requirements.txt"
+ commands = [
+ ["export", "--frozen", "--python", str(self.python), "--no-default-groups",
+ "--no-emit-project", "--no-hashes", "--output-file", str(requirements)],
+ ["pip", "install", "--python", str(self.executable), "--no-index",
+ "--only-binary", ":all:", "--find-links", str(wheelhouse.absolute()),
+ "-r", str(requirements)],
+ ]
+ for command in commands:
+ result = self._run(command, cwd=source, timeout=timeout)
+ if result.returncode:
+ raise classify_uv_failure(command[0], result.returncode, result.stderr or result.stdout)
+ self.check()
+
def check(self) -> None:
result = self._run(
["pip", "check", "--no-config", "--python", str(self.executable)],
diff --git a/pm/packages.py b/pm/packages.py
index 1f9e39fe06d..fdf430b1dbc 100644
--- a/pm/packages.py
+++ b/pm/packages.py
@@ -160,6 +160,7 @@ class Uv(_BionicDebArm, BinaryPackage, DebPackage):
name = "uv"
deps = ("python",)
internal = True
+ on_path = False
binary_rel = {"win32": "uv.exe", "posix": "uv"}
# The staged .deb's main binary: DebPackage.verify checks it.
main_bin_rel = "bin/uv"
@@ -354,50 +355,6 @@ def uv_cache_dir() -> Path:
return machine_cache
-def uv_env(base_env: Optional[dict] = None) -> dict[str, str]:
- """Sanitized env for pm's internal uv invocations: user-level UV
- overrides and active-venv leakage must not steer which interpreter or
- install dir uv picks (the interpreter-hijack class, #83914), and
- ambient user/system uv config (uv.toml under XDG_CONFIG_HOME/DIRS)
- must not reach the subprocess either. User config discovery is
- redirected to an empty dir; HOME is left alone so caches, credentials,
- and git keep working (the #82446 isolation contract, which lived in
- the installers' run_locked_uv_sync() before the sync moved into pm).
- UV_CACHE_DIR always points at the hermes-owned cache (shipped with
- bundles, shared machine-wide) — never the user's ambient cache."""
- env = dict(os.environ if base_env is None else base_env)
- for key in list(env):
- if key.startswith("UV_") or key in (
- "VIRTUAL_ENV",
- "PYTHONPATH",
- "PYTHONHOME",
- "PYTHONSTARTUP",
- "PYTHONEXECUTABLE",
- ):
- env.pop(key)
- isolated = _isolated_config_dir()
- env["XDG_CONFIG_HOME"] = str(isolated)
- env["XDG_CONFIG_DIRS"] = str(isolated)
- env["UV_NO_CONFIG"] = "1"
- env["UV_CACHE_DIR"] = str(uv_cache_dir())
- return env
-
-
-_ISOLATED_CONFIG_DIR: Optional[str] = None
-
-
-def _isolated_config_dir() -> Path:
- """A per-process empty dir ambient uv config is redirected to. One
- shared empty dir is all that's needed (and all that ever gets
- created); it is never populated, so it cannot steer resolution."""
- import tempfile
-
- global _ISOLATED_CONFIG_DIR
- if _ISOLATED_CONFIG_DIR is None:
- _ISOLATED_CONFIG_DIR = tempfile.mkdtemp(prefix="pm-uv-")
- return Path(_ISOLATED_CONFIG_DIR)
-
-
@register
class Venv(StatePackage):
"""The project venv: pyproject.toml + uv.lock + enabled extras.
@@ -442,22 +399,14 @@ class Venv(StatePackage):
"""Prepare one complete environment; the caller commits its selection."""
import uuid
from hermes_cli.runtime_paths import install_state_dir, runtime_facts_path
- from pm.ensure import uv as pm_uv
- from pm.environment import PythonEnvironment
+ from pm.environment import managed_environment
from pm.lock import Facts
from pm.workspace import enabled_member_dirs, lock_and_sync
project = self.project_root()
generation = install_state_dir(project) / "environments" / uuid.uuid4().hex
candidate = generation / "venv"
- uv_bin, env = pm_uv(explicit=repair)
- if uv_bin is None:
- raise InstallError(self.name, "uv is not installed")
- environment = PythonEnvironment(
- uv=Path(uv_bin), python=Path(env["UV_PYTHON"]), destination=candidate,
- cache=Path(env["UV_CACHE_DIR"]), env=env,
- offline=env.get("UV_OFFLINE") == "1",
- )
+ environment = managed_environment(candidate, explicit=repair)
members = [] if repair else (enabled_member_dirs() if plugin_dirs is None else plugin_dirs)
try:
generation.mkdir(parents=True)
@@ -484,7 +433,7 @@ class Venv(StatePackage):
environment.check()
if repair:
from pm.recovery import validate_environment
- validate_environment(environment.executable, env=env, cwd=resolved_lock.parent)
+ validate_environment(environment.executable, env=dict(environment.env), cwd=resolved_lock.parent)
except BaseException:
shutil.rmtree(generation, ignore_errors=True)
raise
diff --git a/pm/runtime.py b/pm/runtime.py
index 379eeafc12f..196f8c022d8 100644
--- a/pm/runtime.py
+++ b/pm/runtime.py
@@ -22,12 +22,11 @@ def runtime_environment() -> dict[str, str]:
from hermes_constants import get_hermes_home
from pm.paths import store_root
- env = {key: value for key, value in os.environ.items()
- if not key.startswith("PYTHON") and not key.startswith("UV_")
- and key != "VIRTUAL_ENV"}
+ from pm.environment import _base_environment
+
+ env = _base_environment()
env["HERMES_HOME"] = str(get_hermes_home())
env["HERMES_RUNTIME_DIR"] = str(store_root())
- env["UV_PYTHON_DOWNLOADS"] = "never"
return env
@@ -148,15 +147,15 @@ def runtime_python(*, bootstrap: bool = True) -> Path:
if is_runtime():
return Path(sys.executable)
from hermes_cli.runtime_paths import install_state_dir
- from pm.ensure import uv as managed_uv
+ from pm._uv import _toolchain
from pm.paths import repo_root
project = repo_root()
resident = _resident_runtime()
if resident is not None:
return resident[0]
- uv, env = managed_uv(realize=False)
- if uv is None:
+ tools = _toolchain(realize=False)
+ if tools is None:
if not bootstrap:
raise InstallError("pm-runtime", "not installed and lazy installs are disabled",
"run `hermes pm install` to prepare the independent PM runtime")
@@ -172,13 +171,14 @@ def runtime_python(*, bootstrap: bool = True) -> Path:
target = current_target()
staged = package.binary(store_root() / package.store_entry(version, target), target) if version else None
if staged is not None and staged.is_file():
- uv, env = str(staged), {"UV_PYTHON": sys.executable}
+ tools = staged, Path(sys.executable)
else:
# Non-shell bootstrap callers (CI) already have a host interpreter.
- uv, env = managed_uv(explicit=True)
- if uv is None:
+ tools = _toolchain(explicit=True)
+ if tools is None:
raise InstallError("pm-runtime", "pinned uv and Python are unavailable")
- return prepare_runtime(Path(uv), Path(env["UV_PYTHON"]), install_state_dir(project) / "pm-runtime",
+ uv, python = tools
+ return prepare_runtime(uv, python, install_state_dir(project) / "pm-runtime",
bootstrap=bootstrap)
diff --git a/pm/runtime_stage.py b/pm/runtime_stage.py
index f95506dcd60..e8157707703 100644
--- a/pm/runtime_stage.py
+++ b/pm/runtime_stage.py
@@ -1,7 +1,6 @@
"""One locked dependency builder for PM workers and packaged runtimes."""
from __future__ import annotations
-import os
from pathlib import Path
import shutil
import subprocess
@@ -19,53 +18,34 @@ def stage_runtime(uv: Path, python: Path, destination: Path, *,
The scratch project prevents uv from discovering the application's workspace.
No project install, application extra, or application lock enters this graph.
"""
+ from pm.environment import PythonEnvironment
from pm.packages import uv_cache_dir
from pm.runtime import runtime_environment
project = project or Path(__file__).resolve().parent
destination = destination.absolute()
- executable = destination / ("Scripts/python.exe" if os.name == "nt" else "bin/python")
env = runtime_environment()
- env["UV_CACHE_DIR"] = str(uv_cache_dir() if cache is None else cache.absolute())
- env["UV_PROJECT_ENVIRONMENT"] = str(destination)
- env["UV_PYTHON"] = str(python)
+ environment = PythonEnvironment(
+ uv=uv, python=python, destination=destination,
+ cache=uv_cache_dir() if cache is None else cache.absolute(), env=env,
+ offline=offline or wheelhouse is not None, output=sys.stderr, no_config=True,
+ )
destination.parent.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix="pm-project-", dir=destination.parent) as temp:
snapshot = Path(temp)
for name in ("pyproject.toml", "uv.lock"):
shutil.copyfile(project / name, snapshot / name)
- commands = [
- [str(uv), "venv", "--relocatable", "--python", str(python), str(destination)],
- [str(uv), "sync", "--project", str(snapshot), "--locked",
- "--no-default-groups", "--no-install-project", "--python", str(python)],
- ]
- if wheelhouse is not None:
- # Locally rebuilt wheels are verified by the caller's wheelhouse
- # manifest, not the upstream wheel hashes in the PM lock.
- offline = True
- requirements = snapshot / "requirements.txt"
- commands[1:] = [
- [str(uv), "export", "--project", str(snapshot), "--frozen",
- "--python", str(python), "--no-default-groups", "--no-emit-project",
- "--no-hashes", "--output-file", str(requirements)],
- [str(uv), "pip", "install", "--python", str(executable),
- "--no-index", "--only-binary", ":all:",
- "--find-links", str(wheelhouse.absolute()), "-r", str(requirements)],
- [str(uv), "pip", "check", "--python", str(executable)],
- ]
- for command in commands:
- # Neither the caller's uv.toml nor user-wide settings may choose
- # PM's indexes, required uv version, or environment policy.
- command.append("--no-config")
- if offline:
- command.append("--offline")
- result = subprocess.run(command, cwd=snapshot, env=env, stdout=sys.stderr, stderr=sys.stderr, timeout=600)
- if result.returncode:
- raise InstallError("pm-runtime", f"{command[1]} exited {result.returncode}")
+ environment.create()
+ if wheelhouse is None:
+ environment.sync(snapshot, locked=True, no_default_groups=True,
+ no_install_project=True, timeout=600)
+ else:
+ environment.install_wheelhouse(snapshot, wheelhouse, timeout=600)
checked = subprocess.run(
- [str(executable), "-I", "-B", "-c", "import packaging, tomli_w, truststore; from ruamel.yaml import YAML"],
+ [str(environment.executable), "-I", "-B", "-c",
+ "import packaging, tomli_w, truststore; from ruamel.yaml import YAML"],
env=env, capture_output=True, text=True, timeout=30,
)
if checked.returncode:
raise InstallError("pm-runtime", f"dependency validation failed: {checked.stderr.strip()}")
- return executable
+ return environment.executable
diff --git a/pm/workspace.py b/pm/workspace.py
index 2cb5eab626d..7e505307877 100644
--- a/pm/workspace.py
+++ b/pm/workspace.py
@@ -471,15 +471,7 @@ def lock_and_sync(
frozen = True
if environment is None:
- from pm.ensure import uv as pm_uv
- from pm.environment import PythonEnvironment
-
- uv_bin, run_env = pm_uv(base_env=env)
- if uv_bin is None:
- raise InstallError("venv", "PM's uv and Python are required; run `hermes pm install`")
- environment = PythonEnvironment(
- uv=Path(uv_bin), python=Path(run_env["UV_PYTHON"]), destination=venv_dir,
- cache=Path(run_env["UV_CACHE_DIR"]), env=run_env,
- offline=run_env.get("UV_OFFLINE") == "1",
- )
+ from pm.environment import managed_environment
+
+ environment = managed_environment(venv_dir, env=env)
environment.sync(generated, extras=extras or (), frozen=frozen)
diff --git a/tests/pm/test_environment_build.py b/tests/pm/test_environment_build.py
index a65640394ad..a1ef0518823 100644
--- a/tests/pm/test_environment_build.py
+++ b/tests/pm/test_environment_build.py
@@ -105,8 +105,12 @@ def locked_project(tmp_path):
@pytest.fixture
-def installable_project(locked_project):
+def installable_project(locked_project, monkeypatch):
source, uv, env = locked_project
+ # The parent suite exercises the worker transport; these tests exercise the
+ # build adapter and engine with locally supplied, real tool binaries.
+ monkeypatch.setattr("pm.client.is_runtime", lambda: True)
+ monkeypatch.setattr("pm._uv._toolchain", lambda **kwargs: (uv, Path(sys.executable)))
metadata = source / "pyproject.toml"
metadata.write_text(metadata.read_text().replace("package=false", "package=true") +
'\n[build-system]\nrequires=[]\nbuild-backend="local_backend"\nbackend-path=["."]\n')
@@ -137,8 +141,8 @@ build_editable = build_wheel
return source, uv, env
-def test_native_provider_builds_all_extras_at_explicit_destination(installable_project, tmp_path, monkeypatch):
- from scripts.build.python_env import build_python_environment
+def test_public_build_installs_all_extras_at_explicit_destination(installable_project, tmp_path, monkeypatch):
+ from pm import build_environment
import pm.paths
import pm.workspace
@@ -147,8 +151,8 @@ def test_native_provider_builds_all_extras_at_explicit_destination(installable_p
monkeypatch.setattr(pm.workspace, "enabled_member_dirs", lambda: pytest.fail("user plugins"))
before = dict(os.environ)
locked = (source / "uv.lock").read_bytes()
- executable = build_python_environment(
- source=source, python=Path(sys.executable), uv=uv, out=tmp_path / "native environment",
+ executable = build_environment(
+ source=source, python=Path(sys.executable), out=tmp_path / "native environment",
cache=tmp_path / "cache", env=env, all_extras=True, offline=True,
)
assert _run([str(executable), "-I", "-c",
@@ -160,26 +164,24 @@ def test_native_provider_builds_all_extras_at_explicit_destination(installable_p
assert not Path(env["HERMES_HOME"]).exists()
[email protected]("extra_flags, expected", [
- (["--extra", "chosen", "--extra", "chosen"], [True, False]),
- (["--all-extras"], [True, True]),
- ([], [False, False]),
[email protected]("selection, expected", [
+ ({"extras": ["chosen", "chosen"]}, [True, False]),
+ ({"all_extras": True}, [True, True]),
+ ({}, [False, False]),
])
-def test_cli_dependency_only_needs_no_application_source(installable_project, tmp_path, extra_flags, expected):
+def test_public_dependency_only_build_needs_no_application_source(installable_project, tmp_path, selection, expected):
source, uv, env = installable_project
(source / "root_app.py").unlink()
(source / "local_backend.py").unlink()
locked = (source / "uv.lock").read_bytes()
- repo = Path(__file__).resolve().parents[2]
- executable = _run(
- [sys.executable, "-m", "scripts.build.python_env", "--source", str(source),
- "--python", sys.executable, "--uv", str(uv), "--out", str(tmp_path / "docker env"),
- "--no-install-project", "--offline", *extra_flags],
- cwd=tmp_path, env={**env, "PYTHONPATH": str(repo)},
- )
- assert executable, "CLI must return the verified environment executable"
+ from pm import build_environment
+
+ executable = build_environment(source=source, python=Path(sys.executable),
+ out=tmp_path / "docker env", cache=tmp_path / "cache", env=env,
+ no_install_project=True, offline=True, **selection)
+ assert executable.is_file()
result = json.loads(_run(
- [executable, "-I", "-c", "import json, importlib.util, importlib.metadata, base_dep; "
+ [str(executable), "-I", "-c", "import json, importlib.util, importlib.metadata, base_dep; "
"print(json.dumps([importlib.util.find_spec('chosen_dep') is not None, "
"importlib.util.find_spec('other_dep') is not None, "
"'construction-root' in [d.metadata['Name'] for d in importlib.metadata.distributions()]]))"],
@@ -205,7 +207,9 @@ def test_child_output_is_live_and_keeps_explicit_index_credentials(tmp_path):
output = AcknowledgingLog()
child_env = dict(os.environ, UV_INDEX_PRIVATE_USERNAME="fixture-user",
UV_INDEX_PRIVATE_PASSWORD="fixture-secret",
- UV_DEFAULT_INDEX="https://fixture.invalid/simple")
+ UV_DEFAULT_INDEX="https://fixture.invalid/simple",
+ UV_PROJECT="/poison/project", UV_VENV_SEED="true", UV_SYSTEM_PYTHON="true",
+ UV_PYTHON="/poison/python", UV_CACHE_DIR="/poison/cache")
environment = PythonEnvironment(
uv=Path(sys.executable), python=Path(sys.executable), destination=tmp_path / "venv",
cache=tmp_path / "cache", env=child_env, output=output,
@@ -219,6 +223,9 @@ def test_child_output_is_live_and_keeps_explicit_index_credentials(tmp_path):
"assert os.environ['UV_INDEX_PRIVATE_USERNAME'] == 'fixture-user'\n"
"assert os.environ['UV_INDEX_PRIVATE_PASSWORD'] == 'fixture-secret'\n"
"assert os.environ['UV_DEFAULT_INDEX'] == 'https://fixture.invalid/simple'\n"
+ "assert not {'UV_PROJECT', 'UV_VENV_SEED', 'UV_SYSTEM_PYTHON'} & os.environ.keys()\n"
+ f"assert os.environ['UV_PYTHON'] == {sys.executable!r}\n"
+ f"assert os.environ['UV_CACHE_DIR'] == {str(tmp_path / 'cache')!r}\n"
"print('child-complete', flush=True)\n"
)
result = environment._run(["-c", script], cwd=tmp_path, timeout=10)
@@ -304,13 +311,13 @@ def test_streaming_eof_does_not_restart_process_wait_timeout(tmp_path):
@pytest.mark.parametrize("damage", ["source", "check", "lock"])
def test_failed_build_removes_only_its_candidate(installable_project, tmp_path, damage):
- from scripts.build.python_env import build_python_environment
+ from pm import build_environment
from pm.package import InstallError
source, uv, env = installable_project
previous = tmp_path / "previous"
- executable = build_python_environment(source=source, python=Path(sys.executable), uv=uv,
- out=previous, env=env, offline=True)
+ executable = build_environment(source=source, python=Path(sys.executable),
+ out=previous, env=env, cache=tmp_path / "cache", offline=True)
cfg = (previous / "pyvenv.cfg").read_bytes()
source_lock = (source / "uv.lock").read_bytes()
if damage == "source":
@@ -323,13 +330,13 @@ def test_failed_build_removes_only_its_candidate(installable_project, tmp_path,
else:
(source / "uv.lock").unlink()
candidate = tmp_path / "candidate"
- with pytest.raises(InstallError, match="dependency validation" if damage == "check" else "uv sync"):
- build_python_environment(source=source, python=Path(sys.executable), uv=uv,
+ with pytest.raises(InstallError, match="dependency validation" if damage == "check" else "uv sync|frozen build requires a lock"):
+ build_environment(source=source, python=Path(sys.executable),
out=candidate, env=env, cache=tmp_path / "cold-cache", offline=True)
assert not candidate.exists()
with pytest.raises(FileExistsError):
- build_python_environment(source=source, python=Path(sys.executable), uv=uv,
- out=previous, env=env, offline=True)
+ build_environment(source=source, python=Path(sys.executable),
+ out=previous, env=env, cache=tmp_path / "cache", offline=True)
assert (previous / "pyvenv.cfg").read_bytes() == cfg
assert _run([str(executable), "-I", "-c", "import base_dep; print(base_dep.__version__)"],
cwd=tmp_path, env=env) == "1.0"
@@ -339,6 +346,31 @@ def test_failed_build_removes_only_its_candidate(installable_project, tmp_path,
assert not (source / "uv.lock").exists(), "frozen builds must not manufacture a lock"
+def test_lock_upgrade_and_group_selection_use_the_same_environment(locked_project, tmp_path):
+ from pm.environment import PythonEnvironment
+ import tomllib
+
+ source, uv, env = locked_project
+ manifest = source / "pyproject.toml"
+ manifest.write_text(manifest.read_text().replace('base-dep==1.0', 'base-dep>=1,<2') +
+ '\n[dependency-groups]\nqa=["other-dep==1.0"]\n')
+ environment = PythonEnvironment(uv=uv, python=Path(sys.executable), destination=tmp_path / "candidate",
+ cache=tmp_path / "cache", env=env, offline=True)
+ environment.lock(source, timeout=60)
+ _wheel(tmp_path / "wheels", "base_dep", "1.1")
+ environment.lock(source, timeout=60)
+ packages = tomllib.loads((source / "uv.lock").read_text())["package"]
+ assert next(p["version"] for p in packages if p["name"] == "base-dep") == "1.0"
+ environment.lock(source, upgrade=True, timeout=60)
+ locked = (source / "uv.lock").read_bytes()
+ environment.create()
+ environment.sync(source, groups=["qa", "qa"], timeout=60)
+ assert _run([str(environment.executable), "-I", "-c",
+ "import base_dep, other_dep; print(base_dep.__version__, other_dep.__version__)"],
+ cwd=tmp_path, env=env) == "1.1 1.0"
+ assert (source / "uv.lock").read_bytes() == locked
+
+
def test_explicit_environment_installs_locked_members_without_live_selection(locked_project, tmp_path, monkeypatch):
from pm.environment import PythonEnvironment
import pm.paths
@@ -422,7 +454,6 @@ def test_explicit_workspace_preserves_seed_and_replays_copied_members(locked_pro
def test_live_apply_keeps_selection_on_failed_union(locked_project, tmp_path, monkeypatch):
- import importlib
from hermes_cli.runtime_paths import runtime_facts_path, selected_venv
from pm.lock import Facts
from pm.packages import Venv
@@ -438,7 +469,7 @@ def test_live_apply_keeps_selection_on_failed_union(locked_project, tmp_path, mo
monkeypatch.setenv("HERMES_HOME", env["HERMES_HOME"])
monkeypatch.setattr(pm.paths, "repo_root", lambda: source)
# Tool acquisition is the adapter's job; the same prepared env is not mutated.
- monkeypatch.setattr(importlib.import_module("pm.ensure"), "uv", lambda **kwargs: (str(uv), env))
+ monkeypatch.setattr("pm._uv._toolchain", lambda **kwargs: (uv, Path(sys.executable)))
original_env = dict(env)
prepared = Venv().apply(["chosen"], plugin_dirs=[source / "member"])
assert env == original_env
diff --git a/tests/pm/test_plugin_survival_contract.py b/tests/pm/test_plugin_survival_contract.py
index 9ae8bcb70e1..81fc22c94b6 100644
--- a/tests/pm/test_plugin_survival_contract.py
+++ b/tests/pm/test_plugin_survival_contract.py
@@ -35,7 +35,6 @@ from pathlib import Path
import pytest
import hermes_yaml as yaml
-import pm.plugins_state as pstate
import pm.workspace as ws
@@ -171,10 +170,7 @@ def admission_env(tmp_path, monkeypatch):
# Exercise the real dependency transaction in-process so the local uv
# fixture owns provisioning; worker transport is covered separately.
monkeypatch.setattr("pm.client.sync_venv", ensure.sync_venv)
- from pm.packages import uv_env
- monkeypatch.setattr(ensure, "uv", lambda **kwargs: (
- shutil.which("uv"), {**uv_env(kwargs.get("base_env")), "UV_PYTHON": sys.executable},
- ))
+ monkeypatch.setattr("pm._uv._toolchain", lambda **kwargs: (Path(shutil.which("uv")), Path(sys.executable)))
return tmp_path, home
diff --git a/tests/pm/test_recovery.py b/tests/pm/test_recovery.py
index 5997b5f52e1..394f5f80c03 100644
--- a/tests/pm/test_recovery.py
+++ b/tests/pm/test_recovery.py
@@ -12,7 +12,7 @@ import sys
import pytest
from pm.lock import Facts
-from pm.packages import uv_env
+from pm.runtime import runtime_environment
from tests.pm.test_workspace_build_inputs import _wheel
@pytest.fixture(autouse=True)
@@ -88,14 +88,12 @@ def test_repair_restores_recorded_plugin_dependencies_without_config(tmp_path, m
)
monkeypatch.setattr(paths, "repo_root", lambda: core)
monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))
- monkeypatch.setattr(engine, "uv", lambda **kwargs: (
- uv, {**uv_env(kwargs.get("base_env")), "UV_PYTHON": sys.executable, "UV_OFFLINE": "1"},
- ))
+ monkeypatch.setattr("pm._uv._toolchain", lambda **kwargs: (Path(uv), Path(sys.executable)))
monkeypatch.setattr(engine, "lazy_installs_allowed", lambda: True)
monkeypatch.setattr(workspace, "enabled_member_dirs", lambda: [plugin])
# The committed core lock is independent of the plugin union.
- env = {**uv_env(), "UV_PYTHON": sys.executable, "UV_OFFLINE": "1"}
- env.pop("UV_NO_CONFIG")
+ env = {**runtime_environment(), "UV_PYTHON": sys.executable, "UV_OFFLINE": "1"}
+ env.pop("UV_NO_CONFIG", None)
subprocess.run([uv, "lock"], cwd=core, env=env, capture_output=True, check=True, timeout=60)
engine.sync_venv([], explicit=True)
old = selected_venv(core)
@@ -194,12 +192,10 @@ def test_uncertain_profile_selection_refuses_sync_but_not_recorded_repair(tmp_pa
sibling_config.write_text("plugins:\n enabled: [worker-deps]\n", encoding="utf-8")
monkeypatch.setenv("HERMES_HOME", str(home))
monkeypatch.setattr(paths, "repo_root", lambda: core)
- monkeypatch.setattr(engine, "uv", lambda **kwargs: (
- uv, {**uv_env(kwargs.get("base_env")), "UV_PYTHON": sys.executable, "UV_OFFLINE": "1"},
- ))
+ monkeypatch.setattr("pm._uv._toolchain", lambda **kwargs: (Path(uv), Path(sys.executable)))
monkeypatch.setattr(engine, "lazy_installs_allowed", lambda: True)
- env = {**uv_env(), "UV_PYTHON": sys.executable, "UV_OFFLINE": "1"}
- env.pop("UV_NO_CONFIG")
+ env = {**runtime_environment(), "UV_PYTHON": sys.executable, "UV_OFFLINE": "1"}
+ env.pop("UV_NO_CONFIG", None)
subprocess.run([uv, "lock"], cwd=core, env=env, check=True, capture_output=True, timeout=60)
engine.sync_venv([], explicit=True)
old = selected_venv(core)
diff --git a/tests/pm/test_recovery_validation.py b/tests/pm/test_recovery_validation.py
index e172aec5490..f7b7c146191 100644
--- a/tests/pm/test_recovery_validation.py
+++ b/tests/pm/test_recovery_validation.py
@@ -1,7 +1,6 @@
"""PM validates real imports before it publishes a recovered dependency tree."""
from __future__ import annotations
-import importlib
import importlib.metadata
import os
from pathlib import Path
@@ -11,7 +10,7 @@ import sys
import pytest
from pm.package import InstallError
-from pm.packages import uv_env
+from pm.runtime import runtime_environment
from pm.recovery import validate_environment
@pytest.fixture(autouse=True)
@@ -37,11 +36,11 @@ def test_validation_rejects_a_missing_required_import(tmp_path, monkeypatch, dam
monkeypatch.setattr(paths, "repo_root", lambda: core)
uv = shutil.which("uv")
assert uv, "validation integration requires real uv"
- env = {**uv_env(), "UV_PYTHON": sys.executable}
- env.pop("UV_NO_CONFIG")
+ env = {**runtime_environment(), "UV_PYTHON": sys.executable}
+ env.pop("UV_NO_CONFIG", None)
workspace = tmp_path / "workspace"
candidate = tmp_path / "venv"
- monkeypatch.setattr(importlib.import_module("pm.ensure"), "uv", lambda **kwargs: (uv, env.copy()))
+ monkeypatch.setattr("pm._uv._toolchain", lambda **kwargs: (Path(uv), Path(sys.executable)))
from pm.workspace import lock_and_sync
lock_and_sync([], [], root=workspace, venv_dir=candidate)
diff --git a/tests/pm/test_runtime_entrypoints.py b/tests/pm/test_runtime_entrypoints.py
index bad7baff5a5..17aaadd512d 100644
--- a/tests/pm/test_runtime_entrypoints.py
+++ b/tests/pm/test_runtime_entrypoints.py
@@ -32,10 +32,7 @@ def test_ci_dependency_phase_uses_isolated_runtime(tmp_path, monkeypatch):
from scripts.ci import setup_toolchain
import subprocess
- import importlib
- ensure = importlib.import_module("pm.ensure")
-
- monkeypatch.setattr(ensure, "uv", lambda: pytest.fail("dependency work ran in bootstrap Python"))
+ monkeypatch.setattr("pm._uv._toolchain", lambda: pytest.fail("dependency work ran in bootstrap Python"))
monkeypatch.setenv("HERMES_RUNTIME_DIR", str(tmp_path / "tools"))
calls = []
python = tmp_path / "pm-runtime" / "python"
@@ -56,11 +53,9 @@ def test_ci_dependency_phase_uses_isolated_runtime(tmp_path, monkeypatch):
@pytest.mark.parametrize("distribution", ["nix", "docker"])
def test_packaged_runtime_uses_explicit_stamp_without_tool_downloads(tmp_path, monkeypatch, distribution):
- import importlib
from pm import runtime, paths
- engine = importlib.import_module("pm.ensure")
- monkeypatch.setattr(engine, "uv", lambda **kw: pytest.fail("packaged PM tried to download tools"))
+ monkeypatch.setattr("pm._uv._toolchain", lambda **kw: pytest.fail("packaged PM tried to download tools"))
project = tmp_path / "app"
project.mkdir()
monkeypatch.setattr(paths, "repo_root", lambda: project)
diff --git a/tests/pm/test_runtime_transaction.py b/tests/pm/test_runtime_transaction.py
index a8e36b92091..b9b36db3363 100644
--- a/tests/pm/test_runtime_transaction.py
+++ b/tests/pm/test_runtime_transaction.py
@@ -101,9 +101,7 @@ def test_real_uv_builds_separate_environment_before_selection(tmp_path, monkeypa
monkeypatch.setattr(paths, "repo_root", lambda: core)
monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))
monkeypatch.setattr("pm.workspace.enabled_member_dirs", lambda: [])
- ensure = importlib.import_module("pm.ensure")
- from pm.packages import uv_env
- monkeypatch.setattr(ensure, "uv", lambda **kw: (uv, {**uv_env(kw.get("base_env")), "UV_PYTHON": sys.executable}))
+ monkeypatch.setattr("pm._uv._toolchain", lambda **kw: (Path(uv), Path(sys.executable)))
prepared = Venv().apply([])
assert selected_venv(core) == base
candidate = prepared["environment"]
diff --git a/tests/pm/test_startup_recovery.py b/tests/pm/test_startup_recovery.py
index 2027b75defd..f1824afd6c3 100644
--- a/tests/pm/test_startup_recovery.py
+++ b/tests/pm/test_startup_recovery.py
@@ -12,7 +12,7 @@ import sys
import pytest
from pm.lock import Facts, Lockfile
-from pm.packages import uv_env
+from pm.runtime import runtime_environment
from pm.store import current_target, sha256_file, tree_digest
from tests.pm.test_workspace_build_inputs import _wheel
@@ -54,12 +54,10 @@ def test_bootstrap_repairs_before_dependency_activation(tmp_path, monkeypatch, m
monkeypatch.setenv("HERMES_HOME", str(home))
monkeypatch.setenv("HERMES_RUNTIME_DIR", str(tmp_path / "tools"))
monkeypatch.setattr(paths, "repo_root", lambda: core)
- monkeypatch.setattr(engine, "uv", lambda **kwargs: (
- uv, {**uv_env(kwargs.get("base_env")), "UV_PYTHON": sys.executable, "UV_OFFLINE": "1"},
- ))
+ monkeypatch.setattr("pm._uv._toolchain", lambda **kwargs: (Path(uv), Path(sys.executable)))
monkeypatch.setattr(engine, "lazy_installs_allowed", lambda: True)
- clean = {**uv_env(), "UV_PYTHON": sys.executable, "UV_OFFLINE": "1"}
- clean.pop("UV_NO_CONFIG")
+ clean = {**runtime_environment(), "UV_PYTHON": sys.executable, "UV_OFFLINE": "1"}
+ clean.pop("UV_NO_CONFIG", None)
subprocess.run([uv, "lock"], cwd=core, env=clean, capture_output=True, check=True, timeout=60)
engine.sync_venv([], explicit=True, plugin_dirs=[])
old = selected_venv(core)
diff --git a/tests/pm/test_union_installs_members.py b/tests/pm/test_union_installs_members.py
index a0c04ad8868..de1b017c9c4 100644
--- a/tests/pm/test_union_installs_members.py
+++ b/tests/pm/test_union_installs_members.py
@@ -66,13 +66,10 @@ def mini_workspace(tmp_path, monkeypatch):
store.mkdir()
venv = tmp_path / "venv"
- import importlib
import shutil
import pm.paths
- from pm.packages import uv_env
- monkeypatch.setattr(importlib.import_module("pm.ensure"), "uv",
- lambda **kwargs: (shutil.which("uv"), {**uv_env(kwargs.get("base_env")), "UV_PYTHON": sys.executable}))
+ monkeypatch.setattr("pm._uv._toolchain", lambda **kwargs: (Path(shutil.which("uv")), Path(sys.executable)))
monkeypatch.setattr(pm.paths, "repo_root", lambda: core)
monkeypatch.setattr(pm.paths, "store_root", lambda: store)
monkeypatch.setattr(ws.paths, "repo_root", lambda: core)
diff --git a/tests/pm/test_uv_cache.py b/tests/pm/test_uv_cache.py
index d5d102ad092..1b92803a470 100644
--- a/tests/pm/test_uv_cache.py
+++ b/tests/pm/test_uv_cache.py
@@ -15,12 +15,30 @@ def isolated_machine_home(tmp_path, monkeypatch):
-def test_uv_env_pins_cache_dir(monkeypatch, tmp_path):
- monkeypatch.setattr(pkgs, "uv_cache_dir", lambda: tmp_path / "c")
- env = pkgs.uv_env({"UV_CACHE_DIR": "/ambient/user/cache", "PATH": "x"})
- assert env["UV_CACHE_DIR"] == str(tmp_path / "c")
- # ambient UV_ vars are stripped, not inherited
- assert "UV_PROJECT_ENVIRONMENT" not in env
+def test_managed_environment_pins_cache_dir(monkeypatch, tmp_path):
+ import shutil
+ import sys
+ from pm.environment import managed_environment
+
+ uv = shutil.which("uv")
+ assert uv
+ monkeypatch.setattr("pm._uv._toolchain", lambda **kw: (Path(uv), Path(sys.executable)))
+ cache = tmp_path / "cache"
+ monkeypatch.setattr(pkgs, "uv_cache_dir", lambda: cache)
+ hostile = tmp_path / "ambient-cache"
+ monkeypatch.setenv("UV_CACHE_DIR", str(hostile))
+ project = tmp_path / "project"
+ project.mkdir()
+ (project / "pyproject.toml").write_text(
+ '[project]\nname="cache-proof"\nversion="1"\nrequires-python=">=3.11"\n'
+ '[tool.uv]\npackage=false\n', encoding="utf-8",
+ )
+ environment = managed_environment(tmp_path / "candidate", offline=True)
+ environment.create()
+ environment.lock(project)
+ environment.sync(project)
+ assert cache.is_dir()
+ assert not hostile.exists()
def test_uv_cache_dir_seeds_from_payload(monkeypatch, tmp_path):
diff --git a/tests/pm/test_uv_python.py b/tests/pm/test_uv_python.py
index 44679a06b73..ce616a7a5db 100644
--- a/tests/pm/test_uv_python.py
+++ b/tests/pm/test_uv_python.py
@@ -10,6 +10,7 @@ import sys
import pytest
+from pm._uv import _toolchain
from pm.lock import Facts, Lockfile
from pm.package import InstallError
from pm.packages import Python, Uv
@@ -37,9 +38,6 @@ def installed_uv(tmp_path, monkeypatch):
entry.mkdir(parents=True)
binary = entry / ("uv.exe" if os.name == "nt" else "uv")
shutil.copy2(uv, binary)
- uvx = Path(uv).with_name("uvx" + binary.suffix)
- assert uvx.is_file(), "the real uv distribution must include uvx"
- shutil.copy2(uvx, entry / uvx.name)
lock.set_pin("uv", "test", {target: {"url": "https://test.invalid/uv", "sha256": digest}})
lock.set_pin("python", "test", {target: {"url": "https://test.invalid/python", "sha256": digest}})
lock.save()
@@ -52,6 +50,19 @@ def installed_uv(tmp_path, monkeypatch):
return tmp_path, binary, facts, target, digest
+def test_internal_tooling_cannot_escape_package_queries(installed_uv):
+ from pm import env_for, installed_package
+
+ _, binary, facts, target, digest = installed_uv
+ assert "PATH" not in Uv().env(binary.parent, target)
+ # Legacy facts can contain PATH even after the package stops exporting it.
+ facts.record("uv", "test", binary.parent.name, {"PATH": [str(binary.parent)]},
+ binary.parent.parent, target=target, artifacts=[digest])
+ assert str(binary.parent) not in env_for("uv", "venv", base_env={"PATH": "external"})["PATH"]
+ with pytest.raises(ValueError, match="internal"):
+ installed_package("uv")
+
+
def test_all_uv_commands_keep_the_pm_interpreter(installed_uv, monkeypatch):
import pm.registry as registry
@@ -72,16 +83,11 @@ def test_all_uv_commands_keep_the_pm_interpreter(installed_uv, monkeypatch):
monkeypatch.setenv("UV_PYTHON", str(root / "ambient-python"))
monkeypatch.setenv("UV_PROJECT_ENVIRONMENT", str(root / "ambient-venv"))
before = dict(os.environ)
- managed_uv, env = importlib.import_module("pm.ensure").uv(realize=False)
- assert managed_uv == str(uv)
- assert env.get("UV_PYTHON") == str(python)
- assert "UV_PROJECT_ENVIRONMENT" not in env
- assert dict(os.environ) == before
- uvx, uvx_env = importlib.import_module("pm.ensure").uv("uvx", realize=False)
- assert Path(uvx) == uv.with_name("uvx" + uv.suffix)
- assert uvx_env["UV_PYTHON"] == str(python)
- subprocess.run([uvx, "--version"], cwd=root, env=uvx_env, check=True, capture_output=True, timeout=30)
+ from pm._uv import _toolchain
+ from pm.environment import managed_environment
+ assert _toolchain(realize=False) == (uv, python)
+ assert dict(os.environ) == before
project = root / "project"
project.mkdir()
(project / "pyproject.toml").write_text(
@@ -89,25 +95,16 @@ def test_all_uv_commands_keep_the_pm_interpreter(installed_uv, monkeypatch):
'[tool.uv]\npackage=false\n', encoding="utf-8",
)
(project / ".python-version").write_text(str(root / "host-only-python"), encoding="utf-8")
- env.pop("UV_NO_CONFIG")
- env.update({"UV_OFFLINE": "1", "UV_PYTHON_DOWNLOADS": "never"})
- environment = root / "candidate"
- env["VIRTUAL_ENV"] = str(environment)
- for args in (["venv", str(environment)], ["lock"], ["sync", "--frozen", "--active"],
- ["run", "--active", "--no-sync", "python", "-c", "import sys; print(sys.prefix)"]):
- result = subprocess.run([managed_uv, *args], cwd=project, env=env,
- capture_output=True, text=True, check=True, timeout=60)
- assert Path(result.stdout.strip()).resolve() == environment.resolve()
-
- incomplete = root / "store" / "uv-without-uvx"
- incomplete.mkdir()
- shutil.copy2(uv, incomplete / uv.name)
- facts.record("uv", "test", incomplete.name, {}, incomplete.parent,
- target=target, artifacts=[digest])
- ensure = importlib.import_module("pm.ensure")
- assert ensure.uv("uvx", realize=False)[0] is None
- with pytest.raises(InstallError, match="binary is missing"):
- ensure.uv("uvx")
+ environment = managed_environment(root / "candidate", offline=True)
+ assert environment.python == python
+ environment.create()
+ environment.lock(project)
+ environment.sync(project)
+ environment.check()
+ result = subprocess.run([str(environment.executable), "-I", "-c", "import sys; print(sys.prefix)"],
+ capture_output=True, text=True, check=True, timeout=30)
+ assert Path(result.stdout.strip()).resolve() == environment.destination.resolve()
+ assert dict(os.environ) == before
def test_uv_refuses_discovery_when_pm_python_is_missing(installed_uv, monkeypatch):
@@ -115,21 +112,19 @@ def test_uv_refuses_discovery_when_pm_python_is_missing(installed_uv, monkeypatc
ensure = importlib.import_module("pm.ensure")
monkeypatch.setattr(ensure, "lazy_installs_allowed", lambda: False)
monkeypatch.setenv("UV_PYTHON", str(root / "ambient-python"))
- managed_uv, env = ensure.uv(realize=False)
- assert managed_uv is None
- assert "UV_PYTHON" not in env
+ assert _toolchain(realize=False) is None
assert not (root / "store" / "python-test").exists()
with pytest.raises(InstallError, match="python"):
- ensure.uv()
+ _toolchain()
entry = root / "store" / "missing-binary"
entry.mkdir()
facts.record("python", "test", entry.name, {}, entry.parent,
target=target, artifacts=[digest])
recorded = facts.path.read_bytes()
- assert ensure.uv(realize=False)[0] is None
+ assert _toolchain(realize=False) is None
with pytest.raises(InstallError, match="lazy installs are disabled: python"):
- ensure.uv()
+ _toolchain()
assert facts.path.read_bytes() == recorded
assert not list(entry.iterdir())
@@ -174,16 +169,16 @@ def test_bundled_uv_uses_a_verified_writable_python_without_changing_runtime(ins
raise AssertionError("the verified Python must be copied without downloading")
monkeypatch.setattr(Store, "fetch_many", no_download)
- assert ensure.uv(realize=False)[0] is None
+ assert _toolchain(realize=False) is None
assert not writable.exists()
with pytest.raises(InstallError, match="lazy installs are disabled"):
- ensure.uv()
+ _toolchain()
assert not writable.exists()
- resolved_uv, env = ensure.uv(explicit=True)
+ resolved_uv, python = _toolchain(explicit=True)
copied = writable / entry.name
- assert resolved_uv == str(uv_binary)
- assert env["UV_PYTHON"] == str(copied / "python.exe")
+ assert resolved_uv == uv_binary
+ assert python == copied / "python.exe"
assert tree_digest(copied) == shipped_digest
copied_fact = Facts(writable / "facts.json").get("python")
assert copied_fact["digest"] == shipped_digest
@@ -197,8 +192,8 @@ def test_bundled_uv_uses_a_verified_writable_python_without_changing_runtime(ins
with monkeypatch.context() as reuse:
reuse.setattr(shutil, "copytree", no_copy)
- assert ensure.uv(realize=False)[1]["UV_PYTHON"] == env["UV_PYTHON"]
- assert ensure.uv()[1]["UV_PYTHON"] == env["UV_PYTHON"]
+ assert _toolchain(realize=False)[1] == python
+ assert _toolchain()[1] == python
assert facts.path.read_bytes() == before
assert tree_digest(entry) == shipped_digest
diff --git a/tests/pm/test_venv_sync_ambient_config.py b/tests/pm/test_venv_sync_ambient_config.py
index f2aac6a6a94..af093f80e6e 100644
--- a/tests/pm/test_venv_sync_ambient_config.py
+++ b/tests/pm/test_venv_sync_ambient_config.py
@@ -1,24 +1,11 @@
-"""Desired behavior: ambient user uv configuration must not affect pm's
-venv sync, while the project's own [tool.uv] settings stay honored.
-
-This is the contract the installers' old run_locked_uv_sync() used to
-guarantee (#82446, #21269, #83914). Now that install.sh / install.ps1
-delegate to ``python -m pm.cli install``, the contract lives in pm's
-venv-sync env. We assert the behavior (a locked project sync succeeds
-under pm's env even when the ambient environment is poisoned), not the
-names of helper functions.
-
-The negative control is the load-bearing half: the same poisoned ambient
-env fed to uv RAW must break the sync — otherwise the test could pass for
-the wrong reason and never catch a regression.
-"""
-
+"""Ambient uv settings cannot steer PM; project configuration still can."""
from __future__ import annotations
import os
+from pathlib import Path
import shutil
import subprocess
-from pathlib import Path
+import sys
import pytest
@@ -29,113 +16,41 @@ def isolated_machine_home(tmp_path, monkeypatch):
monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
-def _write_project(root: Path) -> None:
- """A project whose [tool.uv] the lock depends on: hide it and uv
- rejects the lock (the #82446 shape)."""
- (root / "pyproject.toml").write_text(
- """[project]
-name = "venv-sync-regression"
-version = "0.1.0"
-requires-python = ">=3.11"
-
-[project.optional-dependencies]
-all = []
+def test_ambient_uv_config_does_not_affect_pm_venv_sync(tmp_path, monkeypatch):
+ from pm.environment import managed_environment
-[tool.uv]
-package = false
-exclude-newer = "14 days"
-""",
- encoding="utf-8",
- )
-
-
-def real_uv() -> str:
uv = shutil.which("uv")
- if uv is None:
- pytest.skip("uv is unavailable")
- return uv
-
-
-def locked_project(real_uv, tmp_path: Path) -> Path:
- """A temp project with a lock generated in a clean ambient env."""
+ assert uv, "the isolation contract requires real uv"
+ monkeypatch.setattr("pm._uv._toolchain", lambda **kwargs: (Path(uv), Path(sys.executable)))
project = tmp_path / "project"
project.mkdir()
- _write_project(project)
- clean = os.environ.copy()
- for key in ("UV_NO_CONFIG", "UV_CONFIG_FILE", "UV_DEFAULT_INDEX", "XDG_CONFIG_HOME", "XDG_CONFIG_DIRS"):
- clean.pop(key, None)
- clean["UV_OFFLINE"] = "1"
- locked = subprocess.run(
- [real_uv, "lock"], cwd=project, env=clean,
- capture_output=True, text=True, check=False,
+ (project / "pyproject.toml").write_text(
+ '[project]\nname="venv-sync-regression"\nversion="1"\nrequires-python=">=3.11"\n'
+ '[tool.uv]\npackage=false\nexclude-newer="14 days"\n', encoding="utf-8",
)
- assert locked.returncode == 0, locked.stderr
- return project
-
-
-def _poisoned_env() -> dict:
- env = os.environ.copy()
- env["UV_NO_CONFIG"] = "1"
- env["UV_CONFIG_FILE"] = "/poison/uv.toml"
- # A hostile index: resolution against it can only fail, so if it ever
- # reaches uv the sync is observably broken.
- env["UV_DEFAULT_INDEX"] = "https://poison.invalid/simple"
- env["XDG_CONFIG_HOME"] = "/poison/user"
- env["XDG_CONFIG_DIRS"] = "/poison/system"
- return env
-
-
-def test_ambient_uv_config_does_not_affect_pm_venv_sync(real_uv, locked_project, monkeypatch):
- """Poison the ambient env, then sync through pm's venv-sync env. The
- sync must succeed with the project's [tool.uv] honored — identical to
- the clean-env outcome."""
- poisoned = _poisoned_env()
- monkeypatch.setenv("UV_NO_CONFIG", "1")
- monkeypatch.setenv("UV_CONFIG_FILE", "/poison/uv.toml")
- monkeypatch.setenv("UV_DEFAULT_INDEX", "https://poison.invalid/simple")
-
- # Negative control: uv with the RAW poisoned ambient env rejects the
- # lock (project config hidden by UV_NO_CONFIG). Proves the poison is a
- # real threat the test would catch.
- raw = subprocess.run(
- [real_uv, "lock", "--check"], cwd=locked_project,
- env=poisoned, capture_output=True, text=True, check=False,
- )
- assert raw.returncode != 0, "negative control: raw poisoned env must fail"
-
- # Behavior: pm's venv-sync env makes the ambient config a no-op.
- from pm.packages import uv_env
-
- env = uv_env(base_env=poisoned)
- # The venv-sync shape restores project-config visibility (pm_uv with a
- # venv pops UV_NO_CONFIG); XDG config discovery is isolated to an
- # empty dir so ambient uv.toml can't steer either.
- env.pop("UV_NO_CONFIG", None)
- assert env.get("XDG_CONFIG_HOME") not in ("/poison/user", None)
-
- with_pm = subprocess.run(
- [real_uv, "lock", "--check"], cwd=locked_project,
- env=env, capture_output=True, text=True, check=False,
- )
- assert with_pm.returncode == 0, with_pm.stderr
-
-
-def test_uv_env_strips_ambient_uv_overrides(monkeypatch):
- """The env pm hands uv carries none of the ambient UV_* overrides."""
- monkeypatch.setenv("UV_NO_CONFIG", "1")
- monkeypatch.setenv("UV_CONFIG_FILE", "/poison/uv.toml")
- monkeypatch.setenv("UV_DEFAULT_INDEX", "https://poison.invalid/simple")
- monkeypatch.setenv("XDG_CONFIG_HOME", "/poison/user")
- monkeypatch.setenv("XDG_CONFIG_DIRS", "/poison/system")
-
- from pm.packages import uv_env
-
- env = uv_env()
- assert "UV_NO_CONFIG" in env # hermetic default for non-project calls
- assert "UV_CONFIG_FILE" not in env
- assert "UV_DEFAULT_INDEX" not in env
- # Config discovery is redirected off the ambient dirs.
- assert env.get("XDG_CONFIG_HOME") not in ("/poison/user", None)
- assert env.get("XDG_CONFIG_DIRS") not in ("/poison/system", None)
+ environment = managed_environment(tmp_path / "candidate", offline=True)
+ environment.lock(project)
+ locked = (project / "uv.lock").read_bytes()
+ config = tmp_path / "config"
+ (config / "uv").mkdir(parents=True)
+ (config / "uv" / "uv.toml").write_text('required-version="<0.0.1"\n')
+ for key, value in {
+ "UV_NO_CONFIG": "1", "UV_CONFIG_FILE": "/poison/uv.toml",
+ "UV_DEFAULT_INDEX": "https://poison.invalid/simple", "UV_PYTHON": "/poison/python",
+ "UV_PROJECT_ENVIRONMENT": str(tmp_path / "unrelated-environment"),
+ "UV_PROJECT": "/poison/project", "VIRTUAL_ENV": "/poison/venv",
+ "PYTHONPATH": "/poison/imports", "XDG_CONFIG_HOME": str(config), "XDG_CONFIG_DIRS": str(config),
+ }.items():
+ monkeypatch.setenv(key, value)
+ before = dict(os.environ)
+ raw = subprocess.run([uv, "lock", "--check"], cwd=project,
+ capture_output=True, text=True, timeout=30)
+ assert raw.returncode != 0, "negative control: raw poisoned environment must fail"
+ environment = managed_environment(tmp_path / "candidate", offline=True)
+ environment.create()
+ environment.sync(project, locked=True)
+ environment.check()
+ assert environment.executable.is_file()
+ assert not (tmp_path / "unrelated-environment").exists()
+ assert (project / "uv.lock").read_bytes() == locked
+ assert dict(os.environ) == before
diff --git a/tests/pm/test_workspace.py b/tests/pm/test_workspace.py
index 321bc30f372..551f9abb290 100644
--- a/tests/pm/test_workspace.py
+++ b/tests/pm/test_workspace.py
@@ -10,9 +10,7 @@ core + plugin deps into ONE lock; conflict = loud refusal.
from __future__ import annotations
-import importlib
import os
-import subprocess
from pathlib import Path
import pytest
@@ -274,8 +272,7 @@ def test_sync_failure_is_never_a_conflict(tmp_path, monkeypatch):
stdout = ""
monkeypatch.setattr(ws, "_generate_pyproject", lambda *a, **k: (Path("/x/ws"), False))
- monkeypatch.setattr(importlib.import_module("pm.ensure"), "uv",
- lambda **kwargs: ("uv", {"UV_CACHE_DIR": "/x/cache", "UV_PYTHON": "pm-python"}))
+ monkeypatch.setattr("pm._uv._toolchain", lambda **kwargs: (Path("uv"), Path("pm-python")))
captured = {}
@@ -309,11 +306,8 @@ def test_staging_root_and_env_are_honored_without_live_mutation(monkeypatch, tmp
return FakeProc()
monkeypatch.setattr(ws, "_generate_pyproject", lambda *a, **k: (staging, False))
- monkeypatch.setattr(
- importlib.import_module("pm.ensure"), "uv",
- lambda **kwargs: ("uv", {**(kwargs.get("base_env") or {}),
- "UV_CACHE_DIR": "/x/cache", "UV_PYTHON": "pm-python"}),
- )
+ monkeypatch.setattr("pm._uv._toolchain", lambda **kwargs: (Path("uv"), Path("pm-python")))
+ monkeypatch.setattr("pm.packages.uv_cache_dir", lambda: tmp_path / "cache")
monkeypatch.setattr(ws.subprocess, "run", fake_run)
live_key = "PM_WORKSPACE_TEST_SENTINEL"
@@ -326,7 +320,7 @@ def test_staging_root_and_env_are_honored_without_live_mutation(monkeypatch, tmp
assert Path(seen["cwd"]) == staging
assert seen["env"][live_key] == "staged" # staged env wins
- assert seen["env"]["UV_CACHE_DIR"] == "/x/cache" # uv_env layered on top
+ assert seen["env"]["UV_CACHE_DIR"] == str(tmp_path / "cache")
assert seen["env"]["UV_PROJECT_ENVIRONMENT"] == str(tmp_path / "staging-venv")
assert seen["env"]["UV_PYTHON"] == "pm-python"
assert os.environ[live_key] == "live" # live env untouched
@@ -348,8 +342,7 @@ def test_changed_root_seeds_from_committed_lock_unchanged_keeps_extended(
stderr = ""
stdout = ""
- monkeypatch.setattr(importlib.import_module("pm.ensure"), "uv",
- lambda **kwargs: ("uv", {"UV_PYTHON": "pm-python", "UV_CACHE_DIR": str(tmp_path / "cache")}))
+ monkeypatch.setattr("pm._uv._toolchain", lambda **kwargs: (Path("uv"), Path("pm-python")))
monkeypatch.setattr(ws.subprocess, "run", lambda cmd, **k: FakeProc())
root = ws.workspace_root()
diff --git a/tests/pm/test_workspace_build_inputs.py b/tests/pm/test_workspace_build_inputs.py
index fc5700340bc..46d2da56fc7 100644
--- a/tests/pm/test_workspace_build_inputs.py
+++ b/tests/pm/test_workspace_build_inputs.py
@@ -1,5 +1,4 @@
"""Workspace generation carries the source inputs of a buildable core."""
-import importlib
import json
from pathlib import Path
import shutil
@@ -9,7 +8,6 @@ import sys
import pytest
from pm import workspace
-from pm.packages import uv_env
@pytest.fixture(autouse=True)
@@ -38,8 +36,7 @@ def test_real_build_inputs_stay_in_generated_root(tmp_path, monkeypatch):
root, venv = tmp_path / "staging", tmp_path / "venv"
uv = shutil.which("uv")
assert uv is not None
- monkeypatch.setattr(importlib.import_module("pm.ensure"), "uv",
- lambda **kwargs: (uv, {**uv_env(kwargs.get("base_env")), "UV_PYTHON": sys.executable}))
+ monkeypatch.setattr("pm._uv._toolchain", lambda **kwargs: (Path(uv), Path(sys.executable)))
workspace.lock_and_sync([], [], root=root, venv_dir=venv)
python = venv / ("Scripts/python.exe" if sys.platform == "win32" else "bin/python")
probe = subprocess.run([str(python), "-c", "import buildable_core; print(buildable_core.VALUE)"],
@@ -122,8 +119,7 @@ def test_plugin_can_move_compatible_transitive_but_not_exact_requirement(tmp_pat
uv = shutil.which("uv")
assert uv
monkeypatch.setattr(workspace.paths, "repo_root", lambda: core)
- monkeypatch.setattr(importlib.import_module("pm.ensure"), "uv",
- lambda **kwargs: (uv, {**uv_env(kwargs.get("base_env")), "UV_PYTHON": sys.executable}))
+ monkeypatch.setattr("pm._uv._toolchain", lambda **kwargs: (Path(uv), Path(sys.executable)))
baseline, first_env = tmp_path / "baseline", tmp_path / "first-env"
workspace.lock_and_sync([], [], root=baseline, venv_dir=first_env)
first_lock = (baseline / "uv.lock").read_bytes()
diff --git a/tests/pm/test_workspace_output_encoding.py b/tests/pm/test_workspace_output_encoding.py
index f5ba05cc552..20053dfa152 100644
--- a/tests/pm/test_workspace_output_encoding.py
+++ b/tests/pm/test_workspace_output_encoding.py
@@ -2,7 +2,6 @@
import importlib
import locale
-import os
import subprocess
import sys
@@ -42,11 +41,9 @@ def test_uv_failure_retains_utf8_build_diagnostic(
raw = diagnostic.encode("utf-8") + suffix + b"\n"
expected = diagnostic + ("�" if suffix else "")
monkeypatch.setattr(ws, "_generate_pyproject", lambda *a, **k: (tmp_path, False))
- monkeypatch.setattr(
- importlib.import_module("pm.ensure"), "uv",
- lambda **kwargs: (sys.executable, {**os.environ, "UV_PYTHON": sys.executable,
- "UV_CACHE_DIR": str(tmp_path / "cache")}),
- )
+ from pathlib import Path
+
+ monkeypatch.setattr("pm._uv._toolchain", lambda **kwargs: (Path(sys.executable), Path(sys.executable)))
completed = []
def run_uv(cmd, **kwargs):