The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Let PM own Git environments and Matrix dependency preparation
ethernet02f9a241d30a
diff --git a/hermes_cli/_subprocess_compat.py b/hermes_cli/_subprocess_compat.pyindex 150e6e814f4..736df8b36b8 100644--- a/hermes_cli/_subprocess_compat.py+++ b/hermes_cli/_subprocess_compat.py@@ -27,6 +27,7 @@ __all__ = ["windows_detach_popen_kwargs","bounded_git_probe","bounded_probe_run",+ "selected_git_env","noninteractive_git_env","NO_DRIVER_DIFF_FLAGS","pid_is_hermes",@@ -345,6 +346,22 @@ def _user_safe_directories(base_env: "Mapping[str, str]") -> list[str]:return values+def selected_git_env(base: Mapping[str, str] | None = None) -> dict[str, str]:+ """PM's full Git environment, or the original base for system-Git fallback.++ Keep lazy acquisition under PM's policy (not just installed-package lookup).+ Unsupported targets and failed acquisition must not disable a working system+ Git. Callers apply their own config/security isolation after selection.+ """+ env = dict(base if base is not None else os.environ)+ try:+ from pm import ensure++ return ensure("git", base_env=env).env+ except Exception:+ return env++def noninteractive_git_env(base: "Mapping[str, str] | None" = None) -> dict[str, str]:"""Environment for *internal* git invocations that must never prompt.diff --git a/plugins/platforms/matrix/adapter.py b/plugins/platforms/matrix/adapter.pyindex 1b0a253ab79..197bb6f397b 100644--- a/plugins/platforms/matrix/adapter.py+++ b/plugins/platforms/matrix/adapter.py@@ -718,42 +718,28 @@ def ensure_matrix_deps() -> bool:forever and broke E2EE connect with ``No module named 'asyncpg'``(#31116). Rebinds module-level type globals on success."""- # Check every anchor of the matrix extra (mautrix alone is not enough:- # a partial install left asyncpg missing forever, #31116).- try:- from pm.extras import missing as _extra_missing, ensure_and_bind- missing = _extra_missing("matrix")- except Exception as exc: # pragma: no cover — defensive- logger.debug("Matrix: extras lookup failed: %s", exc)- missing = ()- ensure_and_bind = None # type: ignore[assignment]- if ensure_and_bind is None:+ from pm.extras import ensure_and_bind++ def _import():+ from mautrix.types import (+ ContentURI, EventID, EventType, PresenceState, RoomCreatePreset, RoomID, TrustState, UserID)+ return {+ "ContentURI": ContentURI,+ "EventID": EventID,+ "EventType": EventType,+ "PresenceState": PresenceState,+ "RoomCreatePreset": RoomCreatePreset,+ "RoomID": RoomID,+ "TrustState": TrustState,+ "UserID": UserID,+ }++ if not ensure_and_bind("matrix", _import, globals()):+ logger.warning(+ "Matrix: required packages not installed or need a restart. "+ "Run `hermes pm install`, then restart Hermes."+ )return False- if missing:- def _import():- from mautrix.types import (- ContentURI, EventID, EventType, PresenceState, RoomCreatePreset, RoomID, TrustState, UserID)- return {- "ContentURI": ContentURI,- "EventID": EventID,- "EventType": EventType,- "PresenceState": PresenceState,- "RoomCreatePreset": RoomCreatePreset,- "RoomID": RoomID,- "TrustState": TrustState,- "UserID": UserID,- }-- if ensure_and_bind is None:- return False- if not ensure_and_bind("matrix", _import, globals()):- logger.warning(- "Matrix: required packages not installed (%s). "- "Run: pip install 'mautrix[encryption]' asyncpg aiosqlite "- "Markdown aiohttp-socks",- ", ".join(missing) if missing else "matrix",- )- return Falsee2ee_mode = _resolve_e2ee_mode()if e2ee_mode == "required" and not _check_e2ee_deps():logger.error(@@ -3018,31 +3004,15 @@ def interactive_setup() -> None:if want_e2ee:save_env_value("MATRIX_ENCRYPTION", "true")print_success("E2EE enabled")- matrix_pkg = "mautrix[encryption]" if want_e2ee else "mautrix"try:- from pm import ensure_import as _lazy_ensure- from pm.extras import missing as _extra_missing- _missing_before = _extra_missing("matrix")- if _missing_before:- print_info(f"Installing {matrix_pkg} (+ {len(_missing_before)} runtime deps)...")- try:- _lazy_ensure("matrix")- print_success(f"{matrix_pkg} installed")- except Exception as exc:- print_warning(- "Install failed — run manually: pip install "- "'mautrix[encryption]' asyncpg aiosqlite Markdown aiohttp-socks"- )- print_info(f" Error: {exc}")- except ImportError:- try:- _lazy_ensure("matrix")- print_success(f"{matrix_pkg} installed")- except Exception as exc:- print_warning(- "Install failed — run manually: pip install "- "'mautrix[encryption]' asyncpg aiosqlite Markdown aiohttp-socks")- print_info(f" Error: {exc}")+ from pm import sync_venv++ print_info("Preparing Matrix dependencies...")+ sync_venv(["matrix"], explicit=True)+ print_success("Matrix dependencies prepared. Restart Hermes to use them.")+ except Exception as exc:+ print_warning(f"Matrix dependencies could not be prepared: {exc}")+ print_info("Run `hermes pm install`, then restart Hermes.")print_info("🔒 Security: Restrict who can use your bot")print_info(" Matrix user IDs look like @username:server")allowed_users = prompt("Allowed user IDs (comma-separated, leave empty for open access)")diff --git a/tests/gateway/test_matrix_deps_rebind.py b/tests/gateway/test_matrix_deps_rebind.pyindex 8791255438b..5825ba0e7be 100644--- a/tests/gateway/test_matrix_deps_rebind.py+++ b/tests/gateway/test_matrix_deps_rebind.py@@ -58,11 +58,10 @@ def _fake_mautrix_types():return mod-def fresh_dependency_boundary(monkeypatch):- """Simulate a fresh install: ``missing()`` reports a gap, the install is a- no-op success, and ``from mautrix.types import ...`` resolves against a fake."""- monkeypatch.setattr(pm_extras, "missing", lambda extra: ("asyncpg",))[email protected](params=[(), ("asyncpg",)], ids=["installed", "fresh"])+def fresh_dependency_boundary(monkeypatch, request):+ """Installed and fresh dependencies both bind through PM's single operation."""+ monkeypatch.setattr(pm_extras, "missing", lambda extra: request.param)monkeypatch.setattr(pm_extras, "ensure_import", lambda *a, **kw: None)monkeypatch.delenv("MATRIX_E2EE_MODE", raising=False)monkeypatch.delenv("MATRIX_ENCRYPTION", raising=False)@@ -94,3 +93,20 @@ def test_failed_install_returns_false_with_hint_and_never_raises(with caplog.at_level("WARNING", logger="plugins.platforms.matrix.adapter"):assert matrix_adapter.ensure_matrix_deps() is Falseassert any("required packages not installed" in r.message for r in caplog.records)+++def test_interactive_setup_explicitly_syncs_matrix(tmp_path, monkeypatch):+ import pm+ from hermes_cli import cli_output, config++ answers = iter(["https://matrix.example.test", "test-token", "@bot:example.test", "@owner:example.test", "!home:example.test"])+ monkeypatch.setattr(cli_output, "prompt", lambda *args, **kwargs: next(answers))+ monkeypatch.setattr(cli_output, "prompt_yes_no", lambda *args, **kwargs: False)+ monkeypatch.setattr(config, "get_env_value", lambda key: None)+ monkeypatch.setattr(config, "save_env_value", lambda *args: None)+ calls = []+ monkeypatch.setattr(pm, "sync_venv", lambda extras, **kwargs: calls.append((extras, kwargs)))+ monkeypatch.setattr(pm, "ensure_import", lambda *args: pytest.fail("setup used implicit installation"))+ monkeypatch.setattr(pm_extras, "missing", lambda extra: ("asyncpg",))+ matrix_adapter.interactive_setup()+ assert calls == [(["matrix"], {"explicit": True})]diff --git a/tests/tools/test_checkpoint_manager.py b/tests/tools/test_checkpoint_manager.pyindex 915e01bae20..1f3a944129e 100644--- a/tests/tools/test_checkpoint_manager.py+++ b/tests/tools/test_checkpoint_manager.py@@ -688,8 +688,8 @@ class TestErrorResilience:assert mgr.ensure_checkpoint(str(work_dir), "test") is False# ...and when git isn't installed at all.- monkeypatch.setattr("shutil.which", lambda x: None)- mgr._git_available = None+ monkeypatch.setattr("shutil.which", lambda *args, **kwargs: None)+ mgr.new_turn()assert mgr.ensure_checkpoint(str(work_dir), "test") is Falsediff --git a/tests/tools/test_checkpoint_store_ownership.py b/tests/tools/test_checkpoint_store_ownership.pyindex 458983cb965..371407fe50a 100644--- a/tests/tools/test_checkpoint_store_ownership.py+++ b/tests/tools/test_checkpoint_store_ownership.py@@ -25,7 +25,7 @@ import sysfrom pathlib import Pathfrom tools import checkpoint_manager as cc.CHECKPOINT_BASE = Path(sys.argv[1])-c._managed_git = lambda: None+run = c._run_gitdef paused(args, *rest, **kwargs):result = run(args, *rest, **kwargs)diff --git a/tests/tools/test_git_consumer_environment.py b/tests/tools/test_git_consumer_environment.pynew file mode 100644index 00000000000..d48984792ec--- /dev/null+++ b/tests/tools/test_git_consumer_environment.py@@ -0,0 +1,91 @@+"""Git consumers use the selected package environment without owning its layout."""+import importlib+import shutil+import subprocess++import pytest++import pm+from tools import checkpoint_manager, working_diff++[email protected]("posix")+def test_checkpoint_and_diff_follow_selected_git_environment(tmp_path, monkeypatch):+ git = shutil.which("git")+ assert git is not None+ selected = tmp_path / "selected-tools"+ selected.mkdir()+ observed = tmp_path / "git-environment"+ wrapper = selected / "git"+ import shlex++ wrapper.write_text(+ '#!/bin/sh\n'+ 'test "$HERMES_GIT_HELPER" = "selected" || exit 77\n'+ f'printf "%s\\n" selected >> {shlex.quote(str(observed))}\n'+ f'exec {shlex.quote(git)} "$@"\n',+ encoding="utf-8",+ )+ wrapper.chmod(0o755)++ repo = tmp_path / "repo"+ repo.mkdir()+ subprocess.run([git, "init", str(repo)], check=True, capture_output=True)+ (repo / "new.txt").write_text("new content\n", encoding="utf-8")++ def selected_git(name, *, base_env):+ assert name == "git"+ return pm.Runner(name, {+ **base_env, "PATH": str(selected), "HERMES_GIT_HELPER": "selected"+ })++ monkeypatch.setattr(pm, "ensure", selected_git)+ monkeypatch.setenv("PATH", str(tmp_path / "missing-path"))+ monkeypatch.setattr(checkpoint_manager, "CHECKPOINT_BASE", tmp_path / "checkpoints")+ manager = checkpoint_manager.CheckpointManager(enabled=True)+ assert manager.ensure_checkpoint(str(repo)) is True+ result = working_diff.collect_working_diff(str(repo))+ assert result["success"] is True+ assert "+new content" in result["diff"]+ assert observed.read_text(encoding="utf-8").splitlines()++ # A changed PM selection must affect this same process, not a cached command.+ monkeypatch.setattr(pm, "ensure", lambda name, *, base_env: pm.Runner(name, {+ **base_env, "PATH": str(tmp_path / "missing-path")+ }))+ assert working_diff.collect_working_diff(str(repo))["success"] is False+ manager.new_turn()+ assert manager.ensure_checkpoint(str(repo)) is False++[email protected]("consumer", ["checkpoint", "diff"])[email protected]("failure", ["unsupported-target", "acquisition"])+def test_git_consumers_fall_back_to_system_git(tmp_path, monkeypatch, consumer, failure):+ git = shutil.which("git")+ assert git is not None+ repo = tmp_path / "repo"+ subprocess.run([git, "init", str(repo)], check=True, capture_output=True)+ (repo / "new.txt").write_text("system git content\n", encoding="utf-8")++ # Fail at the PM boundary reached by both ensure and env_for, without+ # pretending this interpreter is running on a different host OS/CPU.+ resolver = importlib.import_module("pm.ensure")+ calls = []++ def unavailable(*args, **kwargs):+ calls.append(True)+ if failure == "unsupported-target":+ raise RuntimeError("unsupported architecture")+ raise pm.InstallError("git", "managed Git unavailable")++ boundary = "current_target" if failure == "unsupported-target" else "_installed_location"+ monkeypatch.setattr(resolver, boundary, unavailable)+ monkeypatch.setattr(checkpoint_manager, "CHECKPOINT_BASE", tmp_path / "checkpoints")+ if consumer == "checkpoint":+ manager = checkpoint_manager.CheckpointManager(enabled=True)+ assert manager.ensure_checkpoint(str(repo)) is True+ else:+ result = working_diff.collect_working_diff(str(repo))+ assert result["success"] is True+ assert "+system git content" in result["diff"]+ assert callsdiff --git a/tools/checkpoint_manager.py b/tools/checkpoint_manager.pyindex 7196a3b4577..09d0ed36329 100644--- a/tools/checkpoint_manager.py+++ b/tools/checkpoint_manager.py@@ -48,7 +48,6 @@ reclaim object storage. A size-cap pass drops the oldest checkpoints perproject until total store size is under ``max_total_size_mb``."""-import functoolsimport hashlibimport jsonimport logging@@ -59,7 +58,7 @@ import subprocessimport timefrom pathlib import Pathfrom hermes_constants import get_hermes_home-from hermes_cli._subprocess_compat import windows_hide_flags+from hermes_cli._subprocess_compat import selected_git_env, windows_hide_flagsfrom typing import Dict, List, Optional, Set, Tuplefrom utils import env_int@@ -289,33 +288,6 @@ def _project_meta_path(store: Path, dir_hash: str) -> Path:# Git env# ---------------------------------------------------------------------------[email protected]_cache(maxsize=1)-def _managed_git() -> Optional[Tuple[List[str], List[str]]]:- """(git invocation, extra PATH dirs) from pm's pinned Git for Windows.-- pm's git package is the canonical Windows git (Git for Windows,- pinned in pm/lock.json); its PATH dirs make the MSYS helpers- (sh.exe, git-remote-*) resolvable to the child. Returns None when pm- cannot provide git — the deliberate POSIX gap (system git by choice),- not installed, or lazy installs disabled — and the caller falls back- to bare ``git`` on PATH. Cached: checkpoints fire several git calls- per turn, so the store lookup should not repeat.- """- try:- import pm-- runner = pm.ensure("git")- for candidate in ("git.exe", "git"):- resolved = shutil.which(candidate, path=runner.env.get("PATH"))- if resolved:- git_dir = str(Path(resolved).resolve().parent)- usr_bin = str(Path(resolved).resolve().parent.parent / "usr" / "bin")- return [resolved], [git_dir, usr_bin]- except Exception:- pass- return None--def _git_env(store: Path,working_dir: str,@@ -341,7 +313,8 @@ def _git_env(# git child with hand-isolated config env; exact preservation — a HOME# rewrite would change which ~/.gitconfig the isolation vars are hiding.from tools.environments.local import build_subprocess_env- env = build_subprocess_env(scrub_secrets=False, inherit_profile_home=False)++ env = selected_git_env(build_subprocess_env(scrub_secrets=False, inherit_profile_home=False))env["GIT_DIR"] = str(store)env["GIT_WORK_TREE"] = str(normalized_working_dir)env.pop("GIT_NAMESPACE", None)@@ -384,15 +357,10 @@ def _run_git(env = _git_env(store, str(normalized_working_dir), index_file=index_file)if extra_env:env.update(extra_env)- managed = _managed_git()- if managed:- cmd, path_dirs = managed- # The store's MSYS dirs must be reachable so git.exe can resolve- # its helpers; prepend them to the isolated child env.- env["PATH"] = os.pathsep.join(path_dirs) + os.pathsep + env.get("PATH", "")- else:- cmd = ["git"]- cmd = cmd + list(args)+ git = shutil.which("git", path=env.get("PATH", ""))+ if git is None:+ return False, "", "git is not installed or not on PATH"+ cmd = [git, *args]allowed_returncodes = allowed_returncodes or set()try:@@ -517,7 +485,8 @@ def _init_store(store: Path, working_dir: str) -> Optional[str]:# here (which always sets GIT_DIR + GIT_WORK_TREE). Use a raw# subprocess with just the config-isolation env vars.from tools.environments.local import build_subprocess_env- init_env = build_subprocess_env(scrub_secrets=False, inherit_profile_home=False)++ init_env = selected_git_env(build_subprocess_env(scrub_secrets=False, inherit_profile_home=False))init_env["GIT_CONFIG_GLOBAL"] = os.devnullinit_env["GIT_CONFIG_SYSTEM"] = os.devnullinit_env["GIT_CONFIG_NOSYSTEM"] = "1"@@ -526,14 +495,11 @@ def _init_store(store: Path, working_dir: str) -> Optional[str]:"GIT_ALTERNATE_OBJECT_DIRECTORIES"):init_env.pop(k, None)try:- managed = _managed_git()- git_cmd, path_dirs = managed if managed else (["git"], None)- if path_dirs:- init_env["PATH"] = (- os.pathsep.join(path_dirs) + os.pathsep + init_env.get("PATH", "")- )+ git = shutil.which("git", path=init_env.get("PATH", ""))+ if git is None:+ return "Shadow store init failed: git is not installed or not on PATH"result = subprocess.run(- git_cmd + ["init", "--bare", str(store)],+ [git, "init", "--bare", str(store)],capture_output=True, text=True, encoding='utf-8', errors='replace',env=init_env, timeout=_GIT_TIMEOUT,stdin=subprocess.DEVNULL,@@ -781,7 +747,6 @@ class CheckpointManager:self.max_total_size_mb = max(0, int(max_total_size_mb))self.max_file_size_mb = max(0, int(max_file_size_mb))self._checkpointed_dirs: Set[str] = set()- self._git_available: Optional[bool] = None # lazy probe# ------------------------------------------------------------------# Turn lifecycle@@ -897,13 +862,6 @@ class CheckpointManager:if not self.enabled:return False- if self._git_available is None:- self._git_available = shutil.which("git") is not None- if not self._git_available:- logger.debug("Checkpoints disabled: git not found")- if not self._git_available:- return False-abs_dir = str(_normalize_path(working_dir))# Skip root, home, and other overly broad directoriesdiff --git a/tools/working_diff.py b/tools/working_diff.pyindex 55a70d9b2c1..cb8a2e8b610 100644--- a/tools/working_diff.py+++ b/tools/working_diff.py@@ -9,14 +9,13 @@ brand-new files show as additions instead of being invisible.from __future__ import annotations-import functoolsimport osimport shutilimport subprocessfrom contextlib import suppress-from typing import Dict, List, Optional+from typing import Dict, List-from hermes_cli._subprocess_compat import harden_git_argv, noninteractive_git_env+from hermes_cli._subprocess_compat import harden_git_argv, noninteractive_git_env, selected_git_env_GIT_TIMEOUT = 15_MAX_UNTRACKED_FILES = 50 # sanity cap so a node_modules explosion can't hang us@@ -29,30 +28,6 @@ _MODE_ARGS = {VALID_MODES = tuple(_MODE_ARGS)[email protected]_cache(maxsize=1)-def _git_command() -> Optional[List[str]]:- """Resolve the git invocation: pm's pinned Git first, then system git.-- pm's git package is the canonical Windows git (Git for Windows,- pinned in pm/lock.json) — it wins over PATH so a stale or broken- system git never breaks diff collection. On POSIX pm deliberately- gaps git (system git by choice), and when pm can't provide it for any- other reason we fall back to bare ``git`` on PATH. None when git is- nowhere — the caller reports it unavailable.- """- try:- import pm-- runner = pm.ensure("git")- for candidate in ("git.exe", "git"):- resolved = shutil.which(candidate, path=runner.env.get("PATH"))- if resolved:- return [resolved]- except Exception:- pass- return ["git"] if shutil.which("git") else None--def _run(args: List[str], cwd: str, timeout: int = _GIT_TIMEOUT):"""Run git, returning (returncode, stdout). Never raises on git failure.@@ -62,14 +37,15 @@ def _run(args: List[str], cwd: str, timeout: int = _GIT_TIMEOUT):the diff-rendering subcommands so attribute-scoped diff/textconv driverscan't execute either."""- command = _git_command()+ env = noninteractive_git_env(selected_git_env())+ command = shutil.which("git", path=env.get("PATH", ""))if command is None:return 127, ""proc = subprocess.run(- [*command, "-c", "core.quotePath=false", *harden_git_argv(args)],+ [command, "-c", "core.quotePath=false", *harden_git_argv(args)],cwd=cwd, capture_output=True, text=True, timeout=timeout,encoding="utf-8", errors="replace",- stdin=subprocess.DEVNULL, env=noninteractive_git_env(),+ stdin=subprocess.DEVNULL, env=env,)return proc.returncode, proc.stdout@@ -109,12 +85,12 @@ def collect_working_diff(cwd: str, mode: str = "working",return {"success": False,"error": f"Unknown mode '{mode}'. Use: {', '.join(VALID_MODES)}"}- if _git_command() is None:- return {"success": False, "error": "git is not installed or not on PATH."}try:code, _ = _run(["rev-parse", "--is-inside-work-tree"], cwd, timeout=5)except (subprocess.TimeoutExpired, OSError) as e:return {"success": False, "error": f"git failed: {e}"}+ if code == 127:+ return {"success": False, "error": "git is not installed or not on PATH."}if code != 0:return {"success": False, "error": "Not a git repository."}