Skip to content

The agent that grows with you

feat(gateway): `hermes gateway status` reports Windows Scheduled Task registration drift

teknium12097cc6b88a6
diff --git a/hermes_cli/gateway_windows.py b/hermes_cli/gateway_windows.py
index 425f86ea2d9..c65dbdfe85b 100644
--- a/hermes_cli/gateway_windows.py
+++ b/hermes_cli/gateway_windows.py
@@ -1235,6 +1235,48 @@ def _task_xml_leaf_values(xml: str) -> dict[str, str] | None:
return values
+# Allowlist of template leaves whose absence/mismatch on the live task means it predates the current
+# template (#113670). Never a full-leaf compare: schtasks exports <UserId> as a SID while the template
+# writes DOMAIN\user, so equality would flag every healthy registration.
+_TASK_DRIFT_LEAVES = {
+ "Task/Settings/RestartOnFailure/Interval": "RestartOnFailure",
+ "Task/Triggers/LogonTrigger/Delay": "LogonTrigger Delay",
+ "Task/Actions/Exec/Arguments": "launcher arguments",
+}
+
+
+def compare_scheduled_task_drift(registered_xml: str, template_xml: str) -> list[str]:
+ """Human-readable drift fragments between a registered task export and the current template,
+ over ``_TASK_DRIFT_LEAVES`` plus the Task ``version``. Empty when aligned or when either side
+ does not parse (fail open)."""
+ live = _task_xml_leaf_values(registered_xml)
+ want = _task_xml_leaf_values(template_xml)
+ if live is None or want is None:
+ return []
+ missing = [label for path, label in _TASK_DRIFT_LEAVES.items() if path in want and path not in live]
+ differs = [label for path, label in _TASK_DRIFT_LEAVES.items() if path in want and path in live and live[path] != want[path]]
+ drift = []
+ if missing:
+ drift.append(f"missing: {', '.join(missing)}")
+ drift.extend(f"{label} differs" for label in differs)
+ if live["Task@version"] != want["Task@version"]:
+ drift.append(f"version {live['Task@version']} vs {want['Task@version']}")
+ return drift
+
+
+def _print_scheduled_task_drift(task_name: str) -> None:
+ """Warn when the registered task predates ``_build_scheduled_task_xml``; silent when it cannot be
+ queried. Reports only — re-registration stays behind the explicit ``hermes gateway install``."""
+ registered = _query_scheduled_task_xml(task_name)
+ if registered is None:
+ return
+ template = _build_scheduled_task_xml(task_name, get_task_script_path().with_suffix(".vbs"), _resolve_task_user())
+ drift = compare_scheduled_task_drift(registered, template)
+ if drift:
+ print(f"⚠ Scheduled Task registration predates the current template ({'; '.join(drift)})")
+ print(" Repair: hermes gateway install")
+
+
def is_installed() -> bool:
"""True when either the schtasks entry or the Startup fallback is present."""
return is_task_registered() or is_startup_entry_installed()
@@ -1399,6 +1441,7 @@ def status(deep: bool = False) -> None:
for key in ("status", "last run time", "last run result"):
if key in info:
print(f" {key.title()}: {info[key]}")
+ _print_scheduled_task_drift(task_name)
elif startup_installed:
entry = get_startup_entry_path()
print(f"✓ Windows login item installed: {entry if entry.exists() else _legacy_startup_entry_path()}")
diff --git a/tests/hermes_cli/test_gateway_windows.py b/tests/hermes_cli/test_gateway_windows.py
index 4155ec1e248..ba370b26414 100644
--- a/tests/hermes_cli/test_gateway_windows.py
+++ b/tests/hermes_cli/test_gateway_windows.py
@@ -385,6 +385,68 @@ def test_uninstall_and_reinstall_sweep_stale_startup_staging_file(monkeypatch, t
assert not staging.exists()
+# 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">
+ <Settings>
+ <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
+ <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
+ <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
+ <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
+ <UseUnifiedSchedulingEngine>true</UseUnifiedSchedulingEngine>
+ </Settings>
+ <Triggers>
+ <LogonTrigger />
+ </Triggers>
+ <Actions Context="Author">
+ <Exec>
+ <Command>wscript.exe</Command>
+ <Arguments>"C:\\Users\\me\\.hermes\\gateway-service\\Hermes_Gateway.vbs"</Arguments>
+ </Exec>
+ </Actions>
+</Task>
+"""
+
+
+def test_scheduled_task_drift_names_missing_hardening_leaves(monkeypatch):
+ """A pre-hardening registration is reported leaf by leaf, and the report is what
+ ``hermes gateway status`` prints together with the ``hermes gateway install`` repair hint."""
+ launcher = Path(r"C:\Users\me\.hermes\gateway-service\Hermes_Gateway.vbs")
+ template = gateway_windows._build_scheduled_task_xml("Hermes_Gateway", launcher, r"PC\me")
+ drift = gateway_windows.compare_scheduled_task_drift(_PRE_HARDENING_TASK_XML, template)
+ assert drift == [
+ "missing: RestartOnFailure, LogonTrigger Delay",
+ "launcher arguments differs",
+ "version 1.3 vs 1.4",
+ ]
+
+ printed: list[str] = []
+ monkeypatch.setattr(gateway_windows, "_exec_schtasks", lambda args: (0, _PRE_HARDENING_TASK_XML if "/XML" in args else "", ""))
+ monkeypatch.setattr(gateway_windows, "get_task_script_path", lambda: launcher.with_suffix(".cmd"))
+ monkeypatch.setattr(gateway_windows, "_resolve_task_user", lambda: r"PC\me")
+ monkeypatch.setattr("builtins.print", lambda *a, **k: printed.append(" ".join(map(str, a))))
+ gateway_windows._print_scheduled_task_drift("Hermes_Gateway")
+ assert printed[0].startswith("⚠ Scheduled Task registration predates the current template (missing: RestartOnFailure")
+ assert "hermes gateway install" in printed[1]
+
+
+def test_scheduled_task_drift_is_silent_when_aligned_or_unqueryable(monkeypatch):
+ """The template compared to itself (with the SID-style <UserId> schtasks exports) is not drift, and
+ a failed ``schtasks /Query /XML`` prints nothing — status must never nag a healthy install."""
+ launcher = Path(r"C:\Users\me\.hermes\gateway-service\Hermes_Gateway.vbs")
+ template = gateway_windows._build_scheduled_task_xml("Hermes_Gateway", launcher, r"PC\me")
+ exported = template.replace(r"<UserId>PC\me</UserId>", "<UserId>S-1-5-21-1-2-3-1001</UserId>")
+ assert exported != template
+ assert gateway_windows.compare_scheduled_task_drift(exported, template) == []
+ assert gateway_windows.compare_scheduled_task_drift("not xml", template) == []
+
+ printed: list[str] = []
+ monkeypatch.setattr(gateway_windows, "_exec_schtasks", lambda args: (1, "", "ERROR: The system cannot find the file specified."))
+ monkeypatch.setattr("builtins.print", lambda *a, **k: printed.append(" ".join(map(str, a))))
+ gateway_windows._print_scheduled_task_drift("Hermes_Gateway")
+ assert printed == []
+
+
diff --git a/website/docs/user-guide/messaging/index.md b/website/docs/user-guide/messaging/index.md
index 6daa98cf991..63af6e06161 100644
--- a/website/docs/user-guide/messaging/index.md
+++ b/website/docs/user-guide/messaging/index.md
@@ -651,6 +651,30 @@ launchd plists are static — if you install new tools (e.g. a new Node.js versi
Like the Linux systemd service, each `HERMES_HOME` directory gets its own launchd label. The default `~/.hermes` uses `ai.hermes.gateway`; other installations use `ai.hermes.gateway-<suffix>`.
:::
+### Windows (Task Scheduler)
+
+```powershell
+hermes gateway install # Register the Hermes_Gateway Scheduled Task (runs at logon)
+hermes gateway start # Start the gateway hidden, without a console window
+hermes gateway stop # Drain and stop the service
+hermes gateway status # Check status, including registration drift
+```
+
+The Scheduled Task runs `wscript.exe` on a generated `.vbs` launcher under `%USERPROFILE%\.hermes\gateway-service\`. The launcher starts `python.exe -m hermes_cli.main gateway run` with a hidden window and **exits immediately** — by design: `wscript.exe` has no console, so at logon it never receives the `CTRL_CLOSE_EVENT` that kills a `cmd.exe`-hosted gateway, and the gateway inherits one hidden console instead of every subprocess flashing its own (see `hermes_cli/gateway_windows.py::_build_gateway_vbs_script`).
+
+:::warning RestartOnFailure covers the launcher, not the gateway
+Because the launcher returns as soon as the gateway is spawned, Task Scheduler only ever sees the launcher's exit code. The `<RestartOnFailure>` policy in the registered task therefore fires only when `wscript.exe` itself fails to start the gateway — it does **not** restart a gateway that crashes or is killed later. Gateway auto-restart on Windows relies on the gateway's own in-process restart path (`/restart`, updates, and the `hermes gateway restart` command); a gateway killed from outside stays down until `hermes gateway start` or `schtasks /Run /TN <task>`.
+:::
+
+`hermes gateway install` writes the task from the current template, but an existing registration is never rewritten automatically — a task registered by an older build keeps its old settings (no `RestartOnFailure`, no logon `Delay`, an older launcher command line) indefinitely. `hermes gateway status` compares the registered task with the current template and warns when it predates it:
+
+```
+⚠ Scheduled Task registration predates the current template (missing: RestartOnFailure, LogonTrigger Delay; version 1.3 vs 1.4)
+ Repair: hermes gateway install
+```
+
+Re-running `hermes gateway install` deletes and re-creates the task from the current template. The check is silent when the task cannot be queried, and it only inspects a few settings Hermes owns (task version, `RestartOnFailure`, the logon trigger delay and the launcher arguments), so deliberate local edits elsewhere in the task are not flagged.
+
## Platform-Specific Toolsets
Each platform has its own toolset: