Skip to content

The agent that grows with you

fix(update): classify Windows gateway supervisors by Hermes ownership, not ancestry

teknium11417ae04248c
diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.py
index 6ca3c2e66a5..a88f7140107 100644
--- a/hermes_cli/gateway.py
+++ b/hermes_cli/gateway.py
@@ -788,19 +788,20 @@ def find_profile_gateway_processes(exclude_pids: set | None = None, *, strict: b
return processes
-def _is_hermes_windows_gateway_service(name: str) -> bool:
- """Return whether an SCM service name declares Hermes ownership."""
- normalized = "".join(char for char in name.casefold() if char.isalnum())
- return normalized == "hermes" or normalized.startswith("hermesgateway")
+def _scm_service_field(service, field: str):
+ """psutil ``WindowsService`` exposes getters as methods; ``as_dict()`` covers objects without them."""
+ getter = getattr(service, field, None)
+ return getter() if callable(getter) else service.as_dict().get(field)
def find_windows_gateway_services(
*, psutil_module=None, profile_processes: list[ProfileGatewayProcess] | None = None
) -> list[WindowsGatewayService]:
- """Profile gateways supervised by real Windows services. Service-logon processes may hide their
- command lines, so identity = Hermes's own PID file + a parent chain ending at a running SCM service
- PID. The whole service subtree is returned so the Desktop preflight exempts exactly what the
- updater stops through the SCM."""
+ """Profile gateways supervised by real, Hermes-owned Windows services. Service-logon processes may
+ hide their command lines, so identity = Hermes's own PID file + a parent chain ending at a running
+ SCM service PID whose name or binary path is Hermes's (``gateway_windows.hermes_owns_windows_service``).
+ The whole service subtree is returned so the Desktop preflight exempts exactly what the updater stops
+ through the SCM; a gateway under any other service (a Scheduled Task's svchost) is a plain process."""
if sys.platform != "win32":
return []
try:
@@ -808,26 +809,29 @@ def find_windows_gateway_services(
import psutil as psutil_module # type: ignore[no-redef] # noqa: PLC0415
if profile_processes is None:
profile_processes = find_profile_gateway_processes(strict=True)
+ from hermes_cli.gateway_windows import hermes_owns_windows_service, hermes_service_roots
+
+ hermes_roots = hermes_service_roots()
service_names_by_pid: dict[int, set[str]] = {}
indeterminate_services_by_pid: dict[int, list[tuple[str, object]]] = {}
for service in psutil_module.win_service_iter():
try:
- if all(callable(getattr(service, field, None)) for field in ("name", "status", "pid")):
- service_name = str(service.name() or "")
- service_status = service.status()
- service_pid = int(service.pid() or 0)
- else:
- data = service.as_dict()
- service_name = str(data.get("name") or "")
- service_status = data.get("status")
- service_pid = int(data.get("pid") or 0)
+ service_name = str(_scm_service_field(service, "name") or "")
+ if not service_name:
+ raise RuntimeError("SCM service has an empty name")
+ # Ownership before state: an OS service above the gateway (Task Scheduler's svchost for a
+ # task-launched gateway, BITS mid-transition) is never its supervisor, so neither its
+ # PID nor its status may steer the pause. Only Hermes-owned services reach the guards below.
+ service_binpath = str(_scm_service_field(service, "binpath") or "")
+ if not hermes_owns_windows_service(service_name, service_binpath, hermes_roots):
+ continue
+ service_status = _scm_service_field(service, "status")
+ service_pid = int(_scm_service_field(service, "pid") or 0)
except FileNotFoundError:
# Deleted between enumeration and inspection.
continue
except Exception as exc:
raise RuntimeError("SCM service inspection failed") from exc
- if not service_name:
- raise RuntimeError("SCM service has an empty name")
if service_status == "stopped":
continue
if service_status != "running":
@@ -836,8 +840,6 @@ def find_windows_gateway_services(
continue
if service_pid <= 0:
raise RuntimeError(f"Running SCM service {service_name} has no valid process ID")
- if not _is_hermes_windows_gateway_service(service_name):
- continue
service_names_by_pid.setdefault(service_pid, set()).add(service_name)
except Exception as exc:
raise RuntimeError("SCM service enumeration failed") from exc
diff --git a/hermes_cli/gateway_windows.py b/hermes_cli/gateway_windows.py
index 7a34788147b..1989a19a27c 100644
--- a/hermes_cli/gateway_windows.py
+++ b/hermes_cli/gateway_windows.py
@@ -77,6 +77,29 @@ def _hermes_home() -> Path:
return Path(get_hermes_home())
+def hermes_service_roots() -> tuple[str, ...]:
+ """Directories a Hermes-owned SCM service binary lives under: the checkout (its ``venv`` included),
+ the running interpreter's ``Scripts`` dir (``hermes.exe`` shim) and the ``gateway-service`` launcher dir."""
+ project_root = Path(__file__).resolve().parent.parent
+ return (str(project_root), str(Path(sys.executable).parent), str(_hermes_home() / "gateway-service"))
+
+
+def _normalize_windows_path(value: str) -> str:
+ return value.strip().lstrip('"').replace("\\", "/").rstrip("/").casefold()
+
+
+def hermes_owns_windows_service(name: str, binpath: str, hermes_roots: tuple[str, ...]) -> bool:
+ """Positive ownership of an SCM service: Hermes-named (``hermes*``) or its binary path starts under a
+ Hermes root. Pure so it is testable off-Windows. A Scheduled-Task-launched gateway descends from
+ ``svchost.exe`` hosting ``Schedule``; without this gate the updater took Task Scheduler for the
+ gateway's supervisor and ``sc.exe stop Schedule`` aborted every update (#97208)."""
+ normalized_name = "".join(char for char in name.casefold() if char.isalnum())
+ if normalized_name.startswith("hermes"):
+ return True
+ candidate = _normalize_windows_path(binpath)
+ return any(candidate.startswith(_normalize_windows_path(root) + "/") for root in hermes_roots if root)
+
+
def _preserve_hermes_home_path(path: str | Path) -> str:
r"""Render Hermes-owned paths under the configured HERMES_HOME spelling.
diff --git a/tests/hermes_cli/test_gateway.py b/tests/hermes_cli/test_gateway.py
index 8fd83f50cd4..326c48c5cfb 100644
--- a/tests/hermes_cli/test_gateway.py
+++ b/tests/hermes_cli/test_gateway.py
@@ -1322,39 +1322,46 @@ def test_find_windows_gateway_services_rejects_transitional_ancestor(monkeypatch
)
def test_find_windows_gateway_services_ignores_task_scheduler_ancestor(monkeypatch):
- """A task-launched gateway is not owned by the Schedule SCM service."""
- monkeypatch.setattr(gateway.sys, "platform", "win32")
- profile = SimpleNamespace(profile="default", pid=300, create_time=300.0)
+ """gateway <- cmd.exe <- svchost.exe(Schedule) <- services.exe: the Task Scheduler host is not the
+ gateway's supervisor, so a task-launched gateway is a plain process (#97208); the same tree under a
+ Hermes-owned service (by binary path) stays SCM-supervised."""
+ import hermes_cli.gateway_windows as gateway_windows
+
+ monkeypatch.setattr(gateway_windows, "hermes_service_roots", lambda: (r"C:\hermes\hermes-agent",))
+ profile = SimpleNamespace(profile="default", pid=18480, create_time=18480.0)
class FakeService:
+ def __init__(self, name, binpath):
+ self._name, self._binpath = name, binpath
+
def as_dict(self):
- return {"name": "Schedule", "pid": 100, "status": "running"}
+ return {"name": self._name, "binpath": self._binpath, "pid": 2360, "status": "running"}
class FakeProcess:
def __init__(self, pid):
self.pid = pid
def parents(self):
- return [FakeProcess(200), FakeProcess(100)]
+ return [FakeProcess(12296), FakeProcess(2360), FakeProcess(4)]
def children(self, recursive=False):
- assert self.pid == 100
- assert recursive is True
- return [FakeProcess(200), FakeProcess(300)]
+ assert self.pid == 2360 and recursive is True
+ return [FakeProcess(12296), FakeProcess(18480)]
def create_time(self):
return float(self.pid)
- fake_psutil = SimpleNamespace(
- win_service_iter=lambda: [FakeService()],
- Process=FakeProcess,
- )
+ def run(service):
+ return gateway.find_windows_gateway_services(
+ psutil_module=SimpleNamespace(win_service_iter=lambda: [service], Process=FakeProcess),
+ profile_processes=[profile],
+ )
- assert gateway.find_windows_gateway_services(
- psutil_module=fake_psutil,
- profile_processes=[profile],
- ) == []
+ assert run(FakeService("Schedule", r"C:\Windows\system32\svchost.exe -k netsvcs -p -s Schedule")) == []
+ owned = run(FakeService("gw", r'"C:\hermes\hermes-agent\venv\Scripts\hermes.exe" gateway run'))
+ assert [(s.name, s.service_pid, s.gateway_pid) for s in owned] == [("gw", 2360, 18480)]
def test_find_windows_gateway_services_rejects_shared_service_host_pid(monkeypatch):
diff --git a/tests/hermes_cli/test_gateway_windows.py b/tests/hermes_cli/test_gateway_windows.py
index d4a62e19317..afc0b3430af 100644
--- a/tests/hermes_cli/test_gateway_windows.py
+++ b/tests/hermes_cli/test_gateway_windows.py
@@ -581,3 +581,23 @@ def test_start_on_tty_hands_both_answers_to_install_and_honours_the_env_opt_out(
+
+
+def test_hermes_owns_windows_service_requires_name_or_binary_under_a_hermes_root():
+ """Task Scheduler (``Schedule`` in svchost) above a task-launched gateway is never its supervisor;
+ a service is Hermes-owned only by a ``hermes*`` name or a binary under the install (#97208)."""
+ roots = (
+ r"C:\Users\kaize\AppData\Local\hermes\hermes-agent",
+ r"C:\Users\kaize\AppData\Local\hermes\hermes-agent\venv\Scripts",
+ r"C:\Users\kaize\AppData\Local\hermes\gateway-service",
+ )
+ owns = gateway_windows.hermes_owns_windows_service
+
+ assert not owns("Schedule", r"C:\Windows\system32\svchost.exe -k netsvcs -p -s Schedule", roots)
+ assert not owns("BITS", r"C:\Windows\System32\svchost.exe -k netsvcs -p -s BITS", roots)
+ assert not owns("Other", r"C:\Users\kaize\AppData\Local\hermes\hermes-agent-fork\run.exe", roots)
+
+ assert owns("HermesGateway", r"C:\nssm\nssm.exe", roots)
+ assert owns("Hermes_Gateway_derek", "", roots)
+ assert owns("gw", r'"C:\Users\KAIZE\AppData\Local\hermes\hermes-agent\venv\Scripts\hermes.exe" gateway run', roots)
+ assert owns("gw", r"C:\Users\kaize\AppData\Local\hermes\gateway-service\Hermes_Gateway.cmd", roots)
diff --git a/website/docs/user-guide/windows-native.md b/website/docs/user-guide/windows-native.md
index e895e5822ba..7f16485481d 100644
--- a/website/docs/user-guide/windows-native.md
+++ b/website/docs/user-guide/windows-native.md
@@ -198,7 +198,7 @@ Login auto-start is only ever installed on an explicit answer: `hermes gateway i
### Why not a Windows Service?
-Services require admin rights to install and tie the gateway's lifecycle to machine boot, not user login. The typical Hermes user wants: log in → gateway available, log out → gateway gone. Scheduled Tasks do exactly that without elevation. If you genuinely want a service, use `nssm` or `sc create` manually — but you probably don't.
+Services require admin rights to install and tie the gateway's lifecycle to machine boot, not user login. The typical Hermes user wants: log in → gateway available, log out → gateway gone. Scheduled Tasks do exactly that without elevation. If you genuinely want a service, use `nssm` or `sc create` manually — but you probably don't. If you do, name it `Hermes*` or point its binary path inside the Hermes install (`venv\Scripts\hermes.exe`, the checkout, or `gateway-service\`): `hermes update` stops and restarts only services it can positively identify as Hermes-owned through the Service Control Manager, and pauses a Scheduled-Task-launched gateway by PID (Task Scheduler itself is never touched).
## Data layout