Skip to content

The agent that grows with you

fix(update): address review on stale-VIRTUAL_ENV pin

mrmixx-max33e813da17fc
diff --git a/hermes_cli/main.py b/hermes_cli/main.py
index b0251a3b908..6ebaf4cf316 100644
--- a/hermes_cli/main.py
+++ b/hermes_cli/main.py
@@ -9566,6 +9566,58 @@ def _repair_venv_via_import_probes(
return "failed"
+def _is_uv_command(install_cmd_prefix: list[str]) -> bool:
+ """True when the install command is a uv/uvx invocation.
+
+ Handles a bare uv binary (``uv`` / ``uvx``, any extension), a path to
+ one, and ``python -m uv`` / ``python -m uvx`` — the naive basename check
+ misses the module form and launcher wrappers whose name does not contain
+ "uv".
+ """
+ if not install_cmd_prefix:
+ return False
+ first = str(install_cmd_prefix[0]).lower()
+ if "uv" in Path(first).name:
+ return True
+ # python -m uv / python -m uvx
+ if len(install_cmd_prefix) >= 3 and first.endswith(("python", "python.exe")):
+ return install_cmd_prefix[1] == "-m" and install_cmd_prefix[2] in (
+ "uv",
+ "uvx",
+ )
+ return False
+
+
+def _insert_python_pin(args: list[str]) -> list[str]:
+ """Insert ``--python <sys.executable>`` into a uv command line.
+
+ If the caller already passed ``--python``, its value wins (uv's last-wins
+ semantics are ambiguous; the explicit caller intent should not be
+ overridden by the fallback pin).
+ """
+ if "--python" in args:
+ return args
+ return [args[0], "--python", str(sys.executable), *args[1:]]
+
+
+def _interpreter_scripts_dir() -> Path | None:
+ """Scripts/bin directory of the running interpreter (sys.executable).
+
+ Used when pinning an install to ``sys.executable`` on a site-packages
+ install where ``PROJECT_ROOT / "venv"`` does not exist: the entry-point
+ shims uv rewrites live next to the interpreter, not under a project venv.
+ """
+ exe = Path(sys.executable)
+ parent = exe.parent
+ scripts_candidates = (
+ [parent / "Scripts"] if _is_windows() else [parent / "bin"]
+ )
+ for cand in scripts_candidates:
+ if cand.is_dir():
+ return cand
+ return None
+
+
def _install_python_dependencies_with_optional_fallback(
install_cmd_prefix: list[str],
*,
@@ -9604,17 +9656,25 @@ def _install_python_dependencies_with_optional_fallback(
and env.get("VIRTUAL_ENV")
and not Path(env["VIRTUAL_ENV"]).is_dir()
and install_cmd_prefix
- and "uv" in Path(install_cmd_prefix[0]).name.lower()
+ and _is_uv_command(install_cmd_prefix)
):
# Only uv needs the explicit pin; pip resolves the target from
# sys.executable itself and has no --python flag.
pin_python = True
env = {**env}
env.pop("VIRTUAL_ENV", None)
+ # When we pin to sys.executable, the entry-point shims that uv will
+ # rewrite live in that interpreter's Scripts/bin directory, NOT in
+ # PROJECT_ROOT/venv (which does not exist on a site-packages install).
+ # Quarantining the wrong dir means the running hermes.exe stays locked
+ # on Windows and the install fails exactly like the original bug. Only
+ # override when the venv-derived dir is missing; otherwise keep it.
+ if scripts_dir is None and _is_windows():
+ scripts_dir = _interpreter_scripts_dir()
def _install(args: list[str]) -> None:
if pin_python:
- args = [args[0], "--python", str(sys.executable), *args[1:]]
+ args = _insert_python_pin(args)
# strict_quarantine: this is the UPDATE dependency sync. A shim that
# cannot be renamed aside proves a hard venv hold; running uv anyway
# is how installs strand half-updated (#87331). ShimQuarantineError
diff --git a/tests/hermes_cli/test_update_stale_virtualenv.py b/tests/hermes_cli/test_update_stale_virtualenv.py
index 90c56cc1cad..291edddecb8 100644
--- a/tests/hermes_cli/test_update_stale_virtualenv.py
+++ b/tests/hermes_cli/test_update_stale_virtualenv.py
@@ -1,11 +1,10 @@
-"""Test: _install_python_dependencies_with_optional_fallback mit stale VIRTUAL_ENV.
+"""Test: _install_python_dependencies_with_optional_fallback with stale VIRTUAL_ENV.
-Simuliert den heutigen Crash: pip/System-Python-Install, wo PROJECT_ROOT =
-site-packages ist und VIRTUAL_ENV=PROJECT_ROOT/venv nicht existiert.
+Simulates the real crash: a pip/system-Python install where PROJECT_ROOT is
+site-packages and VIRTUAL_ENV=PROJECT_ROOT/venv does not exist.
"""
import os
import sys
-import types
import unittest
from pathlib import Path
from unittest import mock
@@ -14,15 +13,12 @@ import hermes_cli.main as main_mod
class StaleVirtualEnvTest(unittest.TestCase):
- def _call(self, uv_bin, venv_path, fake_executable):
- """Führe die Funktion mit gemocktem uv/env aus und fange den subprocess-Aufruf."""
+ def _call(self, uv_cmd, venv_path, fake_executable, is_windows=False):
+ """Run the function with a mocked uv/env and capture the subprocess call."""
captured = []
- real_run_quarantined = main_mod._run_quarantined_install
-
def fake_quarantine(cmd, *, env=None, scripts_dir=None):
- captured.append((list(cmd), dict(env or {})))
- # Nicht wirklich installieren; Verhalten wie Erfolg simulieren.
+ captured.append((list(cmd), dict(env or {}), scripts_dir))
return None
def fake_verify(prefix, *, env=None):
@@ -31,46 +27,88 @@ class StaleVirtualEnvTest(unittest.TestCase):
with mock.patch.object(main_mod, "_run_quarantined_install", fake_quarantine), \
mock.patch.object(main_mod, "_verify_console_scripts_installed", fake_verify), \
mock.patch.object(main_mod, "_venv_scripts_dir", return_value=None), \
- mock.patch.object(main_mod, "_is_windows", return_value=False), \
+ mock.patch.object(main_mod, "_is_windows", return_value=is_windows), \
mock.patch.object(main_mod.sys, "executable", fake_executable), \
mock.patch.object(main_mod, "PROJECT_ROOT", Path("/fake/project")):
main_mod._install_python_dependencies_with_optional_fallback(
- [str(uv_bin), "pip"],
+ list(uv_cmd),
env={"VIRTUAL_ENV": str(venv_path)},
group="all",
)
return captured
def test_stale_virtualenv_pins_python(self):
- """VIRTUAL_ENV zeigt auf nicht-existierendes venv -> --python sys.executable."""
+ """VIRTUAL_ENV points at a nonexistent venv -> --python sys.executable."""
captured = self._call(
- uv_bin=Path("/fake/uv"),
- venv_path=Path("/fake/project/venv"), # existiert nicht
+ uv_cmd=[Path("/fake/uv"), "pip"],
+ venv_path=Path("/fake/project/venv"), # does not exist
fake_executable="/fake/python311/python.exe",
)
- self.assertTrue(captured, "kein subprocess-Aufruf erfasst")
- cmd, env = captured[0]
- # --python muss nach 'install' stehen: uv pip install --python <exe> ...
+ self.assertTrue(captured, "no subprocess call captured")
+ cmd, env, _ = captured[0]
+ # --python must come after 'install': uv pip install --python <exe> ...
self.assertIn("install", cmd)
self.assertIn("--python", cmd)
self.assertEqual(cmd[cmd.index("--python") + 1], "/fake/python311/python.exe")
- # VIRTUAL_ENV aus env entfernt
+ # VIRTUAL_ENV removed from env
self.assertNotIn("VIRTUAL_ENV", env)
def test_existing_virtualenv_keeps_env(self):
- """VIRTUAL_ENV zeigt auf existierendes venv -> unverändert, kein --python."""
+ """VIRTUAL_ENV points at an existing venv -> unchanged, no --python."""
real_venv = Path(sys.executable).resolve().parent.parent
if not real_venv.is_dir():
- self.skipTest("kein echtes venv im Testlauf verfügbar")
+ self.skipTest("no real venv available in this test run")
captured = self._call(
- uv_bin=Path("/fake/uv"),
+ uv_cmd=[Path("/fake/uv"), "pip"],
venv_path=real_venv,
fake_executable=sys.executable,
)
- cmd, env = captured[0]
+ cmd, env, _ = captured[0]
self.assertNotIn("--python", cmd)
self.assertEqual(env.get("VIRTUAL_ENV"), str(real_venv))
+ def test_python_dash_m_uv_is_detected(self):
+ """python -m uv must also trigger the pin (naive basename check misses it)."""
+ captured = self._call(
+ uv_cmd=[Path("/fake/python"), "-m", "uv", "pip"],
+ venv_path=Path("/fake/project/venv"), # does not exist
+ fake_executable="/fake/python311/python.exe",
+ )
+ self.assertTrue(captured, "no subprocess call captured")
+ cmd, _, _ = captured[0]
+ self.assertIn("--python", cmd)
+ self.assertEqual(cmd[cmd.index("--python") + 1], "/fake/python311/python.exe")
+
+ def test_existing_python_flag_wins(self):
+ """A caller-supplied --python is not duplicated by the pin."""
+ captured = self._call(
+ uv_cmd=[Path("/fake/uv"), "pip"],
+ venv_path=Path("/fake/project/venv"),
+ fake_executable="/fake/python311/python.exe",
+ )
+ # Force the caller path through a manual pin with a pre-existing flag.
+ args = ["install", "--python", "/caller/choice/python.exe", "hermes"]
+ pinned = main_mod._insert_python_pin(args)
+ self.assertEqual(pinned, args, "existing --python must win")
+ self.assertEqual(pinned.count("--python"), 1)
+
+ def test_windows_pins_quarantine_to_interpreter_scripts_dir(self):
+ """On Windows with a missing project venv, quarantine must target the
+ interpreter's Scripts dir (where the shims actually live), not None."""
+ fake_scripts = Path("/fake/python311/Scripts")
+ with mock.patch.object(
+ main_mod, "_interpreter_scripts_dir", return_value=fake_scripts
+ ):
+ captured = self._call(
+ uv_cmd=[Path("/fake/uv"), "pip"],
+ venv_path=Path("/fake/project/venv"),
+ fake_executable="/fake/python311/python.exe",
+ is_windows=True,
+ )
+ self.assertTrue(captured, "no subprocess call captured")
+ _, _, scripts_dir = captured[0]
+ self.assertEqual(scripts_dir, fake_scripts)
+
if __name__ == "__main__":
unittest.main(verbosity=2)