The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test: restore update self-lock, quarantine and repair guards dropped by #120071
teknium1e692d61d1908
diff --git a/tests/hermes_cli/test_lazy_refresh_venv_repair.py b/tests/hermes_cli/test_lazy_refresh_venv_repair.pyindex 49480f95842..16b52b07136 100644--- a/tests/hermes_cli/test_lazy_refresh_venv_repair.py+++ b/tests/hermes_cli/test_lazy_refresh_venv_repair.py@@ -158,13 +158,59 @@ def test_restore_active_tool_dependencies_uses_static_allowlist(monkeypatch):assert calls == [(["uv", "pip", "install", "langfuse", "--quiet"], env)]+def test_venv_repair_restores_snapshots_with_an_isolated_uv_env(tmp_path, monkeypatch):+ """The unhealthy-venv repair reinstalls the pre-rebuild lazy/tool snapshots through an env+ built by ``managed_python_env`` (#83914): a third-party ``UV_PYTHON_INSTALL_DIR`` /+ ``UV_PYTHON`` / ``VIRTUAL_ENV`` from unrelated software must not steer uv, and+ ``VIRTUAL_ENV`` points at this install's own venv."""+ from hermes_cli import update_cmd+ from hermes_constants import venv_python_path++ project = tmp_path / "hermes"+ venv_python = venv_python_path(project / "venv", windows=m._is_windows())+ venv_python.parent.mkdir(parents=True)+ venv_python.write_text("", encoding="utf-8")+ foreign = tmp_path / "workbuddy"+ monkeypatch.setenv("UV_PYTHON_INSTALL_DIR", str(foreign / "python"))+ monkeypatch.setenv("UV_PYTHON", str(foreign / "python" / "python.exe"))+ monkeypatch.setenv("VIRTUAL_ENV", str(foreign / "venv"))+ calls = []+ monkeypatch.setattr(m, "PROJECT_ROOT", project)+ monkeypatch.setattr(m, "_abort_dependency_sync_if_self_locked", lambda *_a: None)+ monkeypatch.setattr(+ m, "_install_python_dependencies_with_optional_fallback",+ lambda prefix, *, env, group: calls.append(("core", prefix, env, group)))+ monkeypatch.setattr(+ m, "_refresh_active_lazy_features",+ lambda prefix, *, env, features: calls.append(("lazy", prefix, env, features)) or True)+ monkeypatch.setattr(+ m, "_restore_active_tool_dependencies",+ lambda deps, prefix, *, env: calls.append(("tools", prefix, env, deps)))+ monkeypatch.setattr(m, "_refresh_active_memory_provider_dependencies", lambda: None)+ monkeypatch.setattr(m, "_reapply_plugin_python_dependencies", lambda: None)+ monkeypatch.setattr(m, "_clear_update_incomplete_marker", lambda: None)+ monkeypatch.setattr(update_cmd, "_write_update_incomplete_marker", lambda: None)+ monkeypatch.setattr(update_cmd, "_venv_core_imports_healthy", lambda: (True, "ok"))+ monkeypatch.setattr(+ update_cmd, "_repair_node_deps_on_current_checkout", lambda *_a, **_k: True)+ monkeypatch.setattr("hermes_cli.managed_uv.ensure_uv", lambda **_k: "uv")++ assert update_cmd._repair_venv_on_current_checkout(+ assume_yes=True, gateway_mode=False, pre_update_snapshot_id=None,+ had_desktop_app_before_update=False,+ active_lazy_features=["platform.telegram"],+ active_tool_dependencies=["langfuse"],+ _windows_gateway_resume=None,+ ) is True--------+ assert [(c[0], c[1], c[3]) for c in calls] == [+ ("core", ["uv", "pip"], "all"),+ ("lazy", ["uv", "pip"], ["platform.telegram"]),+ ("tools", ["uv", "pip"], ["langfuse"]),+ ]+ for _phase, _prefix, env, _extra in calls:+ assert env["VIRTUAL_ENV"] == str(project / "venv")+ assert str(foreign) not in env.get("UV_PYTHON_INSTALL_DIR", "")+ assert env.get("UV_PYTHON") is None+ assert env.get("UV_MANAGED_PYTHON") == "1"diff --git a/tests/hermes_cli/test_macos_fda_guidance.py b/tests/hermes_cli/test_macos_fda_guidance.pynew file mode 100644index 00000000000..fc470721cdf--- /dev/null+++ b/tests/hermes_cli/test_macos_fda_guidance.py@@ -0,0 +1,90 @@+"""macOS Full Disk Access onboarding guidance (issue #52010 follow-up).++One FDA grant silences every per-folder TCC prompt permanently. Doctor reports+the state and prints the one-switch setup; ``hermes setup`` surfaces the same+tip at onboarding. The probe reads the FDA-gated TCC db directory, which+returns EPERM (no dialog) without the grant; any other error is indeterminate+and must stay silent. The probe is gated on the real host, so the macOS+branches run on the macOS lane and the off-macOS silence runs on Linux.+"""++import contextlib+import io+import os+import pathlib++import pytest++from hermes_cli import doctor_platform+from hermes_cli.setup_quick import _print_macos_fda_tip+++def _capture(fn):+ buf = io.StringIO()+ with contextlib.redirect_stdout(buf):+ fn()+ return buf.getvalue()+++def home(tmp_path, monkeypatch):+ monkeypatch.setattr(pathlib.Path, "home", classmethod(lambda cls: tmp_path))+ return tmp_path+++def tcc_dir(home):+ tcc = home / "Library" / "Application Support" / "com.apple.TCC"+ tcc.mkdir(parents=True)+ return tcc+++def fda_denied(tcc_dir, monkeypatch):+ """The TCC dir exists but listing it fails with EPERM, exactly as without the grant."""+ real_listdir = os.listdir++ def _listdir(path="."):+ if pathlib.Path(path) == tcc_dir:+ raise PermissionError(13, "Operation not permitted", str(path))+ return real_listdir(path)++ monkeypatch.setattr(os, "listdir", _listdir)+ return tcc_dir++[email protected]_only+def test_doctor_and_setup_are_silent_off_macos(tcc_dir):+ assert _capture(doctor_platform.check_macos_full_disk_access) == ""+ assert _capture(_print_macos_fda_tip) == ""++[email protected]_only+def test_doctor_reports_granted_without_guidance(tcc_dir):+ out = _capture(doctor_platform.check_macos_full_disk_access)+ assert "Full Disk Access granted" in out+ assert "Privacy_AllFiles" not in out++[email protected]_only+def test_doctor_prints_one_switch_guidance_when_denied(fda_denied):+ out = _capture(doctor_platform.check_macos_full_disk_access)+ assert "Privacy_AllFiles" in out+ assert "granted" not in out++[email protected]_only+def test_doctor_is_silent_when_probe_is_indeterminate(home):+ """Missing TCC dir (FileNotFoundError, not EPERM) must not nag."""+ assert _capture(doctor_platform.check_macos_full_disk_access) == ""++[email protected]_only+def test_setup_tip_is_silent_when_already_granted(tcc_dir):+ assert _capture(_print_macos_fda_tip) == ""++[email protected]_only+def test_setup_tip_printed_when_denied(fda_denied):+ out = _capture(_print_macos_fda_tip)+ assert "Privacy_AllFiles" in outdiff --git a/tests/hermes_cli/test_update_apply_shallow_count.py b/tests/hermes_cli/test_update_apply_shallow_count.pynew file mode 100644index 00000000000..3b7d08cc562--- /dev/null+++ b/tests/hermes_cli/test_update_apply_shallow_count.py@@ -0,0 +1,103 @@+"""Shallow-checkout guard on the ``hermes update`` apply path (#53479, mirroring #86257).++``rev-list --count HEAD..origin/<branch>`` on a shallow install can enumerate+the entire remote ancestry ("Found 9980 new commit(s)" on a depth-1 clone).+The apply path detects shallow state, recovers the real count via the GitHub+compare API, and reports the count as unknown (-1) when that fails.++These run ``_prepare_checkout_for_update`` against real git checkouts (a+depth-1 clone and a full clone of a local origin); only the GitHub compare+API — the network boundary — is faked.+"""++from __future__ import annotations++import subprocess++import pytest++import hermes_cli.banner as banner+import hermes_cli.main as cli_main+from hermes_cli import update_cmd+++def _git(cwd, *args):+ subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True, text=True)+++def _commit(repo, n):+ (repo / "f.txt").write_text(f"{n}\n", encoding="utf-8")+ _git(repo, "add", "f.txt")+ _git(repo, "commit", "-q", "-m", f"c{n}")+++def origin(tmp_path, monkeypatch):+ for key, value in {+ "GIT_AUTHOR_NAME": "t", "GIT_AUTHOR_EMAIL": "[email protected]",+ "GIT_COMMITTER_NAME": "t", "GIT_COMMITTER_EMAIL": "[email protected]",+ "GIT_CONFIG_NOSYSTEM": "1",+ }.items():+ monkeypatch.setenv(key, value)+ repo = tmp_path / "origin"+ repo.mkdir()+ _git(repo, "init", "-q", "-b", "main")+ for n in range(1, 4):+ _commit(repo, n)+ return repo+++def _checkout_behind(tmp_path, origin, monkeypatch, *, shallow):+ """Clone *origin*, then land two new upstream commits and fetch them."""+ clone = tmp_path / ("shallow" if shallow else "full")+ depth = ["--depth", "1"] if shallow else []+ _git(tmp_path, "clone", "-q", *depth, origin.as_uri(), str(clone))+ for n in (4, 5):+ _commit(origin, n)+ _git(clone, "fetch", "-q", *depth, "origin", "main")+ monkeypatch.setattr(cli_main, "PROJECT_ROOT", clone)+ return clone+++def _count(monkeypatch, *, api):+ consulted = []++ def fake_compare(head_sha, target_sha):+ consulted.append((head_sha, target_sha))+ return api++ monkeypatch.setattr(banner, "_github_compare_behind", fake_compare)+ plan = update_cmd._prepare_checkout_for_update(+ ["git"], "main", "main", is_fork=False, assume_yes=True, gateway_mode=False,+ gw_input_fn=input, switch_branch=False, _windows_gateway_resume=None)+ return plan.commit_count, consulted+++def test_full_clone_keeps_exact_count_without_the_api(tmp_path, origin, monkeypatch):+ _checkout_behind(tmp_path, origin, monkeypatch, shallow=False)+ count, consulted = _count(monkeypatch, api=999)+ assert count == 2+ assert consulted == []+++def test_shallow_count_is_recovered_via_compare_api(tmp_path, origin, monkeypatch):+ """FAIL-BEFORE: the shallow rev-list number was reported as the commit count."""+ clone = _checkout_behind(tmp_path, origin, monkeypatch, shallow=True)+ count, consulted = _count(monkeypatch, api=12)+ assert count == 12+ head = subprocess.run(["git", "rev-parse", "HEAD", "origin/main"], cwd=clone,+ check=True, capture_output=True, text=True).stdout.split()+ assert consulted == [tuple(head)]+++def test_shallow_count_offline_is_unknown_not_bogus(tmp_path, origin, monkeypatch):+ _checkout_behind(tmp_path, origin, monkeypatch, shallow=True)+ count, _ = _count(monkeypatch, api=None)+ assert count == -1+++def test_shallow_local_ahead_is_up_to_date(tmp_path, origin, monkeypatch):+ """compare says 0 behind (local is ahead): the apply path takes the up-to-date branch."""+ _checkout_behind(tmp_path, origin, monkeypatch, shallow=True)+ count, _ = _count(monkeypatch, api=0)+ assert count == 0diff --git a/tests/hermes_cli/test_update_concurrent_quarantine.py b/tests/hermes_cli/test_update_concurrent_quarantine.pyindex 987d98b47b2..de54a535f98 100644--- a/tests/hermes_cli/test_update_concurrent_quarantine.py+++ b/tests/hermes_cli/test_update_concurrent_quarantine.py@@ -1,20 +1,30 @@"""`hermes update` concurrent-instance gate and Windows gateway service helpers-(#26670, #37039, #98814): gateway/non-gateway classification, leftover venv-holder nomination, gateway-ancestor tree-kill refusal, and SCM stop/restore.+(#26670, #37039, #98814): concurrent shim detection, shim quarantine,+gateway/non-gateway classification, gateway pause/resume (SCM services,+profile and unmapped gateways, venv launcher ancestors), leftover venv holder+nomination, gateway-ancestor tree-kill refusal, and SCM stop/restore.++Windows-only code paths carry ``@pytest.mark.windows_only`` and run on the+native Windows lane; nothing here fakes the host OS."""from __future__ import annotations+import json+import osimport sysimport types+from pathlib import Pathfrom types import SimpleNamespace+from unittest.mock import patchimport pytest+from hermes_cli import dashboard_procsfrom hermes_cli import main as cli_main--+from hermes_cli import main_install_repairfrom hermes_cli import update_cmd+from hermes_constants import project_venv_dir# Tests in this module either exercise the REAL _detect_concurrent_hermes_instances@@ -24,11 +34,436 @@ from hermes_cli import update_cmdpytestmark = pytest.mark.real_concurrent_gate+def _project_venv_root() -> Path:+ """Mirror the guards' lookup: the checkout's real venv/.venv, else venv/."""+ venv_dir = project_venv_dir(cli_main.PROJECT_ROOT) or cli_main.PROJECT_ROOT / "venv"+ return venv_dir.resolve() # the guards prefix-match on the resolved path+++# ---------------------------------------------------------------------------+# _detect_concurrent_hermes_instances — parent-chain exclusion+#+# The setuptools .exe launcher is a separate native process that spawns+# python.exe, so excluding only os.getpid() flags our own launcher as a+# concurrent instance (#30768 follow-up, #29341, #34795).+# ---------------------------------------------------------------------------+++def _fake_psutil_with_ancestors(ancestors, rows):+ """psutil stand-in: ``Process(seed).parents()`` yields *ancestors*.++ *ancestors* is ``[(pid, exe_or_None), ...]`` closest first; ``None`` models+ an ancestor whose ``.exe()`` raises (AccessDenied / exited). *rows* are+ ``(pid, exe, name)`` tuples served by ``process_iter``.+ """++ class _Ancestor:+ def __init__(self, pid, exe):+ self.pid = pid+ self._exe = exe++ def exe(self):+ if self._exe is None:+ raise OSError("exe unavailable (simulated AccessDenied)")+ return self._exe++ class _Seed:+ def __init__(self, pid=None):+ self.pid = pid++ def parents(self):+ return [_Ancestor(pid, exe) for pid, exe in ancestors]++ return types.SimpleNamespace(+ Process=_Seed,+ process_iter=lambda _attrs: iter(+ SimpleNamespace(info={"pid": pid, "exe": exe, "name": name})+ for pid, exe, name in rows+ ),+ )++[email protected]_only+def test_detect_concurrent_parents_call_robust_to_one_bad_hop(tmp_path, monkeypatch):+ """One unreadable ancestor never strands the launcher shim (#29341, #34795).++ The old per-hop ``parent()`` walk bailed on the FIRST psutil error, so an+ AccessDenied on any hop left the launcher shim in the candidate set and the+ update refused on our own launcher. Each ancestor is evaluated on its own:+ the launcher behind the bad hop is excluded, we are excluded, and a real+ concurrent shim process is still reported.+ """+ shim = tmp_path / "hermes.exe"+ shim.write_bytes(b"")+ me = os.getpid()+ bad_hop_pid, launcher_pid, other_pid = me + 50, me + 100, me + 200+ unrelated = tmp_path / "elsewhere" / "python.exe"++ rows = [+ (me, str(shim), "python.exe"),+ (bad_hop_pid, None, "cmd.exe"),+ (launcher_pid, str(shim), "hermes.exe"),+ (other_pid, str(shim), "hermes.exe"),+ (me + 300, str(unrelated), "python.exe"),+ ]+ fake_psutil = _fake_psutil_with_ancestors(+ [(bad_hop_pid, None), (launcher_pid, str(shim))], rows+ )+ monkeypatch.setitem(sys.modules, "psutil", fake_psutil)++ result = dashboard_procs._detect_concurrent_hermes_instances(tmp_path)++ assert result == [(other_pid, "hermes.exe")]+++# ---------------------------------------------------------------------------+# _quarantine_running_hermes_exe — retry, then report+# ---------------------------------------------------------------------------++[email protected]_only+def test_quarantine_succeeds_first_attempt(tmp_path):+ """A free shim is renamed aside once; nothing is reported as failed."""+ shim = tmp_path / "hermes.exe"+ shim.write_bytes(b"old")+ failed: list[str] = []++ pairs = main_install_repair._quarantine_running_hermes_exe(+ tmp_path, failed_out=failed+ )++ assert len(pairs) == 1+ orig, quarantine = pairs[0]+ assert orig == shim+ assert quarantine.name.startswith("hermes.exe.old.")+ assert quarantine.exists()+ assert not shim.exists()+ assert failed == []++[email protected]_only+def test_quarantine_reports_a_lock_it_cannot_break(tmp_path, capsys, monkeypatch):+ """Every retry failed: name the culprits, queue nothing for reboot, and+ report the shim so the dependency sync refuses instead of half-applying."""+ shim = tmp_path / "hermes.exe"+ shim.write_bytes(b"locked")+ failed: list[str] = []++ def always_fails(self, target):+ raise OSError(32, "The process cannot access the file (simulated lock)")++ monkeypatch.setattr(main_install_repair, "_hermes_exe_shims", lambda d: [shim])+ with patch.object(Path, "rename", always_fails), patch(+ "time.sleep", lambda *_a, **_k: None+ ):+ pairs = main_install_repair._quarantine_running_hermes_exe(+ tmp_path, failed_out=failed+ )++ captured = capsys.readouterr().out.lower()++ assert pairs == []+ assert failed == ["hermes.exe"]+ assert shim.exists()+ # A clear message, not raw [WinError 32], and no reboot promise we can't keep.+ assert "could not quarantine" in captured+ assert "reboot" not in captured++# ---------------------------------------------------------------------------# Windows gateway pause/resume before update mutation# ---------------------------------------------------------------------------[email protected]_only+def test_pause_windows_gateways_for_update_stops_profile_and_unmapped_pids(+ monkeypatch,+ tmp_path,+ capsys,+):+ """Profile gateways get a planned-stop marker + graceful drain; unmapped+ gateways are force-stopped with their argv captured for respawn."""+ import gateway.status as status_mod+ import hermes_cli.gateway as gateway_mod++ profile_home = tmp_path / "profiles" / "work"+ profile_home.mkdir(parents=True)+ profile_proc = SimpleNamespace(profile="work", path=profile_home, pid=101)++ monkeypatch.setattr(gateway_mod, "find_gateway_pids", lambda **_k: [101, 202])+ monkeypatch.setattr(+ gateway_mod, "find_windows_gateway_services", lambda **_k: []+ )+ monkeypatch.setattr(+ gateway_mod,+ "find_profile_gateway_processes",+ lambda **_k: [profile_proc],+ )+ monkeypatch.setattr(gateway_mod, "_get_restart_drain_timeout", lambda: 0.1)+ waited_for = []++ def fake_wait(pids, *, timeout):+ waited_for.extend(pids)+ return set()++ monkeypatch.setattr(cli_main, "_wait_for_windows_update_gateway_exit", fake_wait)+ monkeypatch.setattr(+ gateway_mod,+ "_capture_gateway_argv",+ lambda pid: ["pythonw.exe", "-m", "hermes_cli.main", "gateway", "run"]+ if pid == 202+ else None,+ )++ terminated = []+ monkeypatch.setattr(+ status_mod,+ "terminate_pid",+ lambda pid, force=False, **kwargs: terminated.append((pid, force)),+ )++ token = cli_main._pause_windows_gateways_for_update()++ assert token == {+ "resume_needed": True,+ "profiles": {"work": 101},+ "unmapped_pids": [202],+ "unmapped": [+ {+ "pid": 202,+ "argv": ["pythonw.exe", "-m", "hermes_cli.main", "gateway", "run"],+ }+ ],+ }+ assert waited_for == [101]+ assert terminated == [(202, True)]++ marker = json.loads(+ (profile_home / ".gateway-planned-stop.json").read_text(encoding="utf-8")+ )+ assert marker["target_pid"] == 101+ assert marker["stopper_pid"] == os.getpid()++ captured = capsys.readouterr().out+ assert "Paused gateway profile(s): work" in captured+ assert "without profile mapping" in captured+ # An unmapped PID whose argv we captured is respawnable, so we must NOT+ # tell the user to restart it manually.+ assert "Restart manually after update" not in captured++[email protected]_only+def test_pause_and_resume_windows_gateway_service(+ monkeypatch,+ tmp_path,+):+ """A real Windows service is stopped before venv mutation and restarted+ afterward instead of spawning a competing detached gateway."""+ import hermes_cli.gateway as gateway_mod+ import hermes_cli.update_cmd_windows as update_cmd_windows++ profile_home = tmp_path / "profiles" / "default"+ profile_home.mkdir(parents=True)+ profile_proc = SimpleNamespace(profile="default", path=profile_home, pid=101)+ service = SimpleNamespace(+ name="HermesGateway",+ profile="default",+ service_pid=11,+ service_create_time=11.0,+ gateway_pid=101,+ gateway_create_time=101.0,+ descendant_pids=frozenset({11, 22, 101}),+ descendant_identities=((22, 22.0), (101, 101.0)),+ )+ monkeypatch.setattr(gateway_mod, "find_gateway_pids", lambda **_k: [])+ monkeypatch.setattr(+ gateway_mod, "find_profile_gateway_processes", lambda **_k: [profile_proc]+ )+ monkeypatch.setattr(+ gateway_mod, "find_windows_gateway_services", lambda **_k: [service]+ )+ monkeypatch.setattr(gateway_mod, "_get_restart_drain_timeout", lambda: 0.1)++ stopped = []+ started = []+ for mod in (update_cmd, update_cmd_windows):+ monkeypatch.setattr(+ mod,+ "_stop_windows_gateway_service",+ lambda name, **_kwargs: stopped.append(name),+ raising=False,+ )+ monkeypatch.setattr(+ mod,+ "_start_windows_gateway_service",+ lambda name: started.append(name),+ raising=False,+ )+ monkeypatch.setattr(cli_main, "_refresh_windows_gateway_launchers", lambda: None)+ monkeypatch.setattr(+ cli_main,+ "_cold_start_windows_gateway_after_update",+ lambda *_a: (_ for _ in ()).throw(+ AssertionError("service resume must not cold-start")+ ),+ )++ token = cli_main._pause_windows_gateways_for_update()+ assert token == {+ "resume_needed": True,+ "profiles": {},+ "unmapped_pids": [],+ "unmapped": [],+ "services": ["HermesGateway"],+ "expected_services": ["HermesGateway"],+ "restarted_services": [],+ "service_profiles": {"HermesGateway": "default"},+ }+ assert stopped == ["HermesGateway"]++ cli_main._resume_windows_gateways_after_update(token)+ assert started == ["HermesGateway"]+ assert token["resume_needed"] is False+++def _two_services():+ return [+ SimpleNamespace(name="HermesGateway", profile="default", service_pid=11, service_create_time=11.0, gateway_pid=101, gateway_create_time=101.0, descendant_identities=()),+ SimpleNamespace(name="HermesGatewayPicasso", profile="picasso", service_pid=22, service_create_time=22.0, gateway_pid=202, gateway_create_time=202.0, descendant_identities=()),+ ]+++def _patch_service_discovery(monkeypatch, services):+ import hermes_cli.gateway as gateway_mod++ monkeypatch.setattr(gateway_mod, "find_gateway_pids", lambda **_k: [])+ monkeypatch.setattr(gateway_mod, "find_profile_gateway_processes", lambda **_k: [])+ monkeypatch.setattr(+ gateway_mod, "find_windows_gateway_services", lambda **_k: services+ )+++def _patch_service_stop_restore(monkeypatch, fake_stop, fake_restore):+ import hermes_cli.update_cmd_windows as update_cmd_windows++ for mod in (update_cmd, update_cmd_windows):+ monkeypatch.setattr(mod, "_stop_windows_gateway_service", fake_stop)+ monkeypatch.setattr(+ mod, "_restore_windows_gateway_service", fake_restore, raising=False+ )+++def _stop_times_out_on_picasso(name, **_kwargs):+ if name == "HermesGatewayPicasso":+ raise RuntimeError("simulated stop timeout")++[email protected]_only+def test_pause_windows_gateway_service_failure_restores_every_attempted_service(+ monkeypatch,+):+ """A service that times out after accepting stop is restarted too."""+ _patch_service_discovery(monkeypatch, _two_services())+ restarted = []+ _patch_service_stop_restore(+ monkeypatch, _stop_times_out_on_picasso, restarted.append+ )++ with pytest.raises(RuntimeError, match="HermesGatewayPicasso"):+ cli_main._pause_windows_gateways_for_update()++ assert restarted == ["HermesGatewayPicasso", "HermesGateway"]++[email protected]_only+def test_pause_windows_gateway_service_surfaces_rollback_start_failure(+ monkeypatch,+):+ """A rollback restart that fails is named, never swallowed."""+ _patch_service_discovery(monkeypatch, _two_services())++ def fake_restore(name):+ if name == "HermesGateway":+ raise RuntimeError("simulated rollback start failure")++ _patch_service_stop_restore(monkeypatch, _stop_times_out_on_picasso, fake_restore)++ with pytest.raises(RuntimeError, match="rollback failures: HermesGateway"):+ cli_main._pause_windows_gateways_for_update()++[email protected]_only+def test_pause_windows_gateways_aborts_when_service_discovery_is_indeterminate(+ monkeypatch,+):+ """An indeterminate SCM scan aborts before any gateway is torn down."""+ import hermes_cli.gateway as gateway_mod++ monkeypatch.setattr(gateway_mod, "find_profile_gateway_processes", lambda **_k: [])+ monkeypatch.setattr(+ gateway_mod,+ "find_windows_gateway_services",+ lambda **_k: (_ for _ in ()).throw(RuntimeError("SCM scan indeterminate")),+ )+ monkeypatch.setattr(+ gateway_mod,+ "find_gateway_pids",+ lambda **_k: (_ for _ in ()).throw(+ AssertionError("ordinary gateway teardown must not begin")+ ),+ )++ with pytest.raises(RuntimeError, match="SCM scan indeterminate"):+ cli_main._pause_windows_gateways_for_update()++[email protected]_only+def test_pause_windows_gateways_aborts_when_gateway_pid_discovery_is_indeterminate(+ monkeypatch,+):+ """Failed PID discovery aborts instead of reading as "no gateways running"."""+ import hermes_cli.gateway as gateway_mod++ monkeypatch.setattr(gateway_mod, "find_profile_gateway_processes", lambda **_k: [])+ monkeypatch.setattr(gateway_mod, "find_windows_gateway_services", lambda **_k: [])+ monkeypatch.setattr(+ gateway_mod,+ "find_gateway_pids",+ lambda **_k: (_ for _ in ()).throw(RuntimeError("PID discovery failed")),+ )++ with pytest.raises(RuntimeError, match="PID discovery failed"):+ cli_main._pause_windows_gateways_for_update()++[email protected]_only+def test_resume_windows_gateway_service_failure_stays_retryable(+ monkeypatch,+):+ """A service that fails to restart stays on the token for the retry."""+ import hermes_cli.update_cmd_windows as update_cmd_windows++ token = {+ "resume_needed": True,+ "profiles": {},+ "unmapped": [],+ "services": ["HermesGateway"],+ }+ monkeypatch.setattr(cli_main, "_refresh_windows_gateway_launchers", lambda: None)+ for mod in (update_cmd, update_cmd_windows):+ monkeypatch.setattr(+ mod,+ "_start_windows_gateway_service",+ lambda _name: (_ for _ in ()).throw(RuntimeError("simulated start failure")),+ )++ with pytest.raises(RuntimeError, match="HermesGateway"):+ cli_main._resume_windows_gateways_after_update(token)++ assert token["resume_needed"] is True+ assert token["services"] == ["HermesGateway"]++def test_restore_windows_gateway_service_waits_out_stop_pending(monkeypatch):import hermes_cli.update_cmd as update_cmdimport hermes_cli.update_cmd_windows as update_cmd_windows@@ -80,6 +515,150 @@ def test_stop_windows_gateway_service_waits_for_original_descendants()+# ---------------------------------------------------------------------------+# venv-side launcher ancestors (the uv launcher/worker split)+#+# A gateway started through the venv shim is two processes:+# venv\Scripts\python.exe (launcher) -> uv\python\...\python.exe (worker)+# The gateway's PID file records the WORKER, so find_gateway_pids() (and the+# pause set built from it) only ever sees the worker. The venv-holder guard+# matches on the venv path prefix, so it only ever sees the LAUNCHER. The two+# sets were disjoint: a gateway the updater had just stopped still tripped the+# guard, aborting every update ("venv-blocked: N process(es) hold the install").+# ---------------------------------------------------------------------------+++def _fake_psutil_tree(tree, venv_exe, worker_exe, dead=None):+ """psutil stand-in where ``tree`` maps worker pid -> parent pid.++ Even pids are venv-side (``venv_exe``); odd pids are unrelated ancestors+ (``worker_exe``) that must NOT be returned. Pids in ``dead`` (a live+ reference — later additions count) are uninspectable: construction raises,+ exactly like psutil.NoSuchProcess for an exited process.+ """++ dead_set = dead if dead is not None else set()++ class FakeProc:+ def __init__(self, pid=None):+ self.pid = pid+ if pid in dead_set:+ raise ValueError(f"process {pid} has exited")+ if pid is not None and pid not in tree and pid not in tree.values():+ raise ValueError(f"no such pid {pid}")++ def parent(self):+ ppid = tree.get(self.pid)+ return FakeProc(ppid) if ppid else None++ def parents(self):+ return []++ def exe(self):+ return venv_exe if self.pid % 2 == 0 else worker_exe++ return types.SimpleNamespace(Process=FakeProc)++[email protected]_only+def test_venv_launcher_ancestors_returns_venv_side_parent(monkeypatch):+ """The worker's venv-side parent is reported so the guard set is covered."""+ venv_exe = str(_project_venv_root() / "Scripts" / "python.exe")+ worker_exe = r"C:\Users\x\AppData\Roaming\uv\python\cpython-3.11\python.exe"++ # worker 200 -> launcher 100 (even == venv-side)+ monkeypatch.setitem(+ sys.modules, "psutil", _fake_psutil_tree({200: 100}, venv_exe, worker_exe)+ )++ assert cli_main._venv_launcher_ancestors([200]) == [100]++[email protected]_only+def test_venv_launcher_ancestors_ignores_non_venv_parents(monkeypatch):+ """A Scheduled Task's cmd.exe / an operator shell is not a venv holder."""+ venv_exe = str(_project_venv_root() / "Scripts" / "python.exe")+ worker_exe = r"C:\Windows\System32\cmd.exe"++ # worker 200 -> parent 101 (odd == NOT venv-side)+ monkeypatch.setitem(+ sys.modules, "psutil", _fake_psutil_tree({200: 101}, venv_exe, worker_exe)+ )++ assert cli_main._venv_launcher_ancestors([200]) == []++[email protected]_only+def test_pause_kill_set_covers_venv_guard_abort_set(+ monkeypatch,+ tmp_path,+):+ """INVARIANT: whatever the venv guard would abort on must be stopped.++ Before the launcher walk existed, ``terminated`` held only the uv-side+ worker while the guard reported the venv-side launcher, so the update+ aborted forever despite a "successful" pause. The worker exits during the+ graceful drain and is uninspectable afterwards, so the launcher must be+ resolved BEFORE draining.+ """+ import gateway.status as status_mod+ import hermes_cli.gateway as gateway_mod++ venv_exe = str(_project_venv_root() / "Scripts" / "python.exe")+ worker_exe = r"C:\Users\x\AppData\Roaming\uv\python\cpython-3.11\python.exe"++ profile_home = tmp_path / "profiles" / "default"+ profile_home.mkdir(parents=True)+ # The PID file records the WORKER (even-numbered parent 400 is its launcher).+ worker_pid, launcher_pid = 500, 400+ profile_proc = SimpleNamespace(+ profile="default", path=profile_home, pid=worker_pid+ )++ monkeypatch.setattr(gateway_mod, "find_gateway_pids", lambda **_k: [worker_pid])+ monkeypatch.setattr(+ gateway_mod, "find_windows_gateway_services", lambda **_k: []+ )+ monkeypatch.setattr(+ gateway_mod, "find_profile_gateway_processes", lambda **_k: [profile_proc]+ )+ monkeypatch.setattr(gateway_mod, "_get_restart_drain_timeout", lambda: 0.1)+ drained_dead: set[int] = set()++ def _drain_marks_workers_dead(pids, *, timeout):+ drained_dead.update(int(p) for p in pids)+ return set()++ monkeypatch.setattr(+ cli_main,+ "_wait_for_windows_update_gateway_exit",+ _drain_marks_workers_dead,+ )+ monkeypatch.setitem(+ sys.modules,+ "psutil",+ _fake_psutil_tree(+ {worker_pid: launcher_pid}, venv_exe, worker_exe, dead=drained_dead+ ),+ )++ terminated = []+ monkeypatch.setattr(+ status_mod,+ "terminate_pid",+ lambda pid, force=False, **kwargs: terminated.append(int(pid)),+ )++ cli_main._pause_windows_gateways_for_update()++ # What the downstream venv-holder guard would report as blocking.+ guard_would_abort_on = {launcher_pid}+ assert guard_would_abort_on.issubset(set(terminated)), (+ f"pause stopped {sorted(terminated)} but the venv guard aborts on "+ f"{sorted(guard_would_abort_on)} — disjoint sets abort the update"+ )++# ---------------------------------------------------------------------------# _leftover_pausable_gateway_pids (the guard-level gateway fallback)#@@ -348,6 +927,137 @@ def test_filter_non_gateway_concurrent_instances_gateway_only(monkeypatch):# ---------------------------------------------------------------------------+def _update_args():+ return SimpleNamespace(+ check=False,+ gateway=False,+ yes=False,+ force=False,+ backup=False,+ no_backup=True,+ )++[email protected]_only+def test_update_gate_skips_abort_when_only_concurrent_is_gateway(+ tmp_path, capsys, monkeypatch+):+ """#37039: with only gateway runtimes concurrent, the gate must NOT+ sys.exit(2) — the update proceeds to the pre-update backup step, and the+ pause machinery owns the gateways. The real classifier decides."""+ scripts_dir = tmp_path / "Scripts"+ scripts_dir.mkdir()+ monkeypatch.setitem(+ sys.modules,+ "psutil",+ _fake_psutil_classify(+ {+ 1000: ["hermes.exe", "gateway", "run"],+ 2000: [r"C:\venv\Scripts\hermes-gateway.exe"],+ }+ ),+ )++ with patch.object(+ cli_main, "_venv_scripts_dir", return_value=scripts_dir+ ), patch.object(+ cli_main,+ "_detect_concurrent_hermes_instances",+ return_value=[(1000, "hermes.exe"), (2000, "hermes-gateway.exe")],+ ), patch.object(+ cli_main, "_run_pre_update_backup"+ ) as mock_backup:+ mock_backup.side_effect = RuntimeError("reached post-gate body")+ with pytest.raises(RuntimeError, match="reached post-gate body"):+ update_cmd._cmd_update_impl(_update_args(), gateway_mode=False)++ mock_backup.assert_called_once()+ assert "Another hermes.exe is running" not in capsys.readouterr().out++[email protected]_only+def test_update_gate_still_aborts_on_non_gateway_concurrent(+ tmp_path, capsys, monkeypatch+):+ """A non-gateway concurrent instance still aborts with exit 2 before any+ mutation, and the message lists only the non-gateway PID (the gateway is+ not the user's problem to kill)."""+ scripts_dir = tmp_path / "Scripts"+ scripts_dir.mkdir()+ monkeypatch.setitem(+ sys.modules,+ "psutil",+ _fake_psutil_classify(+ {1000: ["hermes.exe", "gateway", "run"], 3000: ["hermes.exe"]}+ ),+ )++ with patch.object(+ cli_main, "_venv_scripts_dir", return_value=scripts_dir+ ), patch.object(+ cli_main,+ "_detect_concurrent_hermes_instances",+ return_value=[(1000, "hermes.exe"), (3000, "hermes.exe")],+ ), patch.object(+ cli_main, "_run_pre_update_backup"+ ) as mock_backup:+ with pytest.raises(SystemExit) as excinfo:+ update_cmd._cmd_update_impl(_update_args(), gateway_mode=False)++ assert excinfo.value.code == 2+ mock_backup.assert_not_called()+ captured = capsys.readouterr().out+ assert "3000" in captured+ assert "1000" not in captured # gateway PID no longer blamed+ assert "--force" in captured++[email protected]_only+def test_update_impl_refuses_before_terminating_gateway_ancestor(+ monkeypatch, capsys+):+ """#98814: the live venv-holder path gates the destructive call itself —+ a gateway holder that is our own ancestor is never terminated."""+ import gateway.status as status_mod+ import hermes_cli.gateway as gateway_cli++ holder = (+ 300,+ "python.exe",+ r"C:\x\venv\Scripts\python.exe -m hermes_cli.main gateway run",+ )+ monkeypatch.setattr(+ gateway_cli,+ "_is_pid_ancestor_of_current_process",+ lambda pid: pid == 300,+ )++ with patch.object(+ cli_main, "_venv_scripts_dir", return_value=None+ ), patch.object(+ cli_main, "_run_pre_update_backup", return_value=None+ ), patch.object(+ cli_main, "_pause_windows_gateways_for_update", return_value=None+ ), patch.object(+ cli_main, "_detect_venv_python_processes", return_value=[holder]+ ), patch.object(+ cli_main, "_leftover_pausable_gateway_pids", return_value=[300]+ ), patch.object(+ cli_main, "_resume_windows_gateways_after_update"+ ) as resume, patch.object(+ status_mod, "terminate_pid"+ ) as terminate:+ with pytest.raises(SystemExit) as excinfo:+ update_cmd._cmd_update_impl(_update_args(), gateway_mode=False)++ assert excinfo.value.code == 2+ terminate.assert_not_called()+ resume.assert_called_once_with(None)+ output = capsys.readouterr().out+ assert "taskkill /T" in output+ assert "`/update`" in output++def test_stop_service_refuses_pid_reuse_before_sc_stop(monkeypatch):import hermes_cli.update_cmd as update_cmd@@ -367,5 +1077,3 @@ def test_stop_service_refuses_pid_reuse_before_sc_stop(monkeypatch):)assert calls == []--diff --git a/tests/hermes_cli/test_update_shim_self_lock.py b/tests/hermes_cli/test_update_shim_self_lock.pyindex c0ad4ac44fe..021405d057c 100644--- a/tests/hermes_cli/test_update_shim_self_lock.py+++ b/tests/hermes_cli/test_update_shim_self_lock.py@@ -1,14 +1,209 @@-"""Pending-rename filter for the Windows console-shim update self-lock (#88838, #89599, #86093).+"""The Windows console-shim update self-lock (#88838, #89599, #86093, #79542).-``_filter_pending_shim_renames`` is a pure function over registry-``PendingFileRenameOperations`` entries, so it runs on any host.+``venv\\Scripts\\hermes.exe`` is a launcher that runs the interpreter with the+shim itself as its script, keeping the file open without FILE_SHARE_DELETE for+the whole command. An update started that way must therefore replace a file it+is holding, which Windows refuses — so the DEPENDENCY SYNC re-runs itself under+``venv\\Scripts\\python.exe``.++The detection and hand-off tests are ``windows_only``: the shim matcher is+gated on the real host, so they run on the Windows lane. The pending-rename+filter and the venv-layout lookup are host-independent and run everywhere."""from __future__ import annotations+import os+import sys+import typesfrom pathlib import Path+import pytest++from hermes_cli import main as cli_mainfrom hermes_cli import main_install_repair+from hermes_constants import venv_bin_dir++SHIM_NAMES = ["hermes.exe", "hermes-agent.exe", "hermes-acp.exe", "hermes-gateway.exe"]+++def venv(tmp_path, monkeypatch):+ """A project venv Scripts dir with a python.exe, wired into the shim matcher."""+ scripts = tmp_path / "venv" / "Scripts"+ scripts.mkdir(parents=True)+ (scripts / "python.exe").write_bytes(b"")+ # update_cmd reads these off hermes_cli.main (frozen ``_m()`` surface); the+ # install-repair helpers read their own module globals — patch both.+ for target in (cli_main, main_install_repair):+ monkeypatch.setattr(target, "_venv_scripts_dir", lambda: scripts)+ monkeypatch.setattr(sys, "argv", ["hermes", "update"])+ monkeypatch.delenv(cli_main._UPDATE_REEXEC_ENV, raising=False)+ _fake_psutil(monkeypatch, [])+ return scripts+++def _fake_psutil(monkeypatch, ancestor_exes: list[str]):+ """Stand in for psutil with a fixed self+ancestor executable chain."""++ class _Proc:+ def __init__(self, exe=None, pid=os.getpid()):+ self._exe, self.pid = exe, pid++ def exe(self):+ if self._exe is None:+ raise OSError("exe unavailable")+ return self._exe++ def parents(self):+ return [_Proc(exe, 1000 + i) for i, exe in enumerate(ancestor_exes)]++ monkeypatch.setitem(sys.modules, "psutil", types.SimpleNamespace(Process=_Proc))+++def _capture_popen(monkeypatch, raises: Exception | None = None):+ calls = []++ def fake_popen(cmd, env=None, **kwargs):+ if raises is not None:+ raise raises+ calls.append((list(cmd), dict(env or {}), kwargs))+ return object()++ monkeypatch.setattr(cli_main.subprocess, "Popen", fake_popen)+ return calls+++# ---------------------------------------------------------------------------+# Shim detection+# ---------------------------------------------------------------------------++[email protected]_only[email protected]("shim_name", SHIM_NAMES)+def test_detects_shim_as_argv0(venv, monkeypatch, shim_name):+ monkeypatch.setattr(sys, "argv", [str(venv / shim_name), "update"])+ assert main_install_repair._windows_shim_in_process_chain() == venv / shim_name++[email protected]_only+def test_detects_shim_from_zipapp_main_py(venv, monkeypatch):+ """runpy/zipapp launches put ``<shim>\\__main__.py`` in argv[0]."""+ monkeypatch.setattr(sys, "argv", [str(venv / "hermes.exe" / "__main__.py")])+ assert main_install_repair._windows_shim_in_process_chain() == venv / "hermes.exe"++[email protected]_only+def test_detects_shim_in_ancestor_chain(venv, monkeypatch):+ """The launcher is usually a separate parent process, not argv[0]."""+ _fake_psutil(monkeypatch, [str(venv / "hermes.exe")])+ assert main_install_repair._windows_shim_in_process_chain() == venv / "hermes.exe"+ # ...and it is that launcher's pid, not ours, a detached child must outwait (#101600).+ assert main_install_repair._windows_shim_holder_pid() == 1000++[email protected]_only+def test_ignores_hermes_exe_outside_the_project_venv(venv, monkeypatch, tmp_path):+ """A shim from some other install must never trigger a re-exec."""+ other = tmp_path / "other" / "Scripts"+ other.mkdir(parents=True)+ monkeypatch.setattr(sys, "argv", [str(other / "hermes.exe"), "update"])+ _fake_psutil(monkeypatch, [str(other / "hermes.exe")])+ assert main_install_repair._windows_shim_in_process_chain() is None+++# ---------------------------------------------------------------------------+# Re-exec hand-off+# ---------------------------------------------------------------------------++[email protected]_only+def test_reexec_runs_same_args_under_venv_python(venv, monkeypatch):+ monkeypatch.setattr(sys, "argv", [str(venv / "hermes.exe"), "update", "--yes"])+ calls = _capture_popen(monkeypatch)+ token = {"resume_needed": True, "profiles": {"default": 4}, "unmapped": []}++ assert cli_main._reexec_dependency_sync_off_windows_shim(token) is True+ cmd, env, kwargs = calls[0]+ assert cmd == [+ str(venv / "python.exe"), "-m", "hermes_cli.main", "update", "--yes",+ ]+ assert env[cli_main._UPDATE_REEXEC_ENV] == "1"+ # The parent exits, so a prompt in the child could never be answered.+ assert kwargs["stdin"] is cli_main.subprocess.DEVNULL+ # #101600: the child waits for THIS pid and resumes exactly the paused fleet; the parent's+ # copy is disarmed so it exits instead of relaunching gateways while it still holds the shim.+ from hermes_cli import update_handoff+ assert env[update_handoff.SHIM_PARENT_PID_ENV] == str(os.getpid())+ assert token["resume_needed"] is False+ monkeypatch.setenv(update_handoff.GATEWAY_RESUME_ENV, env[update_handoff.GATEWAY_RESUME_ENV])+ assert update_handoff.adopt_handed_off_gateway_resume() == {+ "resume_needed": True, "profiles": {"default": 4}, "unmapped": []}+ assert update_handoff.GATEWAY_RESUME_ENV not in os.environ++[email protected]_only+def test_reexec_does_not_recurse(venv, monkeypatch):+ monkeypatch.setattr(sys, "argv", [str(venv / "hermes.exe"), "update"])+ monkeypatch.setenv(cli_main._UPDATE_REEXEC_ENV, "1")+ calls = _capture_popen(monkeypatch)++ assert cli_main._reexec_dependency_sync_off_windows_shim() is False+ assert calls == []++[email protected]_only+def test_reexec_falls_through_when_spawn_fails(venv, monkeypatch):+ """A failed spawn keeps the sync in-process (it then fails closed on the lock)."""+ monkeypatch.setattr(sys, "argv", [str(venv / "hermes.exe"), "update"])+ _capture_popen(monkeypatch, raises=OSError("no exec"))++ assert cli_main._reexec_dependency_sync_off_windows_shim() is False+++# ---------------------------------------------------------------------------+# Hand-off placement: the dependency-sync boundary+# ---------------------------------------------------------------------------++[email protected]_only+def test_sync_guard_hands_off_when_only_the_shim_is_held(venv, monkeypatch):+ """No native module mapped, but we ARE the shim: hand off and exit 0 WITHOUT resuming the+ paused fleet here — the child owns the token (#101600)."""+ monkeypatch.setattr(sys, "argv", [str(venv / "hermes.exe"), "update"])+ monkeypatch.setattr(cli_main, "_detect_self_loaded_native_modules", lambda: [])+ resumed = []+ monkeypatch.setattr(cli_main, "_resume_windows_gateways_after_update", resumed.append)+ calls = _capture_popen(monkeypatch)++ with pytest.raises(SystemExit) as excinfo:+ cli_main._abort_dependency_sync_if_self_locked({"resume_needed": True, "profiles": {}})++ assert excinfo.value.code == 0+ assert calls, "expected the dependency sync to be handed to the venv python"+ assert resumed == [], "the shim parent must exit at once, not relaunch gateways"++[email protected]_only+def test_sync_guard_defers_native_lock_before_considering_the_shim(venv, monkeypatch):+ """A mapped .pyd still exits 2 — the marker recovery owns that case."""+ monkeypatch.setattr(sys, "argv", [str(venv / "hermes.exe"), "update"])+ monkeypatch.setattr(+ cli_main, "_detect_self_loaded_native_modules", lambda: ["PyYAML (_yaml.pyd)"]+ )+ monkeypatch.setattr(cli_main, "_defer_update_for_self_lock", lambda loaded: None)+ calls = _capture_popen(monkeypatch)++ with pytest.raises(SystemExit) as excinfo:+ cli_main._abort_dependency_sync_if_self_locked()++ assert excinfo.value.code == 2+ assert calls == [], "a native-module deferral must not also spawn a child"+++# ---------------------------------------------------------------------------+# Reboot-deferred renames+# ---------------------------------------------------------------------------def test_pending_rename_filter_drops_only_our_shim_pairs():@@ -46,3 +241,15 @@ def test_pending_rename_filter_preserves_a_trailing_delete_entry():# ---------------------------------------------------------------------------[email protected]("venv_name", ["venv", ".venv"])+def test_venv_scripts_dir_finds_both_layouts(tmp_path, monkeypatch, venv_name):+ """uv writes .venv; our installers write venv. Both must resolve (#79542).++ A ``venv``-only lookup silently returned None on a ``.venv`` install, so the+ whole Windows shim-lock preflight skipped itself. Uses the host's real bin+ dir name (``Scripts``/``bin``), so no OS is faked.+ """+ scripts = venv_bin_dir(tmp_path / venv_name, windows=main_install_repair._is_windows())+ scripts.mkdir(parents=True)+ monkeypatch.setattr(cli_main, "PROJECT_ROOT", tmp_path)+ assert main_install_repair._venv_scripts_dir() == scriptsdiff --git a/tests/hermes_cli/test_verify_console_scripts.py b/tests/hermes_cli/test_verify_console_scripts.pynew file mode 100644index 00000000000..701b0581854--- /dev/null+++ b/tests/hermes_cli/test_verify_console_scripts.py@@ -0,0 +1,99 @@+"""Post-install console-script verification on Windows (issue #52931).++``uv pip install -e .`` can record ``hermes.exe`` in the wheel RECORD while the+file never lands, so ``hermes`` drops off PATH after a "successful" install.+``_verify_console_scripts_installed`` must notice the missing shim and repair it+with ``--reinstall -e .`` under quarantine. The check is gated on the real host,+so these tests run on the Windows lane.+"""++from __future__ import annotations++import textwrap++import pytest++from hermes_cli import main_install_repair++pytestmark = pytest.mark.windows_only++_SCRIPTS = ("hermes", "hermes-agent", "hermes-acp")+++def scripts_dir(tmp_path, monkeypatch):+ """A project with three declared console scripts and an empty venv Scripts dir."""+ (tmp_path / "pyproject.toml").write_text(+ textwrap.dedent(+ """\+ [project]+ name = "fake"+ version = "0.0.0"++ [project.scripts]+ hermes = "hermes_cli.main:main"+ hermes-agent = "run_agent:main"+ hermes-acp = "acp_adapter.entry:main"+ """+ ),+ encoding="utf-8",+ )+ import hermes_cli.main as main_mod++ monkeypatch.setattr(main_mod, "PROJECT_ROOT", tmp_path)+ scripts = tmp_path / "venv" / "Scripts"+ scripts.mkdir(parents=True)+ monkeypatch.setattr(main_install_repair, "_venv_scripts_dir", lambda: scripts)+ return scripts+++def _record_installs(monkeypatch, *, lands: tuple[str, ...] = ()):+ """Replace the quarantined uv install; it writes the *lands* shims like a real repair."""+ calls = []++ def fake_install(cmd, *, env=None, scripts_dir=None, **_kwargs):+ calls.append((list(cmd), scripts_dir))+ assert scripts_dir is not None+ for name in lands:+ (scripts_dir / f"{name}.exe").write_bytes(b"shim")++ monkeypatch.setattr(main_install_repair, "_run_quarantined_install", fake_install)+ return calls+++def test_missing_hermes_exe_is_reinstalled(scripts_dir, monkeypatch, capsys):+ """The #52931 shape: hermes-agent/hermes-acp landed, hermes.exe did not."""+ for name in ("hermes-agent", "hermes-acp"):+ (scripts_dir / f"{name}.exe").write_bytes(b"shim")+ calls = _record_installs(monkeypatch, lands=("hermes",))++ main_install_repair._verify_console_scripts_installed(["uv", "pip"], env={})++ assert calls == [(["uv", "pip", "install", "--reinstall", "-e", "."], scripts_dir)]+ assert (scripts_dir / "hermes.exe").is_file()+ out = capsys.readouterr().out+ assert "hermes" in out and "missing" in out+ assert "Still missing" not in out+++def test_repair_that_still_leaves_a_shim_missing_is_reported(scripts_dir, monkeypatch, capsys):+ """A reinstall that again fails to land the shim must not claim success."""+ for name in ("hermes-agent", "hermes-acp"):+ (scripts_dir / f"{name}.exe").write_bytes(b"shim")+ _record_installs(monkeypatch)++ main_install_repair._verify_console_scripts_installed(["uv", "pip"], env={})++ out = capsys.readouterr().out+ assert "Still missing after repair: hermes" in out+ assert "python -m hermes_cli.main" in out+++def test_no_reinstall_when_every_shim_is_present(scripts_dir, monkeypatch):+ for name in _SCRIPTS:+ (scripts_dir / f"{name}.exe").write_bytes(b"shim")+ calls = _record_installs(monkeypatch)++ main_install_repair._verify_console_scripts_installed(["uv", "pip"], env={})++ assert calls == []