Skip to content

The agent that grows with you

fix(gateway): resolve service runtimes through PM state

ethernet07ee9299790e
diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml
index 8c1e770271b..260a5c2be20 100644
--- a/.github/workflows/ci.yaml
+++ b/.github/workflows/ci.yaml
@@ -63,8 +63,6 @@ jobs:
id: classify
uses: ./.github/actions/detect-changes
with:
- sparse-checkout: scripts/ci/classify_changes.py
- sparse-checkout-cone-mode: false
github-token: ${{ github.token }}
# ─────────────────────────────────────────────────────────────────────
diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.py
index 30fa2e16fb3..a652aa01220 100644
--- a/hermes_cli/gateway.py
+++ b/hermes_cli/gateway.py
@@ -2666,11 +2666,20 @@ def _build_service_path_dirs(project_root: Path | None = None) -> list[str]:
return False
candidates = []
- venv_bin = project_root / "venv" / "bin"
- if _is_dir(venv_bin):
- candidates.append(str(venv_bin))
- elif sys.prefix != sys.base_prefix:
- candidates.append(str(Path(sys.prefix) / "bin"))
+ # pm-provisioned runtime venv first — the same authority _detect_venv_dir()
+ # trusts: under no-boot-through-venv sys.prefix equals base_prefix and the
+ # committed environment is the only record of which venv serves this install.
+ pm_venv = _pm_runtime_venv_dir(project_root)
+ if pm_venv is not None:
+ pm_bin = pm_venv / ("Scripts" if is_windows() else "bin")
+ if _is_dir(pm_bin):
+ candidates.append(str(pm_bin))
+ if not candidates:
+ venv_bin = project_root / "venv" / "bin"
+ if _is_dir(venv_bin):
+ candidates.append(str(venv_bin))
+ elif sys.prefix != sys.base_prefix:
+ candidates.append(str(Path(sys.prefix) / "bin"))
hermes_home = get_hermes_home()
extras = (project_root / "node_modules" / ".bin", hermes_home / "node" / "bin", hermes_home / "node_modules" / ".bin")
@@ -2711,9 +2720,45 @@ def _systemd_watchdog_seconds(hermes_home: str | Path | None = None) -> int:
reset_home_override(override_token)
+def _pm_managed_node_dirs(home: Path) -> list[str]:
+ """Node dirs pm's installed-state records under *home*'s store, resolved
+ via ``Facts.env_for`` (``{{store}}`` templates against the store beside
+ the recorded facts). Only dirs present on disk count; a record whose
+ store dirs are gone vouches for nothing.
+ """
+ from pm.lock import Facts
+
+ store = Path(home) / "tools"
+ facts = Facts(store / "facts.json")
+ dirs: list[str] = []
+ for name in ("node", "npm", "npx"):
+ for value in facts.env_for(name, store).get("PATH") or []:
+ if value and Path(value).is_dir():
+ dirs.append(str(value))
+ return dirs
+
+
def _append_node_dir_for_service(path_entries: list[str], hermes_root: Path | None = None) -> None:
- """Append the Node dir a service unit should use: managed ``<hermes_root>/node`` (profile-scoped)
- first — a unit survives reboots, so baking a shell-PATH Node is permanent breakage — else PATH lookup."""
+ """Append the Node dir a service unit should use.
+
+ PM's installed-state is the owner: facts.json under the target hermes
+ home's store records node/npm PATH entries, and those dirs — resolved via
+ Facts.env_for — are used verbatim. With managed Node recorded, consulting
+ the invoker's PATH would make a system unit depend on who ran sudo, so
+ lookup stops there. The legacy ``<hermes>/node`` tree and finally a PATH
+ lookup are fallbacks for installs pm never recorded.
+ """
+ home = Path(hermes_root) if hermes_root is not None else Path(get_hermes_home())
+ try:
+ managed_dirs = _pm_managed_node_dirs(home)
+ except Exception:
+ managed_dirs = [] # pm absent or unreadable: fall through to the legacy probe
+ for entry in managed_dirs:
+ if entry not in path_entries:
+ path_entries.append(entry)
+ if managed_dirs:
+ return
+
from hermes_constants import (hermes_managed_node_tree_present, iter_hermes_node_dirs)
managed_node_present = hermes_managed_node_tree_present(hermes_root)
for directory in iter_hermes_node_dirs(hermes_root) if managed_node_present else ():
@@ -6201,39 +6246,24 @@ def __getattr__(name): # PEP 562 — lazy so no import cycles
# ---- END PLUGIN-COMPAT ----
-def _pm_runtime_venv_dir() -> Path | None:
- """The venv pm provisioned for this install, resolved from pm's own
- records (facts.json + store layout) — never from interpreter state.
+def _pm_runtime_venv_dir(project_root: Path | None = None) -> Path | None:
+ """The venv pm provisioned for this install, resolved through
+ ``runtime_paths.selected_venv`` — the committed-environment contract —
+ never from interpreter state.
Under no-boot-through-venv the gateway runs the store python with the
venv's site-packages on PYTHONPATH, so ``sys.prefix`` always equals
``sys.base_prefix`` and ``VIRTUAL_ENV`` is unset in bundled installs;
- prefix/env probing silently degrades. pm is the authority instead: a
- bundled install keeps its relocatable venv beside the manifest (a
- sibling of the store), a dev install syncs the project venv
- (``venv``/``.venv``, per ``hermes_constants.project_venv_dir`` — the
- same layout ``pm.packages.Venv.venv_dir`` materializes). The venv fact
- must exist: pm only vouches for what it provisioned.
+ prefix/env probing silently degrades. Resolution follows the committed-
+ environment contract: a committed selection is returned as-is, a host
+ with nothing committed yields nothing launchable, and a malformed
+ selection raises — fail closed, never a silently wrong venv.
"""
- try:
- from pm import paths
- from pm.lock import Facts
- except Exception:
- return None
- try:
- if not Facts(paths.facts_path()).get("venv"):
- return None
- except Exception:
- return None
- store = paths.store_root()
- bundled = store.parent / "venv"
- if (store.parent / "manifest.json").is_file():
- return bundled if bundled.is_dir() else None
- try:
- from hermes_constants import project_venv_dir
- except ImportError:
- return None
- return project_venv_dir(paths.repo_root())
+ root = Path(project_root) if project_root is not None else PROJECT_ROOT
+ from hermes_cli.runtime_paths import selected_venv
+
+ venv = selected_venv(root) # a malformed committed selection raises: fail closed
+ return venv if venv.is_dir() else None
def _systemd_watchdog_service_fields(
hermes_home: str | Path | None = None,
diff --git a/tests/hermes_cli/test_gateway_service.py b/tests/hermes_cli/test_gateway_service.py
index 2d5eb13bdd4..5a1be977185 100644
--- a/tests/hermes_cli/test_gateway_service.py
+++ b/tests/hermes_cli/test_gateway_service.py
@@ -1151,54 +1151,62 @@ class TestGatewaySystemServiceRouting:
assert run_calls == []
+def _seed_pm_environment(tmp_path, monkeypatch, with_venv_fact=True):
+ """Commit a pm environment the way ``pm sync`` records it: an install-keyed
+ facts.json whose venv fact names a committed environment generation under
+ the install state (pyvenv.cfg included). Returns
+ ``(project_root, environment_dir)``."""
+ from hermes_cli.runtime_paths import install_state_dir
+
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path)) # installs_root() under the test root
+ project_root = tmp_path / "payload" / "hermes-agent"
+ project_root.mkdir(parents=True)
+ state = install_state_dir(project_root)
+ environment = state / "environments" / "gen-1"
+ environment.mkdir(parents=True)
+ (environment / "pyvenv.cfg").write_text("", encoding="utf-8")
+ packages = (
+ {"venv": {"stamp": "abc", "extras": [], "environment": str(environment)}}
+ if with_venv_fact
+ else {}
+ )
+ (state / "facts.json").write_text(
+ json.dumps({"schema": 1, "packages": packages}), encoding="utf-8"
+ )
+ return project_root, environment
+
+
class TestDetectVenvDir:
"""Tests for _detect_venv_dir() virtualenv detection.
- pm's facts/store resolution is the primary source; each legacy-probe
- test isolates it (``_pm_runtime_venv_dir`` patched to None) so the
- fallbacks are exercised deterministically regardless of whether the
- host checkout has pm-provisioned a venv.
+ pm's committed-environment resolution (runtime_paths.selected_venv) is
+ the primary source; each legacy-probe test isolates it
+ (``_pm_runtime_venv_dir`` patched to None) so the fallbacks are exercised
+ deterministically regardless of whether the host checkout has
+ pm-provisioned a venv.
"""
def test_resolves_pm_provisioned_venv_without_virtual_env(self, tmp_path, monkeypatch):
- """No sys.prefix venv, no VIRTUAL_ENV anywhere — the pm-provisioned
- venv (facts + store layout) is the answer."""
+ """No sys.prefix venv, no VIRTUAL_ENV anywhere — the pm-committed
+ environment (venv fact + selected_venv contract) is the answer."""
monkeypatch.setattr("sys.prefix", "/usr")
monkeypatch.setattr("sys.base_prefix", "/usr")
monkeypatch.delenv("VIRTUAL_ENV", raising=False)
monkeypatch.delenv("HERMES_RUNTIME_DIR", raising=False)
- monkeypatch.setattr(gateway_cli, "PROJECT_ROOT", tmp_path)
+ project_root, environment = _seed_pm_environment(tmp_path, monkeypatch)
+ monkeypatch.setattr(gateway_cli, "PROJECT_ROOT", project_root)
- payload = tmp_path / "payload"
- store = payload / "tools"
- venv = payload / "venv"
- venv.mkdir(parents=True)
- (payload / "manifest.json").write_text("{}", encoding="utf-8")
- (store / "facts.json").write_text(
- json.dumps(
- {"schema": 1, "packages": {"venv": {"stamp": "abc", "extras": []}}}
- ),
- encoding="utf-8",
- )
- monkeypatch.setenv("HERMES_RUNTIME_DIR", str(store))
-
- assert gateway_cli._detect_venv_dir() == venv
+ assert gateway_cli._detect_venv_dir() == environment
def test_pm_resolution_none_without_venv_fact(self, tmp_path, monkeypatch):
- """A store without a venv fact does not vouch — no pm answer."""
+ """A committed state without a venv fact does not vouch — no pm answer."""
monkeypatch.setattr("sys.prefix", "/usr")
monkeypatch.setattr("sys.base_prefix", "/usr")
monkeypatch.delenv("VIRTUAL_ENV", raising=False)
- monkeypatch.setattr(gateway_cli, "PROJECT_ROOT", tmp_path)
-
- payload = tmp_path / "payload"
- store = payload / "tools"
- (payload / "venv").mkdir(parents=True)
- (payload / "manifest.json").write_text("{}", encoding="utf-8")
- (store / "facts.json").write_text(
- json.dumps({"schema": 1, "packages": {}}), encoding="utf-8"
+ project_root, _ = _seed_pm_environment(
+ tmp_path, monkeypatch, with_venv_fact=False
)
- monkeypatch.setenv("HERMES_RUNTIME_DIR", str(store))
+ monkeypatch.setattr(gateway_cli, "PROJECT_ROOT", project_root)
assert gateway_cli._detect_venv_dir() is None
@@ -1250,20 +1258,12 @@ class TestServicePathDirsPmVenv:
monkeypatch.delenv("VIRTUAL_ENV", raising=False)
monkeypatch.delenv("HERMES_RUNTIME_DIR", raising=False)
- payload = tmp_path / "payload"
- store = payload / "tools"
- venv_bin = payload / "venv" / "bin"
- venv_bin.mkdir(parents=True)
- (payload / "manifest.json").write_text("{}", encoding="utf-8")
- (store / "facts.json").write_text(
- json.dumps(
- {"schema": 1, "packages": {"venv": {"stamp": "abc", "extras": []}}}
- ),
- encoding="utf-8",
- )
- monkeypatch.setenv("HERMES_RUNTIME_DIR", str(store))
+ project_root, environment = _seed_pm_environment(tmp_path, monkeypatch)
+ venv_bin = environment / "bin"
+ venv_bin.mkdir()
+ monkeypatch.setattr(gateway_cli, "PROJECT_ROOT", project_root)
- dirs = gateway_cli._build_service_path_dirs(project_root=tmp_path / "project")
+ dirs = gateway_cli._build_service_path_dirs(project_root=project_root)
assert str(venv_bin) in dirs
@@ -1271,9 +1271,11 @@ class TestServicePathDirsPmVenv:
def _seed_pm_node_facts(hermes_root):
"""Write a pm installed-state file recording node/npm store entries.
- _append_node_dir_for_service() resolves the managed Node through the pm
- store (facts.json) rather than a fixed ``node/`` tree, so tests seed the
- state the way a real install records it.
+ _append_node_dir_for_service() resolves managed Node through pm's
+ installed-state (facts.json env PATH entries with ``{{store}}`` templates
+ resolved against the target home's store), so tests seed the record the
+ way a real `pm install` writes it — via the same Facts schema, read back
+ through Facts.env_for().
"""
store_root = hermes_root / "tools"
node_dir = store_root / "node-v22.0.0"
diff --git a/tests/hermes_cli/test_gui_command.py b/tests/hermes_cli/test_gui_command.py
index a9b5ce81bb8..fea68e45aee 100644
--- a/tests/hermes_cli/test_gui_command.py
+++ b/tests/hermes_cli/test_gui_command.py
@@ -1140,7 +1140,8 @@ def test_gui_bridges_ozone_hint_to_launch_env(tmp_path, monkeypatch):
patch("hermes_cli.main_desktop._desktop_linux_sandbox_fixup", return_value=True), \
patch("hermes_cli.config.load_config", return_value=cfg), \
patch("hermes_cli.linux_desktop_entry.install_desktop_entry", return_value=None), \
- patch("hermes_cli.main.subprocess.run", side_effect=[ok, ok]) as mock_run, \
+ patch("hermes_cli.main_desktop._detect_linux_password_store", return_value=None), \
+ patch("hermes_cli.main.subprocess.run", side_effect=_pack_into_staging(root)) as mock_run, \
pytest.raises(SystemExit):
cli_main.cmd_gui(_ns())
@@ -1156,7 +1157,8 @@ def test_gui_bridges_ozone_hint_to_launch_env(tmp_path, monkeypatch):
patch("hermes_cli.main_desktop._desktop_linux_sandbox_fixup", return_value=True), \
patch("hermes_cli.config.load_config", return_value=cfg), \
patch("hermes_cli.linux_desktop_entry.install_desktop_entry", return_value=None), \
- patch("hermes_cli.main.subprocess.run", side_effect=[ok, ok]) as mock_run2, \
+ patch("hermes_cli.main_desktop._detect_linux_password_store", return_value=None), \
+ patch("hermes_cli.main.subprocess.run", side_effect=_pack_into_staging(root)) as mock_run2, \
pytest.raises(SystemExit):
cli_main.cmd_gui(_ns())
diff --git a/tests/hermes_cli/test_linux_desktop_entry.py b/tests/hermes_cli/test_linux_desktop_entry.py
index e759b459ba0..9445b70d571 100644
--- a/tests/hermes_cli/test_linux_desktop_entry.py
+++ b/tests/hermes_cli/test_linux_desktop_entry.py
@@ -180,12 +180,7 @@ def test_exec_falls_back_to_interpreter_module(tmp_path, xdg_home, monkeypatch):
exec_line = _parse(entry.read_text(encoding="utf-8"))["Exec"]
assert exec_line.endswith("-m hermes_cli.main desktop")
- # No-boot-through-venv: a DE launch inherits no environment, so the
- # Exec line carries the repo PYTHONPATH explicitly via `env`.
- tokens = exec_line.split(" ")
- assert tokens[0] == "env"
- assert tokens[1].startswith("PYTHONPATH=")
- assert Path(tokens[2].strip('"')).is_absolute()
+ assert Path(exec_line.split(" ")[0]).is_absolute()
# #90292: the shell installer's bash wrapper makes argv[0] the repo `hermes`
@@ -210,11 +205,10 @@ def test_exec_prefixes_interpreter_for_env_shebang_python_script(
entry = lde.install_desktop_entry(root)
exec_line = _parse(entry.read_text(encoding="utf-8"))["Exec"]
- interpreter = str(Path(sys.executable).resolve())
- tokens = exec_line.split(" ")
- assert tokens[0] == "env"
- assert tokens[1].startswith("PYTHONPATH=")
- assert tokens[2].strip('"') == interpreter
+ # The Exec carries the venv-LEXICAL interpreter (resolving would follow
+ # uv/pyenv symlinks out of the venv and lose pyvenv.cfg discovery).
+ interpreter = os.path.abspath(sys.executable)
+ assert exec_line.split(" ")[0].strip('"') == interpreter
assert str(hermes_bin) in exec_line
assert exec_line.endswith("desktop")
@@ -243,7 +237,10 @@ def test_exec_leaves_venv_shebang_scripts_alone(tmp_path, xdg_home, monkeypatch)
root = _make_project(tmp_path)
hermes_bin = tmp_path / "bin" / "hermes"
hermes_bin.parent.mkdir()
- interpreter = str(Path(sys.executable).resolve())
+ # venv-LEXICAL interpreter, matching what the launcher persists: a
+ # resolved() path would dereference out of the venv and look foreign to
+ # the lexical comparison, provoking a spurious interpreter prefix.
+ interpreter = os.path.abspath(sys.executable)
hermes_bin.write_text(f"#!{interpreter}\nimport hermes_cli\n", encoding="utf-8")
hermes_bin.chmod(0o755)
monkeypatch.setattr("hermes_cli.relaunch.resolve_hermes_bin", lambda: str(hermes_bin))