The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): status names and uninstall removes pre-suffix Windows launchers
teknium196ee0516c6ce
diff --git a/hermes_cli/gateway_windows.py b/hermes_cli/gateway_windows.pyindex a472900e235..a7a372d915d 100644--- a/hermes_cli/gateway_windows.py+++ b/hermes_cli/gateway_windows.py@@ -877,6 +877,11 @@ def install(_startup_staging_path().unlink(missing_ok=True)except OSError:pass+ if force:+ # Pre-suffix strays (task ``Hermes_Gateway``, Startup ``Hermes_Gateway.vbs``) are unreachable by+ # the current names, so a plain reconcile never heals them (#116157).+ from hermes_cli.gateway_windows_legacy import remove_legacy_launchers+ remove_legacy_launchers()# On locked-down accounts schtasks can sit for the full timeout before returning Access Denied.# All intent questions were asked above, so ask for UAC before touching schtasks.@@ -1270,6 +1275,9 @@ def uninstall() -> None:except FileNotFoundError:pass+ from hermes_cli.gateway_windows_legacy import remove_legacy_launchers+ remove_legacy_launchers()+if is_task_registered() and not scheduled_task_removed:print(f"⚠ Scheduled Task still registered: {task_name}")@@ -1550,6 +1558,8 @@ def status(deep: bool = False) -> None:print(f"✓ Windows login item installed: {entry if entry.exists() else _legacy_startup_entry_path()}")else:print("✗ Gateway service not installed")+ from hermes_cli.gateway_windows_legacy import warn_legacy_launchers+ warn_legacy_launchers()print(f"✓ Gateway process running (PID: {', '.join(map(str, pids))})" if pids else "✗ No gateway process detected")diff --git a/hermes_cli/gateway_windows_legacy.py b/hermes_cli/gateway_windows_legacy.pynew file mode 100644index 00000000000..fd4ff67cd65--- /dev/null+++ b/hermes_cli/gateway_windows_legacy.py@@ -0,0 +1,77 @@+"""Pre-suffix Windows gateway launchers: the objects the current per-profile names cannot reach.++Before task/launcher names carried ``_profile_suffix()``, an install wrote the Scheduled Task+``Hermes_Gateway``, the Startup entry ``Hermes_Gateway.vbs``/``.cmd`` and the launcher pair+``gateway-service\\Hermes_Gateway.{vbs,cmd}``. Every operation in ``gateway_windows`` is keyed on+``get_task_name()`` → ``Hermes_Gateway_<suffix>``, so those strays are never queried, rewritten,+reported or removed: they keep launching a second gateway at logon, never pick up launcher+fixes, and ``hermes gateway status`` prints ✓ while they do (#116157). This module enumerates+them once; ``status`` warns, ``uninstall`` and ``install --force`` remove.+"""++from __future__ import annotations++from pathlib import Path+++def _w():+ import hermes_cli.gateway_windows as gateway_windows # facade binding is the seam for tests++ return gateway_windows+++def legacy_launcher_artifacts() -> list[tuple[str, str, Path | str]]:+ """``(kind, label, target)`` for every pre-suffix launcher still present; ``kind`` is ``"file"``+ or ``"task"``. Empty when this home owns the bare name (its current objects ARE the bare ones)."""+ w = _w()+ bare = w._TASK_NAME_DEFAULT+ if w.get_task_name() == bare:+ return []+ found: list[tuple[str, str, Path | str]] = []+ startup = w._startup_dir()+ service_dir = w._hermes_home() / "gateway-service"+ for path, label in (+ (startup / f"{bare}.vbs", "legacy pre-suffix Windows login item"),+ (startup / f"{bare}.cmd", "legacy pre-suffix Windows login item"),+ (service_dir / f"{bare}.vbs", "legacy pre-suffix task launcher"),+ (service_dir / f"{bare}.cmd", "legacy pre-suffix task script"),+ ):+ if path.exists():+ found.append(("file", label, path))+ code, _out, _err = w._exec_schtasks(["/Query", "/TN", bare])+ if code == 0:+ found.append(("task", "legacy pre-suffix Scheduled Task", bare))+ return found+++def warn_legacy_launchers() -> bool:+ """``hermes gateway status``: name every stray so nobody has to do file-mtime archaeology."""+ artifacts = legacy_launcher_artifacts()+ for _kind, label, target in artifacts:+ print(f"⚠ {label} still installed: {target}")+ if artifacts:+ print(" These predate per-profile launcher names and also start the gateway at logon.")+ print(" Remove them with: hermes gateway uninstall (then: hermes gateway install)")+ return bool(artifacts)+++def remove_legacy_launchers() -> None:+ """``uninstall`` / ``install --force``: delete the strays; a task that needs elevation is named+ with the exact elevated command instead of being silently left behind."""+ w = _w()+ for kind, label, target in legacy_launcher_artifacts():+ if kind == "file":+ try:+ Path(target).unlink()+ print(f"✓ Removed {label}: {target}")+ except OSError as exc:+ print(f"⚠ Could not remove {label} {target}: {exc}")+ continue+ code, _out, err = w._exec_schtasks(["/Delete", "/F", "/TN", str(target)])+ if code == 0:+ print(f"✓ Removed {label} {str(target)!r}")+ elif w._is_access_denied(err.strip()):+ print(f"⚠ {label} {str(target)!r} needs an elevated shell to remove; run as administrator:")+ print(f" schtasks /Delete /F /TN {target}")+ else:+ print(f"⚠ schtasks /Delete {str(target)!r} returned code {code}: {err.strip()}")diff --git a/tests/hermes_cli/test_gateway_windows.py b/tests/hermes_cli/test_gateway_windows.pyindex c6822124f80..89b3e7f45fa 100644--- a/tests/hermes_cli/test_gateway_windows.py+++ b/tests/hermes_cli/test_gateway_windows.py@@ -440,6 +440,54 @@ def test_uninstall_and_reinstall_sweep_stale_startup_staging_file(monkeypatch, tassert not staging.exists()+def test_status_names_and_uninstall_removes_pre_suffix_launchers(monkeypatch, tmp_path, capsys):+ """#116157: a Scheduled Task ``Hermes_Gateway`` and a Startup ``Hermes_Gateway.vbs`` left from before+ per-profile suffixes are invisible to every ``get_task_name()``-keyed operation. ``status`` must name+ them and ``uninstall`` must remove them (files unlinked, ``schtasks /Delete`` issued for the task)."""+ startup, home = tmp_path / "Startup", tmp_path / "home"+ (home / "gateway-service").mkdir(parents=True)+ startup.mkdir()+ legacy_vbs = startup / "Hermes_Gateway.vbs"+ legacy_vbs.write_text("legacy", encoding="utf-8")+ legacy_pair = home / "gateway-service" / "Hermes_Gateway.cmd"+ legacy_pair.write_text("legacy", encoding="utf-8")+ schtasks_calls = []+ registered = {"Hermes_Gateway"}++ def fake_schtasks(args):+ schtasks_calls.append(args)+ name = args[args.index("/TN") + 1]+ if args[0] == "/Delete":+ registered.discard(name)+ return (0, "SUCCESS", "")+ return (0, "", "") if name in registered else (1, "", "ERROR: The system cannot find the file specified.")++ monkeypatch.setattr(gateway_windows, "_assert_windows", lambda: None)+ monkeypatch.setattr(gateway_windows, "get_task_name", lambda: "Hermes_Gateway_alice")+ monkeypatch.setattr(gateway_windows, "get_task_script_path", lambda: home / "gateway-service" / "Hermes_Gateway_alice.cmd")+ monkeypatch.setattr(gateway_windows, "get_startup_entry_path", lambda: startup / "Hermes_Gateway_alice.vbs")+ monkeypatch.setattr(gateway_windows, "_legacy_startup_entry_path", lambda: startup / "Hermes_Gateway_alice.cmd")+ monkeypatch.setattr(gateway_windows, "_startup_dir", lambda: startup)+ monkeypatch.setattr(gateway_windows, "_hermes_home", lambda: home)+ monkeypatch.setattr(gateway_windows, "_exec_schtasks", fake_schtasks)+ monkeypatch.setattr(gateway_windows, "_gateway_pids", lambda *a, **k: [])+ monkeypatch.setattr(gateway_windows, "_print_start_attestation_warning", lambda: None)++ gateway_windows.status()+ out = capsys.readouterr().out+ assert f"legacy pre-suffix Windows login item still installed: {legacy_vbs}" in out+ assert f"legacy pre-suffix task script still installed: {legacy_pair}" in out+ assert "legacy pre-suffix Scheduled Task still installed: Hermes_Gateway" in out++ gateway_windows.uninstall()+ out = capsys.readouterr().out+ assert "Removed legacy pre-suffix Scheduled Task 'Hermes_Gateway'" in out+ assert not legacy_vbs.exists() and not legacy_pair.exists()+ assert ["/Delete", "/F", "/TN", "Hermes_Gateway"] in schtasks_calls+ gateway_windows.status()+ assert "legacy pre-suffix" not in capsys.readouterr().out++# Reporter's `Export-ScheduledTask` of a task registered before the hardened template (#113670)._PRE_HARDENING_TASK_XML = """<?xml version="1.0" encoding="UTF-16"?><Task version="1.3" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">diff --git a/tests/hermes_cli/test_legacy_launchers_windows_live.py b/tests/hermes_cli/test_legacy_launchers_windows_live.pynew file mode 100644index 00000000000..c1eb238b94f--- /dev/null+++ b/tests/hermes_cli/test_legacy_launchers_windows_live.py@@ -0,0 +1,61 @@+"""Live Windows probe: pre-suffix gateway launchers are reported by ``status`` and removed by+``uninstall`` (#116157).++Runs only on real Windows (the on-demand ``wine2e/**`` windows-latest lane). It registers a REAL+Scheduled Task named ``Hermes_Gateway`` (harmless action) plus a pre-suffix Startup entry under a+temp APPDATA, then drives the production ``status()`` / ``uninstall()`` against ``schtasks.exe``.+"""++import shutil+import subprocess++import pytest++import hermes_cli.gateway_windows as gateway_windows++[email protected]_only+def test_status_warns_and_uninstall_removes_pre_suffix_launchers(tmp_path, monkeypatch, capsys):+ home = tmp_path / "hermes"+ (home / "gateway-service").mkdir(parents=True)+ monkeypatch.setenv("HERMES_HOME", str(home))+ appdata = tmp_path / "AppData" / "Roaming"+ startup = appdata / "Microsoft" / "Windows" / "Start Menu" / "Programs" / "Startup"+ startup.mkdir(parents=True)+ monkeypatch.setenv("APPDATA", str(appdata))+ monkeypatch.setattr(gateway_windows, "_gateway_pids", lambda *a, **k: [])+ monkeypatch.setattr(gateway_windows, "_print_start_attestation_warning", lambda: None)++ current = gateway_windows.get_task_name()+ assert current != "Hermes_Gateway", "a temp home must carry a profile suffix"+ legacy_vbs = startup / "Hermes_Gateway.vbs"+ legacy_vbs.write_text("' pre-suffix login item\r\n", encoding="utf-8")+ legacy_pair = home / "gateway-service" / "Hermes_Gateway.vbs"+ legacy_pair.write_text("' pre-suffix launcher\r\n", encoding="utf-8")++ schtasks = shutil.which("schtasks") or "schtasks"+ create = subprocess.run(+ [schtasks, "/Create", "/F", "/TN", "Hermes_Gateway", "/SC", "ONLOGON", "/TR", "cmd.exe /c exit 0"],+ capture_output=True, text=True, timeout=60,+ )+ assert create.returncode == 0, create.stderr+ try:+ gateway_windows.status()+ out = capsys.readouterr().out+ assert "legacy pre-suffix Scheduled Task still installed: Hermes_Gateway" in out+ assert f"legacy pre-suffix Windows login item still installed: {legacy_vbs}" in out+ assert f"legacy pre-suffix task launcher still installed: {legacy_pair}" in out+ assert "hermes gateway uninstall" in out++ gateway_windows.uninstall()+ out = capsys.readouterr().out+ assert "Removed legacy pre-suffix Scheduled Task 'Hermes_Gateway'" in out+ assert not legacy_vbs.exists()+ assert not legacy_pair.exists()+ query = subprocess.run([schtasks, "/Query", "/TN", "Hermes_Gateway"], capture_output=True, text=True, timeout=60)+ assert query.returncode != 0, "the pre-suffix task must be gone after uninstall"++ gateway_windows.status()+ assert "legacy pre-suffix" not in capsys.readouterr().out+ finally:+ subprocess.run([schtasks, "/Delete", "/F", "/TN", "Hermes_Gateway"], capture_output=True, text=True, timeout=60)