Skip to content

The agent that grows with you

fix(windows): remove the hermes launchers on uninstall

emozilla5d5179d7a9c0
diff --git a/hermes_cli/uninstall.py b/hermes_cli/uninstall.py
index efc546d8eb5..fbced3bab7f 100644
--- a/hermes_cli/uninstall.py
+++ b/hermes_cli/uninstall.py
@@ -336,12 +336,20 @@ def uninstall_gateway_service():
# or open a new terminal anyway).
-def _hermes_path_markers(hermes_home: Path) -> list[str]:
- """Path-entry substrings that identify Hermes-owned User-PATH entries."""
+def _hermes_path_markers(hermes_home: Path, *, include_managed_bin: bool = False) -> list[str]:
+ """Path-entry substrings that identify Hermes-owned User-PATH entries.
+
+ ``include_managed_bin`` adds the managed binary dir (``<root>\\bin``,
+ holding the hermes launchers and the managed uv) — only wanted when
+ that dir is about to be deleted (full uninstall from the default root),
+ so a keep-data uninstall leaves the still-working managed uv resolvable.
+ """
root = str(hermes_home).rstrip("\\/")
# Match on prefix so sub-entries (git\cmd, git\bin, git\usr\bin, node, etc.)
# all get swept. Also match the bare hermes-agent install dir.
markers = [root + "\\hermes-agent", root + "\\git", root + "\\node", root + "\\venv"]
+ if include_managed_bin:
+ markers.append(root + "\\bin")
# Also match if HERMES_HOME was customised to somewhere else — find-and-nuke
# any entry whose path component contains "hermes". We don't want to catch
# unrelated entries like "chermes-foo" or "ephermeral", so we look for
@@ -349,11 +357,17 @@ def _hermes_path_markers(hermes_home: Path) -> list[str]:
return markers
-def remove_path_from_windows_registry(hermes_home: Path) -> list[str]:
+def remove_path_from_windows_registry(hermes_home: Path, *, include_managed_bin: bool = False) -> list[str]:
"""Strip Hermes-owned entries from User-scope PATH in the registry.
Returns the list of removed path entries. Operates on HKCU\\Environment,
same key the installer wrote to via ``[Environment]::SetEnvironmentVariable``.
+
+ ``include_managed_bin`` adds ``<hermes_home>\\bin`` (the managed binary
+ dir holding the hermes launchers and the managed uv) to the sweep. Only
+ pass it when that dir is actually being deleted — full uninstall from
+ the default root — so a keep-data uninstall leaves the still-working
+ managed uv resolvable.
"""
try:
import winreg
@@ -371,7 +385,7 @@ def remove_path_from_windows_registry(hermes_home: Path) -> list[str]:
return []
# Preserve REG_EXPAND_SZ vs REG_SZ so unexpanded %VARS% survive.
entries = [e for e in path_value.split(";") if e]
- markers = _hermes_path_markers(hermes_home)
+ markers = _hermes_path_markers(hermes_home, include_managed_bin=include_managed_bin)
kept: list[str] = []
for entry in entries:
entry_norm = entry.rstrip("\\/")
@@ -430,6 +444,58 @@ def remove_portable_tooling_windows(hermes_home: Path) -> list[Path]:
return removed
+def remove_windows_bin_launchers(*, windows: bool | None = None) -> list[Path]:
+ """Delete the ``hermes`` launchers install.ps1 staged in the managed
+ binary dir (the default Hermes root's ``bin``, next to the managed uv).
+
+ Every uninstall mode deletes the code checkout, so the launchers —
+ which invoke ``<checkout>\\venv\\Scripts`` — would otherwise dangle:
+ ``hermes`` in a new terminal resolves to a launcher whose target is
+ gone and errors, which reads worse than command-not-found. The managed
+ uv (uv*.exe) in the same dir is left for keep-data reinstalls.
+
+ A launcher that IS this process's own trampoline is mandatory-locked
+ against deletion but not rename (same fact
+ ``_install_repair._quarantine_running_hermes_exe`` relies on), so
+ deletion falls back to renaming it aside with a non-executable suffix.
+
+ *windows* is an injectable platform verdict for tests (same pattern as
+ ``_install_repair.ensure_windows_bin_launchers``).
+ """
+ if windows is None:
+ windows = _is_windows()
+ if not windows:
+ return []
+ try:
+ # Lockstep launcher-name list — the same names install.ps1 and the
+ # startup heal stage into this dir.
+ from hermes_cli._install_repair import _WINDOWS_BIN_LAUNCHERS
+ from hermes_constants import get_default_hermes_root
+
+ bin_dir = get_default_hermes_root() / "bin"
+ except Exception as e:
+ log_warn(f"Could not locate the managed binary dir: {e}")
+ return []
+
+ removed: list[Path] = []
+ for name in _WINDOWS_BIN_LAUNCHERS:
+ for suffix in (".exe", ".cmd"):
+ launcher = bin_dir / f"{name}{suffix}"
+ if not launcher.exists():
+ continue
+ try:
+ launcher.unlink()
+ removed.append(launcher)
+ except OSError:
+ aside = launcher.with_name(f"{launcher.name}.uninstalled.{os.getpid()}")
+ try:
+ os.rename(launcher, aside)
+ removed.append(launcher)
+ except OSError as e:
+ log_warn(f"Could not remove {launcher}: {e}")
+ return removed
+
+
def _is_windows() -> bool:
import sys
return sys.platform == "win32"
@@ -794,7 +860,14 @@ def _perform_uninstall(
# Expand %LOCALAPPDATA% etc. in hermes_home so the marker matching is
# against fully resolved paths — installer writes literal strings
# like C:\Users\<u>\AppData\Local\hermes\git\cmd, not %LOCALAPPDATA%.
- removed_path_entries = remove_path_from_windows_registry(Path(os.path.expandvars(str(hermes_home))))
+ # The managed binary dir (hermes\bin: launchers + managed uv) leaves
+ # the PATH only when the full wipe below is about to delete it;
+ # keep-data mode keeps the dir and the still-working uv resolvable.
+ sweep_managed_bin = full_uninstall and _is_default_hermes_home(hermes_home)
+ removed_path_entries = remove_path_from_windows_registry(
+ Path(os.path.expandvars(str(hermes_home))),
+ include_managed_bin=sweep_managed_bin,
+ )
if removed_path_entries:
for entry in removed_path_entries:
log_success(f"Removed from User PATH: {entry}")
@@ -818,6 +891,19 @@ def _perform_uninstall(
else:
log_info("No wrapper script found")
+ # 3a. Remove the Windows launchers from the managed binary dir. Both
+ # modes delete the code checkout below, so a surviving launcher
+ # would dangle — `hermes` in a new terminal would resolve and then
+ # error on its missing venv target, worse than command-not-found.
+ if _is_windows():
+ log_info("Removing Windows hermes launchers...")
+ removed_launchers = remove_windows_bin_launchers()
+ if removed_launchers:
+ for launcher in removed_launchers:
+ log_success(f"Removed {launcher}")
+ else:
+ log_info("No Windows hermes launchers found")
+
# 3b. Remove node/npm/npx symlinks the installer left in ~/.local/bin
# (only when they still point into this Hermes home's node dir, so we
# never clobber an existing nvm / user-managed Node).
diff --git a/tests/hermes_cli/test_uninstall_windows_bin_launchers.py b/tests/hermes_cli/test_uninstall_windows_bin_launchers.py
new file mode 100644
index 00000000000..fc2eba3aafa
--- /dev/null
+++ b/tests/hermes_cli/test_uninstall_windows_bin_launchers.py
@@ -0,0 +1,110 @@
+"""Uninstall must not leave a dangling ``hermes`` command on Windows.
+
+Every uninstall mode deletes the code checkout, but the launchers install.ps1
+staged in the managed binary dir (the default Hermes root's ``bin``, shared
+with the managed uv) live outside it. A surviving launcher makes ``hermes``
+in a new terminal resolve and then error on its missing venv target — worse
+than command-not-found. The managed uv next to them must survive keep-data
+uninstalls, so the PATH sweep takes the ``bin`` entry only on a full wipe.
+
+Platform verdicts are injected parameters (input→output, not host fakes).
+"""
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from hermes_cli import uninstall
+from hermes_cli._install_repair import _WINDOWS_BIN_LAUNCHERS
+
+
+def managed_bin(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ """Default-root ``bin`` holding launchers of both forms plus managed uv."""
+ home = tmp_path / "hermes"
+ bin_dir = home / "bin"
+ bin_dir.mkdir(parents=True)
+ (bin_dir / "hermes.exe").write_bytes(b"MZ launcher")
+ (bin_dir / "hermes-acp.cmd").write_text("@echo off\r\n", encoding="ascii")
+ (bin_dir / "uv.exe").write_bytes(b"MZ managed uv")
+ (bin_dir / "uvx.exe").write_bytes(b"MZ managed uvx")
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ return bin_dir
+
+
+def test_removes_both_launcher_forms_and_keeps_managed_uv(managed_bin: Path):
+ removed = uninstall.remove_windows_bin_launchers(windows=True)
+
+ assert sorted(p.name for p in removed) == ["hermes-acp.cmd", "hermes.exe"]
+ assert not (managed_bin / "hermes.exe").exists()
+ assert not (managed_bin / "hermes-acp.cmd").exists()
+ # The managed uv stays — keep-data reinstalls still need it.
+ assert (managed_bin / "uv.exe").exists()
+ assert (managed_bin / "uvx.exe").exists()
+
+
+def test_anchors_on_default_root_not_profile_home(
+ managed_bin: Path, monkeypatch: pytest.MonkeyPatch
+):
+ """The launcher dir is per-machine; a profile HERMES_HOME must not
+ redirect the sweep into ``profiles/<name>/bin``."""
+ home = managed_bin.parent
+ monkeypatch.setenv("HERMES_HOME", str(home / "profiles" / "work"))
+
+ removed = uninstall.remove_windows_bin_launchers(windows=True)
+
+ assert sorted(p.name for p in removed) == ["hermes-acp.cmd", "hermes.exe"]
+ assert not (managed_bin / "hermes.exe").exists()
+
+
+def test_noop_on_posix(managed_bin: Path):
+ assert uninstall.remove_windows_bin_launchers(windows=False) == []
+ assert (managed_bin / "hermes.exe").exists()
+
+
+def test_noop_when_no_launchers_staged(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
+ home = tmp_path / "hermes"
+ home.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(home))
+
+ assert uninstall.remove_windows_bin_launchers(windows=True) == []
+
+
+def test_launcher_names_stay_in_lockstep_with_install_ps1():
+ """The sweep must cover exactly the names install.ps1 stages, and no
+ generic name it could clobber. Reads the real installer list so the two
+ sides cannot drift apart silently."""
+ import re
+
+ install_ps1 = (
+ Path(uninstall.__file__).resolve().parents[1] / "scripts" / "install.ps1"
+ ).read_text(encoding="ascii")
+ match = re.search(r"foreach \(\$launcher in @\(([^)]*)\)\)", install_ps1)
+ assert match, "launcher staging loop not found in install.ps1"
+ staged = set(re.findall(r'"([^"]+)"', match.group(1)))
+
+ assert staged == set(_WINDOWS_BIN_LAUNCHERS)
+ for name in _WINDOWS_BIN_LAUNCHERS:
+ assert name.startswith("hermes") # never a generic name it could clobber
+
+
+class TestManagedBinPathMarker:
+ """The managed ``bin`` PATH entry goes only when the dir itself goes."""
+
+ def test_keep_data_markers_spare_the_managed_bin(self, tmp_path: Path):
+ home = tmp_path / "hermes"
+ markers = [m.lower() for m in uninstall._hermes_path_markers(home)]
+
+ bin_key = str(home / "bin").lower()
+ assert not any(bin_key.startswith(m) for m in markers)
+
+ def test_full_wipe_markers_take_the_managed_bin(self, tmp_path: Path):
+ home = tmp_path / "hermes"
+ markers = [
+ m.lower()
+ for m in uninstall._hermes_path_markers(home, include_managed_bin=True)
+ ]
+
+ bin_key = str(home / "bin").lower()
+ assert any(bin_key.startswith(m) for m in markers)