The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(install-state): a Windows gateway's Scheduled Task and Startup fallback name its home
alt-glitcha34a281b9f8f
diff --git a/hermes_cli/gateway_service_owner.py b/hermes_cli/gateway_service_owner.pyindex ea33d762489..29b35f9c38c 100644--- a/hermes_cli/gateway_service_owner.py+++ b/hermes_cli/gateway_service_owner.py@@ -107,6 +107,14 @@ def service_definition_homes(definition: str) -> list[str]:return homes+def service_definition_launchers(definition: str) -> list[str]:+ """The scripts a definition starts, by their quoted absolute paths. The Windows Startup-folder+ fallback and a Scheduled Task's action name no home: they start the home's ``gateway.vbs``, which does."""+ import re+ found = re.findall(r'"((?:[A-Za-z]:[\\/]|\\\\|/)[^"\r\n]*\.(?:vbs|cmd))"', definition, flags=re.IGNORECASE)+ return list(dict.fromkeys(found))++def temp_home_in_service_definition(definition: str) -> str | None:"""Temp-dir HERMES_HOME baked into a systemd unit / launchd plist, or None. A temp home means atest/E2E harness generated it; installing it leaves the gateway "running" but deaf to every platform."""diff --git a/hermes_cli/gateway_windows.py b/hermes_cli/gateway_windows.pyindex a0646a814ee..f275836be8a 100644--- a/hermes_cli/gateway_windows.py+++ b/hermes_cli/gateway_windows.py@@ -182,7 +182,7 @@ def _quote_vbs_string(value: str) -> str:# ── schtasks.exe wrapper-def _exec_schtasks(args: list[str]) -> tuple[int, str, str]:+def _exec_schtasks(args: list[str], timeout: float = _SCHTASKS_TIMEOUT_S) -> tuple[int, str, str]:"""Run ``schtasks.exe`` with a hard timeout. Return (code, stdout, stderr); a wedge returnscode=124 with a synthetic stderr so the fallback regex matches."""_assert_windows()@@ -194,7 +194,7 @@ def _exec_schtasks(args: list[str]) -> tuple[int, str, str]:# UnicodeDecodeError from subprocess' reader threads. CREATE_NO_WINDOW: no flashing console under a TUI.proc = subprocess.run([schtasks, *args], capture_output=True, text=False,- timeout=_SCHTASKS_TIMEOUT_S, creationflags=windows_hide_flags(),+ timeout=timeout, creationflags=windows_hide_flags(),check=False,)return (@@ -203,7 +203,7 @@ def _exec_schtasks(args: list[str]) -> tuple[int, str, str]:_decode_schtasks_output(proc.stderr or b""),)except subprocess.TimeoutExpired:- return (124, "", f"schtasks timed out after {_SCHTASKS_TIMEOUT_S}s")+ return (124, "", f"schtasks timed out after {timeout}s")except OSError as e:return (1, "", f"schtasks invocation failed: {e}")@@ -1383,6 +1383,29 @@ def _query_scheduled_task_xml(task_name: str) -> str | None:return out+# The install probe runs before the desktop backend says ready: a wedged schtasks must not hold that.+_TASK_PROBE_TIMEOUT_S = 5+++def registered_task_launchers() -> list[str]:+ """The scripts this OS user's ``Hermes_Gateway*`` Scheduled Tasks start (``install_state``). A task+ install removes the Startup-folder entries, so for a custom home the task is all that still names+ it. Empty off Windows, and when Task Scheduler does not answer, as for an unreadable Startup entry."""+ if sys.platform != "win32":+ return []+ from hermes_cli.gateway_service_owner import service_definition_launchers++ code, listing, _err = _exec_schtasks(["/Query", "/FO", "CSV", "/NH"], timeout=_TASK_PROBE_TIMEOUT_S)+ names = re.findall(rf'^"\\({_TASK_NAME_DEFAULT}[^"\\]*)"', listing, flags=re.MULTILINE) if code == 0 else []+ launchers: list[str] = []+ for name in dict.fromkeys(names):+ code, xml, _err = _exec_schtasks(["/Query", "/TN", name, "/XML"], timeout=_TASK_PROBE_TIMEOUT_S)+ leaves = (_task_xml_leaf_values(xml) if code == 0 else None) or {}+ command = leaves.get("Task/Actions/Exec/Command", "").strip('"')+ launchers += service_definition_launchers(f'"{command}" {leaves.get("Task/Actions/Exec/Arguments", "")}')+ return launchers++def _task_xml_leaf_values(xml: str) -> dict[str, str] | None:"""Namespace-agnostic ``Task/Settings/...`` leaf-path → text map, or ``None`` for invalid XML.The root ``version`` attribute is exposed as ``Task@version``."""diff --git a/hermes_cli/install_state.py b/hermes_cli/install_state.pyindex de121a625f8..efa2158f0f4 100644--- a/hermes_cli/install_state.py+++ b/hermes_cli/install_state.py@@ -249,19 +249,36 @@ def _registry_home() -> Iterable[Path]:def _service_homes() -> Iterable[Path]:- """The ``HERMES_HOME`` of every gateway service this OS user runs: its own definitions, and the- machine-wide units that run as it. Another account's gateway is that account's install."""- from hermes_cli.gateway_service_owner import service_definition_homes+ """The ``HERMES_HOME`` of every gateway service this OS user runs: its own definitions, the+ machine-wide units that run as it, and the launchers its Scheduled Tasks start. Another account's+ gateway is that account's install."""+ from hermes_cli import gateway_windowsfrom hermes_platform.resolver import known_dirsfor machine_wide, globs in ((False, known_dirs.gateway_service_definition_globs()),(True, known_dirs.system_gateway_service_definition_globs())):for definition in _expand_all(globs):- with contextlib.suppress(OSError, UnicodeError, ValueError):- text = _read_text(definition)- account = _unit_account(text) or ("root" if machine_wide else None)- if account is None or _is_this_account(account):- yield from (Path(home.strip().strip('"')) for home in service_definition_homes(text))+ yield from _definition_homes(definition, machine_wide=machine_wide)+ for launcher in gateway_windows.registered_task_launchers():+ yield from _definition_homes(Path(launcher), machine_wide=False, follow=False)+++def _definition_homes(definition: Path, *, machine_wide: bool, follow: bool = True) -> Iterator[Path]:+ """The homes one definition names, and those named by the launchers it starts (the Windows+ Startup-folder fallback names only its launcher). Unreadable: none."""+ from hermes_cli.gateway_service_owner import service_definition_homes, service_definition_launchers++ try:+ text = _read_text(definition)+ except (OSError, UnicodeError, ValueError):+ return+ account = _unit_account(text) or ("root" if machine_wide else None)+ if account is not None and not _is_this_account(account):+ return+ yield from (Path(home.strip().strip('"')) for home in service_definition_homes(text))+ if follow:+ for launcher in service_definition_launchers(text):+ yield from _definition_homes(Path(launcher), machine_wide=False, follow=False)def _unit_account(unit: str) -> str | None:diff --git a/tests/hermes_cli/test_gateway_windows.py b/tests/hermes_cli/test_gateway_windows.pyindex 220a846d69f..17fffac45b2 100644--- a/tests/hermes_cli/test_gateway_windows.py+++ b/tests/hermes_cli/test_gateway_windows.py@@ -43,6 +43,24 @@ def test_exec_schtasks_decodes_ansi_output_under_utf8_mode(monkeypatch):assert gateway_windows._is_access_denied(err) and gateway_windows._should_fall_back(1, err)[email protected]("windows")+def test_registered_task_launchers_reads_each_hermes_task_action(monkeypatch):+ """The install probe's view of the Scheduled Tasks: the launcher each ``Hermes_Gateway*`` task+ starts, as the task XML this module writes names it, and a pre-``wscript`` task's ``.cmd``."""+ launcher = r"C:\Users\Ann Lee\custom hermes\gateway-service\Hermes_Gateway_work.vbs"+ legacy = r"C:\Users\ann\h2\gateway-service\Hermes_Gateway.cmd"+ current = gateway_windows._build_scheduled_task_xml("Hermes_Gateway_work", Path(launcher), "PC\\ann")+ older = current.replace("<Command>wscript.exe</Command>", f"<Command>{legacy}</Command>").replace(+ f'//B //Nologo "{launcher}"', "")+ listing = ('\r\n"\\Microsoft\\Windows\\Defrag\\ScheduledDefrag","N/A","Ready"\r\n'+ '"\\Hermes_Gateway_work","N/A","Ready"\r\n"\\Hermes_Gateway","N/A","Running"\r\n')+ xml = {"Hermes_Gateway_work": current, "Hermes_Gateway": older}+ monkeypatch.setattr(gateway_windows, "_exec_schtasks",+ lambda args, timeout=None: (0, listing if "/FO" in args else xml[args[2]], ""))++ assert gateway_windows.registered_task_launchers() == [launcher, legacy]++@pytest.mark.platforms("windows")def test_exec_schtasks_round_trips_non_ascii_task_argument_live(monkeypatch):"""Real schtasks.exe on a real task whose argument carries a non-ASCII (ANSI-representable)diff --git a/tests/hermes_cli/test_install_state.py b/tests/hermes_cli/test_install_state.pyindex 4fbc9ba84a6..cbfd4faa815 100644--- a/tests/hermes_cli/test_install_state.py+++ b/tests/hermes_cli/test_install_state.py@@ -140,6 +140,28 @@ def test_gateway_service_definitions_name_their_homes(tmp_path, monkeypatch):assert set(install_state._service_homes()) == {home, Path(f"{home}-win")}+def test_a_gateway_started_by_a_scheduled_task_or_the_startup_fallback_names_its_home(tmp_path, monkeypatch):+ """A Scheduled Task install removes the Startup-folder entries, and the Startup fallback only starts+ the home's own launcher: both name their home through the ``gateway.vbs`` they start."""+ from hermes_cli import gateway_windows+ from hermes_platform.resolver import known_dirs++ def launcher(home: Path) -> Path: # what _write_task_script leaves in the home+ script = home / "gateway-service" / "Hermes_Gateway.vbs"+ script.parent.mkdir(parents=True)+ script.write_text(f'env.Item("HERMES_HOME") = "{home}"\r\n', encoding="utf-8")+ return script++ by_task, by_startup = tmp_path / "task home", tmp_path / "startup home"+ startup = tmp_path / "Startup" / "Hermes_Gateway.vbs"+ startup.parent.mkdir()+ startup.write_text(gateway_windows._build_startup_launcher(launcher(by_startup).with_suffix(".cmd")), encoding="utf-8")+ monkeypatch.setattr(known_dirs, "gateway_service_definition_globs", lambda: (str(startup.parent / "Hermes_Gateway*"),))+ monkeypatch.setattr(gateway_windows, "registered_task_launchers", lambda: [str(launcher(by_task))], raising=False)++ assert {by_task, by_startup} <= set(install_state._service_homes())++@pytest.mark.platforms("posix")def test_a_gateway_service_counts_only_for_the_account_it_runs_as(tmp_path, monkeypatch):"""A machine-wide unit is another account's install unless it runs as this one (``User=``, root