The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(pm): report unwritable install state once
JoaoMarcos440b105e071462
diff --git a/hermes_bootstrap.py b/hermes_bootstrap.pyindex b740702af58..cda4bcfa3ec 100644--- a/hermes_bootstrap.py+++ b/hermes_bootstrap.py@@ -518,7 +518,7 @@ if _legacy_post_swap is not None:raise SystemExit(_continue_legacy_post_swap(_handoff_path, argv_tail=_argv_tail))-from pm.environments import activate_dependencies+from pm.environments import activate_dependencies, install_state_permission_messagefrom hermes_cli._early_recovery import recover_if_neededfrom hermes_cli._parser import command_argv@@ -542,6 +542,9 @@ if not _pm_repair:raise SystemExit(subprocess.call(_command))os.execv(str(_launch_python), _command)except Exception as exc:+ if isinstance(exc, PermissionError) and (message := install_state_permission_message(_root, exc)):+ print(f"hermes: {message}", file=sys.stderr)+ raise SystemExit(1) from None# Degrade, never brick the CLI: the previous dependency generation is still selected# (a failed sync commits nothing), so an offline or half-finished update leaves a# usable Hermes plus a warning. Activation below is the real gate — a tree whose@@ -549,10 +552,13 @@ if not _pm_repair:print(f"hermes: source-update completion failed: {exc}; ""running with the previous dependencies — run `hermes update` to finish it",file=sys.stderr)- recover_if_needed(_root)try:+ recover_if_needed(_root)activate_dependencies(_root)except (RuntimeError, OSError) as exc:+ if isinstance(exc, PermissionError) and (message := install_state_permission_message(_root, exc)):+ print(f"hermes: {message}", file=sys.stderr)+ raise SystemExit(1) from Noneif command_argv(sys.argv[1:])[:1] != ["pm"]:print(f"hermes: {exc}; run `hermes pm repair`", file=sys.stderr)raise SystemExit(1) from Nonediff --git a/hermes_cli/_early_recovery.py b/hermes_cli/_early_recovery.pyindex ee641db7409..e8804e10e81 100644--- a/hermes_cli/_early_recovery.py+++ b/hermes_cli/_early_recovery.py@@ -611,6 +611,10 @@ def recover_if_needed(project_root: Path | None = None, argv: list[str] | None =print("hermes: dependency environment repaired", file=sys.stderr)return Trueexcept Exception as exc:+ from pm.environments import install_state_permission_message++ if isinstance(exc, PermissionError) and install_state_permission_message(root, exc):+ raise # The bootstrap or PM CLI reports the access error once.for marker in markers:_count_failed_attempt(marker)print(f"hermes: dependency repair failed: {exc}; run `hermes pm repair`", file=sys.stderr)diff --git a/pm/cli.py b/pm/cli.pyindex 37634cc85c0..d4f122f828d 100644--- a/pm/cli.py+++ b/pm/cli.py@@ -858,6 +858,13 @@ def main(argv=None) -> int:except InstallError as exc:print(f"✗ {exc}", file=sys.stderr)return 1+ except PermissionError as exc:+ from pm.environments import install_state_permission_message++ if message := install_state_permission_message(repo_root(), exc):+ print(f"✗ {message}", file=sys.stderr)+ return 1+ raiseif __name__ == "__main__":diff --git a/pm/environments.py b/pm/environments.pyindex 53877c4ee88..85ff4801601 100644--- a/pm/environments.py+++ b/pm/environments.py@@ -35,6 +35,17 @@ def install_state_dir(project_root: Path) -> Path:return installs_root() / install_key(project_root)+def install_state_permission_message(project_root: Path, exc: PermissionError) -> str | None:+ """Describe an access failure inside this install's dependency state."""+ if not exc.filename:+ return None+ denied = Path(exc.filename).resolve()+ if not denied.is_relative_to(install_state_dir(project_root).resolve()):+ return None+ return (f"install state is not writable by this user ({denied}); "+ "run as the install owner or grant write access")++def runtime_facts_path(project_root: Path) -> Path:return install_state_dir(project_root) / "facts.json"diff --git a/tests/pm/test_install_state_permissions.py b/tests/pm/test_install_state_permissions.pynew file mode 100644index 00000000000..2faffb737a5--- /dev/null+++ b/tests/pm/test_install_state_permissions.py@@ -0,0 +1,100 @@+"""Permission failures in install state must explain the actual access problem."""++from __future__ import annotations++import os+from pathlib import Path+import subprocess+import sys+from types import ModuleType++import pytest++from pm.environments import install_state_dir, install_state_permission_message++[email protected]("phase", ["preparation", "activation"])+def test_bootstrap_reports_unwritable_install_once(tmp_path, monkeypatch, phase):+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))+ root = Path(__file__).resolve().parents[2]+ target = install_state_dir(root) / (+ "pm-runtime/.prepare.lock" if phase == "preparation" else ".install.lock"+ )+ code = """+import errno+import sys+import pm.environments as environments+target, phase = sys.argv[1:3]+from hermes_cli import _early_recovery, venv_sync++def denied(*args, **kwargs):+ raise PermissionError(errno.EACCES, "Permission denied", target)++venv_sync.prepare_launch = denied if phase == "preparation" else lambda *_: None+_early_recovery.recover_if_needed = lambda *_: False+environments.activate_dependencies = denied if phase == "activation" else lambda *_: None+sys.argv = ["hermes", "-z", "hi"]+import hermes_bootstrap+"""+ result = subprocess.run(+ [sys.executable, "-S", "-c", code, str(target), phase],+ env={**os.environ, "PYTHONPATH": str(root)},+ capture_output=True, text=True, timeout=30,+ )+ assert result.returncode == 1, result.stderr+ assert result.stderr.count("hermes: ") == 1+ assert "install state is not writable by this user" in result.stderr+ assert str(target) in result.stderr+ assert "source-update completion failed" not in result.stderr+ assert "run `hermes update`" not in result.stderr+ assert "hermes pm repair" not in result.stderr+ assert "Traceback" not in result.stderr+++def test_pm_repair_reports_unwritable_runtime_without_traceback(tmp_path, monkeypatch, capsys):+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))+ root = Path(__file__).resolve().parents[2]+ target = install_state_dir(root) / "pm-runtime" / ".prepare.lock"+ code = """+import errno+import sys+from pm import runtime++runtime.is_runtime = lambda: False+def denied(*args):+ raise PermissionError(errno.EACCES, "Permission denied", sys.argv[1])+runtime.run_cli = denied+from pm.cli import main+raise SystemExit(main(["repair"]))+"""+ result = subprocess.run(+ [sys.executable, "-c", code, str(target)],+ env={**os.environ, "PYTHONPATH": str(root)},+ capture_output=True, text=True, timeout=30,+ )+ assert result.returncode == 1, result.stderr+ assert "install state is not writable by this user" in result.stderr+ assert str(target) in result.stderr+ assert "Traceback" not in result.stderr+ lease = install_state_dir(root) / "environments" / "generation" / ".leases" / "reader"+ assert install_state_permission_message(root, PermissionError(13, "Permission denied", str(lease)))+ outside = tmp_path / "other" / ".prepare.lock"+ exc = PermissionError(13, "Permission denied", str(outside))+ assert install_state_permission_message(root, exc) is None++ from hermes_cli import _early_recovery++ project = tmp_path / "source"+ project.mkdir()+ (project / "pyproject.toml").write_text("[project]\n", encoding="utf-8")+ denied_path = install_state_dir(project) / ".install.lock"+ recovery = ModuleType("pm.recovery")++ def fail_repair(*_):+ raise PermissionError(13, "Permission denied", str(denied_path))++ recovery.repair_dependencies = fail_repair+ monkeypatch.setitem(sys.modules, "pm.recovery", recovery)+ with pytest.raises(PermissionError):+ _early_recovery.recover_if_needed(project, argv=["pm", "repair"], explicit=True)+ assert "run `hermes pm repair`" not in capsys.readouterr().err