The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(hermes_cli/update): compact Windows gateway pause/resume module — walrus rungs, poll helper reuse, shared purpose tuple
Tekniumb5605b7a8219
diff --git a/hermes_cli/update_cmd_windows.py b/hermes_cli/update_cmd_windows.pyindex 6dc9585ff05..76def34f88f 100644--- a/hermes_cli/update_cmd_windows.py+++ b/hermes_cli/update_cmd_windows.py@@ -17,8 +17,9 @@ from pathlib import Pathfrom hermes_cli.update_cmd_common import _best_effort-# Log-record parity with the origin module.-logger = logging.getLogger("hermes_cli.update_cmd")+logger = logging.getLogger("hermes_cli.update_cmd") # log-record parity with the origin module++_BACKEND_PURPOSES = ("serve", "dashboard")@contextmanager@@ -35,11 +36,8 @@ def _write_update_planned_stop_marker(profile_path: Path, pid: int) -> bool:try:from gateway.status import _get_process_start_timefrom utils import atomic_json_write-- record = {- "target_pid": pid, "target_start_time": _get_process_start_time(pid),- "stopper_pid": os.getpid(), "written_at": datetime.now(timezone.utc).isoformat(),- }+ record = {"target_pid": pid, "target_start_time": _get_process_start_time(pid),+ "stopper_pid": os.getpid(), "written_at": datetime.now(timezone.utc).isoformat()}atomic_json_write(Path(profile_path) / ".gateway-planned-stop.json", record, indent=None, separators=(",", ":"))return Trueexcept (OSError, PermissionError):@@ -50,7 +48,6 @@ def _wait_for_windows_update_gateway_exit(pids: list[int], *, timeout: float) ->"""Wait for the given gateway PIDs to exit, returning survivors."""if not pids:return set()-from gateway.status import _pid_existsdef _alive(pid: int) -> bool:@@ -72,8 +69,8 @@ def _self_and_non_gateway_ancestor_pids(psutil) -> set[int]:"""PIDs a venv-holder scan must never nominate: this process and its non-gateway ancestry.Do NOT blanket-exclude ancestors: under ``/update`` the updater is a CHILD of the gateway, and hiding it- dead-ends the update on ``venv-blocked``. Keep GATEWAY ancestors visible (the pause path stops them- gracefully; a detached child survives on Windows); never nominate interactive ancestry as a blocker.+ dead-ends the update on ``venv-blocked``. Gateway ancestors stay visible (the pause path stops them+ gracefully; a detached child survives on Windows); interactive ancestry is never a blocker."""try:from gateway.status import looks_like_gateway_command_line as _is_gw@@ -125,21 +122,19 @@ def _detect_venv_python_processes(*, exclude_pids: set[int] | None = None) -> liThe hermes.exe shim guard misses the Desktop backend and anything off ``venv\\Scripts\\python(w).exe``;they keep ``.pyd`` files mapped so a mid-update dependency sync dies half-way. Empty off-Windows / without- psutil; self + non-gateway ancestors excluded.+ psutil; self + non-gateway ancestors excluded. cmdline/cwd are expensive per process on Windows (500++ procs can blow the Desktop preflight watchdog), so they are fetched lazily for plausible candidates only.+ The FULL cmdline is kept: callers parse it (the pausable-gateway exemption looks for ``gateway run``)."""from hermes_cli.update_cmd import _mpsutil = _psutil()if not _m()._is_windows() or psutil is None:return []-venv_prefix = _lower_dir_prefix(_m().PROJECT_ROOT / "venv")root_prefix = _lower_dir_prefix(_m().PROJECT_ROOT)skip = set(exclude_pids or set()) | _self_and_non_gateway_ancestor_pids(psutil)-matches: list[tuple[int, str, str]] = []try:- # cmdline/cwd are expensive per-process on Windows (500+ procs can blow the- # Desktop preflight watchdog): fetch them lazily for plausible candidates only.proc_iter = psutil.process_iter(["pid", "exe", "name"])except Exception:return []@@ -174,8 +169,6 @@ def _detect_venv_python_processes(*, exclude_pids: set[int] | None = None) -> licwd_low = os.sepis_holder = root_prefix in cmdline_low or cwd_low.startswith(root_prefix)if is_holder:- # FULL cmdline: callers parse it (pausable-gateway exemption looks for `gateway run`);- # truncating here misreported autostarted gateways as blockers. Truncate at display time.matches.append((int(pid), name, cmdline_raw))return matches@@ -200,9 +193,7 @@ def _holder_value_flags() -> frozenset:flags: set[str] = {"--profile", "-p", "--config"}try:from hermes_cli._parser import build_top_level_parser-- parser = build_top_level_parser()[0]- for action in parser._actions:+ for action in build_top_level_parser()[0]._actions:if action.option_strings and action.nargs != 0:flags.update(action.option_strings)_holder_value_flags_cache = frozenset(flags)@@ -231,7 +222,6 @@ def _hermes_holder_subcommand(cmdline: str) -> str | None:entry_idx = next((i for i, token in enumerate(tokens) if _is_entry(i, token)), None)if entry_idx is None:return None-value_flags = _holder_value_flags()i = entry_idx + 1while i < len(tokens):@@ -251,12 +241,12 @@ def _format_venv_python_holders_message(matches: list[tuple[int, str, str]]) ->Labels come from the parsed SUBCOMMAND, never substring: a standalone ``hermes dashboard`` must not becalled the Desktop backend, ``--preserve-cache`` must not match "serve". Unknown argv gets no hint."""- lines = ["✗ Other Hermes processes are running from this install's venv:"]hint_by_subcommand = {"serve": " ← Hermes backend (if the Desktop app is open, close it)","dashboard": " ← hermes dashboard (stop it: hermes dashboard stop, or close that terminal)","gateway": " ← gateway",}+ lines = ["✗ Other Hermes processes are running from this install's venv:"]for pid, name, cmdline in matches[:6]:hint = hint_by_subcommand.get(_hermes_holder_subcommand(cmdline) or "", "")lines.append(f" PID {pid} {name} {cmdline[:120]}{hint}")@@ -284,9 +274,8 @@ def _venv_launcher_ancestors(pids: list[int]) -> list[int]:psutil = _psutil()if not _m()._is_windows() or not pids or psutil is None:return []-venv_prefix = _lower_dir_prefix(_m().PROJECT_ROOT / "venv")- skip = _self_and_non_gateway_ancestor_pids(psutil)+ skip = _self_and_non_gateway_ancestor_pids(psutil) | set(pids)found: list[int] = []for pid in pids:with suppress(Exception):@@ -294,9 +283,7 @@ def _venv_launcher_ancestors(pids: list[int]) -> list[int]:if parent is None:continueppid = int(parent.pid)- if ppid in skip or ppid in found or ppid in set(pids):- continue- if (parent.exe() or "").lower().startswith(venv_prefix):+ if ppid not in skip and ppid not in found and (parent.exe() or "").lower().startswith(venv_prefix):found.append(ppid)return found@@ -309,7 +296,6 @@ def _leftover_pausable_gateway_pids(matches: list[tuple[int, str, str]]) -> listre-read via psutil when possible since the scan may hold only a cmdline prefix."""from hermes_cli._scan_venv_blockers import _is_pausable_gateway-psutil = _psutil()pids: list[int] = []for pid, _name, cmdline in matches:@@ -332,17 +318,15 @@ def _refuse_gateway_ancestor_tree_kill(pids: list[int], *, gateway_mode: bool) -return Falsetry:from hermes_cli.gateway import _is_pid_ancestor_of_current_process-ancestors = [int(pid) for pid in pids if _is_pid_ancestor_of_current_process(int(pid))]except Exception as exc:logger.debug("Could not inspect gateway ancestry before tree-kill: %s", exc)return Falseif not ancestors:return False- rendered = ", ".join(str(pid) for pid in ancestors)print("✗ Refusing to stop the gateway process tree because this updater "- f"is running inside it (gateway PID(s): {rendered}).\n"+ f"is running inside it (gateway PID(s): {', '.join(str(pid) for pid in ancestors)}).\n"" On Windows, taskkill /T would terminate the updater before the update can run.\n"" From a chat platform, use `/update` instead.\n"" Otherwise, run `hermes update` from a separate terminal."@@ -363,11 +347,8 @@ def _ledger_manual_serve_holders(matches: list[tuple[int, str, str]]) -> list[direturn []holder_pids = {int(pid) for pid, _name, _cmd in matches}return [- entry- for entry in ledger_entries()- if entry.get("purpose") in ("serve", "dashboard")- and isinstance(entry.get("pid"), int)- and entry["pid"] in holder_pids+ entry for entry in ledger_entries()+ if entry.get("purpose") in _BACKEND_PURPOSES and isinstance(entry.get("pid"), int) and entry["pid"] in holder_pidsand spawner_is_dead(entry) is not False # False = live Desktop supervisor owns it; keep refusing]@@ -377,27 +358,20 @@ def _serve_relaunch_commands(entries: list[dict]) -> list[list[str]]:(joined argv cannot round-trip Windows paths with spaces). Entries without a port are skipped."""from hermes_cli.update_cmd import _m- commands: list[list[str]] = []hermes = "hermes"with suppress(Exception):scripts_dir = _m()._venv_scripts_dir()if scripts_dir is not None:- for name in ("hermes.exe", "hermes"):- if (scripts_dir / name).is_file():- hermes = str(scripts_dir / name)- break+ hermes = next((str(scripts_dir / n) for n in ("hermes.exe", "hermes") if (scripts_dir / n).is_file()), hermes)+ commands: list[list[str]] = []for entry in entries:port = entry.get("port")if not isinstance(port, int) or port <= 0:continue- profile = str(entry.get("profile") or "")- host = str(entry.get("host") or "")+ profile, host = str(entry.get("profile") or ""), str(entry.get("host") or "")commands.append(- [hermes]- + (["--profile", profile] if profile and profile != "default" else [])- + [str(entry.get("purpose"))]- + (["--host", host] if host else [])- + ["--port", str(port)]+ [hermes] + (["--profile", profile] if profile and profile != "default" else [])+ + [str(entry.get("purpose"))] + (["--host", host] if host else []) + ["--port", str(port)])return commands@@ -458,16 +432,15 @@ def _orphaned_desktop_backend_pids(matches: list[tuple[int, str, str]]) -> list[psutil = _psutil()if psutil is None:return None-# Pass 1: find orphaned backend ROOTS among the holders.roots: list[tuple[int, int]] = []- remaining: list[tuple[int, str]] = [] # (pid, argv_low) still to justify+ remaining: list[int] = [] # holders still to justifyfor pid, _name, cmdline in matches:low = _live_argv_low(psutil, pid, cmdline)if low is None:continue # exited between scan and classification — nothing to reapif not _is_backend_argv(low):- remaining.append((int(pid), low))+ remaining.append(int(pid))continuetry:proc = psutil.Process(int(pid))@@ -478,26 +451,24 @@ def _orphaned_desktop_backend_pids(matches: list[tuple[int, str, str]]) -> list[continue # exited during classification — nothing to reapexcept Exception:return None-try:ppid = proc.ppid()parent = psutil.Process(ppid) if ppid else None- # PID-reuse check: a "parent" created after its child is a recycled PID.+ # PID-reuse check: a "parent" created after its child is a recycled PID. A live parent is+ # not a root but may be an orphan root's descendant (the venv trampoline re-execs uv+ # python with the SAME argv) — defer to pass 2.if parent is not None and parent.is_running() and parent.create_time() <= proc.create_time():- # Live parent: not a root, maybe an orphan root's descendant (the venv- # trampoline re-execs uv python with the SAME argv). Defer to pass 2.- remaining.append((int(pid), low))+ remaining.append(int(pid))continueexcept psutil.NoSuchProcess:pass # parent gone → orphanexcept Exception:return Noneroots.append((int(pid), process_start_time))-# Pass 2: every non-backend holder must descend from an accepted orphan root# (dies with the tree reap); anything else keeps the refusal.root_set = {pid for pid, _start_time in roots}- for pid, _low in remaining:+ for pid in remaining:if not root_set:return Nonetry:@@ -519,17 +490,13 @@ def _ledger_reapable_backend_pids(matches: list[tuple[int, str, str]]) -> list[i"""try:from hermes_cli.process_identity import REAPABLE_PURPOSES, ledger_entries, spawner_is_dead-entries = ledger_entries()except Exception:return []by_pid = {e.get("pid"): e for e in entries if isinstance(e.get("pid"), int)}return [- int(pid)- for pid, _name, _cmdline in matches- if (entry := by_pid.get(int(pid)))- and entry.get("purpose") in REAPABLE_PURPOSES- and spawner_is_dead(entry) is True+ int(pid) for pid, _name, _cmdline in matches+ if (entry := by_pid.get(int(pid))) and entry.get("purpose") in REAPABLE_PURPOSES and spawner_is_dead(entry) is True]@@ -562,7 +529,6 @@ def _stop_process_trees(pids: list[int] | list[tuple[int, int]]) -> None:"""from gateway.status import get_process_start_timefrom hermes_cli._subprocess_compat import pid_is_hermes, windows_hide_flags-for entry in pids:pid, expected_start_time = entry if isinstance(entry, tuple) else (int(entry), get_process_start_time(int(entry)))try:@@ -588,34 +554,32 @@ def _looks_like_desktop_control_plane(cmdline: str) -> bool:parser-derived classifier, never substring (``kanban --preserve-cache``, ``-m dashboard chat``).Undeterminable subcommand is NOT a control plane."""- return "hermes_cli.main" in (cmdline or "").lower() and _hermes_holder_subcommand(cmdline) in ("serve", "dashboard")+ return "hermes_cli.main" in (cmdline or "").lower() and _hermes_holder_subcommand(cmdline) in _BACKEND_PURPOSESdef _desktop_owns_gateway_lifecycle() -> bool:"""True when Desktop currently supervises this install's control plane (updater must not steal gateway start).Not proof messaging is served: serve is the control plane, the gateway a detached sibling. Prefer the spawn- ledger; fall back to the venv-holder scan. An orphaned control plane (supervisor gone) does not count.+ ledger; fall back to the venv-holder scan. An orphaned control plane (supervisor gone) does not count;+ without psutil orphanhood is unprovable and a live control plane suffices."""from hermes_cli.update_cmd import _mwith _best_effort('Desktop-lifecycle ledger probe failed: %s'):from hermes_cli.process_identity import ledger_entries, spawner_is_dead-- if any(e.get("purpose") in ("serve", "dashboard") and spawner_is_dead(e) is False for e in ledger_entries()):+ if any(e.get("purpose") in _BACKEND_PURPOSES and spawner_is_dead(e) is False for e in ledger_entries()):return True-psutil = _psutil()try:holders = _m()._detect_venv_python_processes()except Exception as exc:logger.debug("Desktop-lifecycle holder scan failed: %s", exc)return False-for pid, _name, cmdline in holders:if not _looks_like_desktop_control_plane(cmdline):continueif psutil is None:- return True # cannot prove orphanhood; a live control plane suffices+ return Truewith suppress(Exception):if _parent_is_live(psutil.Process(int(pid))):return True@@ -675,19 +639,14 @@ def _verify_service_identities(psutil, name: str, service, expected_service_idenif current_service_pid != int(expected_service_identity[0]):raise RuntimeError(f"Windows service {name} SCM process identity changed before stop")for label, identity in (("service", expected_service_identity), ("gateway", expected_gateway_identity)):- if identity is None:- continue- pid, create_time = identity- if abs(_process_create_time(psutil, pid, label, "before stop") - float(create_time)) > 0.001:+ if identity is not None and abs(_process_create_time(psutil, identity[0], label, "before stop") - float(identity[1])) > 0.001:raise RuntimeError(f"Windows {label} process identity changed before stop")if expected_service_identity is not None and expected_gateway_identity is not None:- service_pid = int(expected_service_identity[0])- gateway_pid = int(expected_gateway_identity[0])try:- ancestor_pids = {int(parent.pid) for parent in psutil.Process(gateway_pid).parents()}+ ancestor_pids = {int(parent.pid) for parent in psutil.Process(int(expected_gateway_identity[0])).parents()}except Exception as exc:raise RuntimeError("Windows gateway ancestry is unavailable before service stop") from exc- if service_pid not in ancestor_pids:+ if int(expected_service_identity[0]) not in ancestor_pids:raise RuntimeError(f"Windows gateway is no longer owned by service {name}")@@ -698,9 +657,11 @@ def _stop_windows_gateway_service(expected_gateway_identity: tuple[int, float] | None = None,timeout: float = 30.0,) -> None:- """Stop one verified Windows service and wait until SCM reports it down."""- import psutil # noqa: PLC0415+ """Stop one verified Windows service and wait until SCM reports it down.+ Lingering matching-identity processes after SCM says stopped make venv mutation unsafe — fail closed.+ """+ import psutil # noqa: PLC0415service = psutil.win_service_get(name)_verify_service_identities(psutil, name, service, expected_service_identity, expected_gateway_identity)_sc_exe("stop", name, service, "stopped")@@ -711,16 +672,13 @@ def _stop_windows_gateway_service(if not _poll_until(lambda: service.status() == "stopped" and not _alive(), timeout):if service.status() != "stopped":raise RuntimeError(f"Windows service {name} did not stop within {timeout:.0f}s; venv mutation unsafe.")- # Lingering matching-identity processes make venv mutation unsafe — fail closed.- alive_after_stop = _alive()- if alive_after_stop:+ if alive_after_stop := _alive():raise RuntimeError(f"Windows service {name} stopped but its process tree is still alive: {alive_after_stop}")def _start_windows_gateway_service(name: str, *, timeout: float = 30.0) -> None:"""Start one previously paused Windows service and verify it is running."""import psutil # noqa: PLC0415-service = psutil.win_service_get(name)_sc_exe("start", name, service, "running")if not _poll_until(lambda: service.status() == "running", timeout):@@ -731,18 +689,16 @@ def _restore_windows_gateway_service(name: str, *, timeout: float = 60.0) -> Non"""Restore a service after an uncertain stop, including STOP_PENDING."""from hermes_cli.update_cmd import _start_windows_gateway_serviceimport psutil # noqa: PLC0415-service = psutil.win_service_get(name)- deadline = _time.monotonic() + timeout- while _time.monotonic() < deadline:++ def _settled() -> bool:status = service.status()- if status == "running":- returnif status == "stopped":_start_windows_gateway_service(name)- return- _time.sleep(0.2)- raise RuntimeError(f"Windows service {name} did not reach a restorable state within {timeout:.0f}s")+ return status in ("running", "stopped")++ if not _poll_until(_settled, timeout):+ raise RuntimeError(f"Windows service {name} did not reach a restorable state within {timeout:.0f}s")def _windows_cold_start_plan() -> dict | None:@@ -754,14 +710,12 @@ def _windows_cold_start_plan() -> dict | None:the skip is ownership, not liveness."""from hermes_cli.update_cmd import _desktop_owns_gateway_lifecycle-with _best_effort('Could not check Desktop gateway-lifecycle ownership before update: %s'):if _desktop_owns_gateway_lifecycle():logger.debug("Skipping Windows gateway cold-start plan: Desktop owns gateway lifecycle")return Nonewith _best_effort('Could not check Windows gateway autostart state before update: %s'):from hermes_cli import gateway_windows-if gateway_windows.is_installed():return {"resume_needed": True, "profiles": {}, "unmapped_pids": [], "unmapped": [], "cold_start_if_installed": True}return None@@ -774,7 +728,6 @@ def _pause_windows_gateway_services(service_gateways, token: dict, profiles: dicservices AND the already-paused ordinary gateways before re-raising."""from hermes_cli.update_cmd import _restore_windows_gateway_service, _stop_windows_gateway_service-paused_services = []current_service_name = Nonetry:@@ -790,9 +743,7 @@ def _pause_windows_gateway_services(service_gateways, token: dict, profiles: diccurrent_service_name = Noneif paused_services:token.update(services=paused_services, expected_services=list(paused_services), restarted_services=[])- token["service_profiles"] = {- str(s.name): str(s.profile) for s in service_gateways if str(s.name) in paused_services- }+ token["service_profiles"] = {str(s.name): str(s.profile) for s in service_gateways if str(s.name) in paused_services}print(" ✓ Paused Windows gateway service(s): " + ", ".join(paused_services))return tokenexcept Exception as exc:@@ -813,9 +764,8 @@ def _pause_windows_gateway_services(service_gateways, token: dict, profiles: dicdef _discover_windows_gateways():- """``(profile_processes, service_gateways, running_pids)`` for the pause; any indeterminate probe aborts."""+ """``(profile_processes, service_gateways, service_gateway_pids, running_pids)`` for the pause; any indeterminate probe aborts."""from hermes_cli.gateway import find_gateway_pids, find_profile_gateway_processes, find_windows_gateway_services-with _abort_on_error("Could not map Windows gateway PIDs to profiles"):profile_process_list = find_profile_gateway_processes(strict=True)profile_processes = {proc.pid: proc for proc in profile_process_list}@@ -847,7 +797,6 @@ def _request_socket_pauses(running_pids, profile_processes, service_gateway_pids_write_update_planned_stop_marker(Path(proc.path), int(pid))try:from gateway.control_socket import pause_gateway_for_update-ack = pause_gateway_for_update(Path(proc.path))if ack and (ack.get("pausing") or ack.get("already_stopping")):socket_acks.append(ack)@@ -879,25 +828,18 @@ def _pause_windows_gateways_for_update() -> dict | None:locked during ``git``/``uv``. Stop only PIDs the gateway discovery code identifies."""from hermes_cli.update_cmd import _m-if not _m()._is_windows():return None-with _abort_on_error("Could not prepare Windows gateway pause for update"):from gateway.status import get_process_start_time, terminate_pidfrom hermes_cli.gateway import _capture_gateway_argv-profile_processes, service_gateways, service_gateway_pids, running_pids = _discover_windows_gateways()if not running_pids:return _windows_cold_start_plan()-profiles, mapped_pids, socket_acks = _request_socket_pauses(running_pids, profile_processes, service_gateway_pids)-- # Resolve venv-side launchers BEFORE draining: a dead worker's parent cannot be- # recovered (NoSuchProcess). The launcher keeps ``.pyd`` mapped and would trip the- # venv-holder guard after the gateway stopped; it is killed with the survivors.+ # Resolve venv-side launchers BEFORE draining: a dead worker's parent cannot be recovered (NoSuchProcess).+ # The launcher keeps ``.pyd`` mapped and would trip the venv-holder guard; it is killed with the survivors.launcher_pids = _m()._venv_launcher_ancestors(mapped_pids)-print("→ Stopping Windows gateway process(es) before updating Hermes...")drain_timeout = _gateway_drain_timeout(socket_acks)survivors = _m()._wait_for_windows_update_gateway_exit(mapped_pids, timeout=drain_timeout)@@ -913,7 +855,6 @@ def _pause_windows_gateways_for_update() -> dict | None:# Snapshot unmapped gateways' argv *before* force-killing so resume can replay it.# Unmapped = no profile->PID-file mapping (e.g. Scheduled Task ``pythonw.exe -m ...``).unmapped = [{"pid": int(pid), "argv": _argv_or_none(int(pid))} for pid in unmapped_pids]-# Tree-kill survivors, unmapped gateways, and pre-drain launchers; a launcher# already gone with its worker raises ProcessLookupError and is skipped.force_killed = []@@ -921,17 +862,14 @@ def _pause_windows_gateways_for_update() -> dict | None:with suppress(ProcessLookupError, PermissionError, OSError):terminate_pid(int(pid), force=True, expected_start_time=get_process_start_time(int(pid)))force_killed.append(int(pid))-if profiles:print(f" ✓ Paused gateway profile(s): {', '.join(sorted(profiles))}")if force_killed:print(f" → Force-stopped {len(force_killed)} gateway process(es)")if unmapped_pids:print(f" → Stopped {len(unmapped_pids)} gateway process(es) without profile mapping")- if any(not u.get("argv") for u in unmapped):- # No recoverable cmdline (psutil missing, access denied, gone): manual restart.+ if any(not u.get("argv") for u in unmapped): # no recoverable cmdline (psutil missing, denied, gone)print(" Restart manually after update: hermes gateway run")-token = {"resume_needed": True, "profiles": profiles, "unmapped_pids": unmapped_pids, "unmapped": unmapped}return _pause_windows_gateway_services(service_gateways, token, profiles, unmapped)@@ -941,6 +879,7 @@ def _cold_start_windows_gateway_after_update() -> bool:Idempotent: re-checks nothing is running so a concurrent autostart can't duplicate. A successful Popendoesn't prove survival (a job object denying breakaway kills it), so success is gated on the liveness poll.+ Vouched PIDs are attested so a death AFTER updater exit is reported by the next CLI invocation."""from hermes_cli.update_cmd import _desktop_owns_gateway_lifecycle, _mif not _m()._is_windows():@@ -963,7 +902,6 @@ def _cold_start_windows_gateway_after_update() -> bool:if not ready_pids:raise RuntimeError(f"Windows gateway cold-start PID {pid} did not become ready")print(f"\n✓ Gateway started via cold-start after update (PID: {', '.join(map(str, ready_pids))})")- # Vouched PIDs: a death AFTER updater exit is reported by the next CLI invocation.with suppress(Exception):gateway_windows._write_start_attestation(ready_pids, "cold-start after update")return True@@ -980,7 +918,6 @@ def _refresh_windows_gateway_launchers() -> None:returnwith _best_effort('Could not refresh Windows gateway launchers after update: %s'):from hermes_cli import gateway_windows-if gateway_windows.is_installed():gateway_windows._write_task_script()print(" ✓ Refreshed Windows gateway launcher scripts")@@ -998,10 +935,8 @@ def _refresh_bootstrap_cache_scripts(branch: str = "main") -> None:cache_dir = Path(_m().get_hermes_home()) / "bootstrap-cache"if not cache_dir.is_dir():return- # Mirror install_script.rs::sanitize_ref().- safe_ref = re.sub(r"[^A-Za-z0-9._-]", "_", str(branch or "main"))- # Mirror install_script.rs::is_valid_commit(): immutable commit pin, never rewrite.- if re.fullmatch(r"[0-9a-fA-F]{7,40}", safe_ref):+ safe_ref = re.sub(r"[^A-Za-z0-9._-]", "_", str(branch or "main")) # install_script.rs::sanitize_ref()+ if re.fullmatch(r"[0-9a-fA-F]{7,40}", safe_ref): # install_script.rs::is_valid_commit(): immutable pinreturnrefreshed = []for kind, src_name in (("ps1", "install.ps1"), ("sh", "install.sh")):@@ -1011,10 +946,9 @@ def _refresh_bootstrap_cache_scripts(branch: str = "main") -> None:continue # this ref was never bootstrap-cached — nothing to healdata = src.read_bytes()if kind == "ps1" and not data.startswith(b"\xef\xbb\xbf"):- # PowerShell needs the BOM or localized/em-dash text mis-decodes.- data = b"\xef\xbb\xbf" + data+ data = b"\xef\xbb\xbf" + data # PowerShell needs the BOM or localized/em-dash text mis-decodes.if cached.read_bytes() == data:- continue # already current+ continuetmp = cached.with_suffix(cached.suffix + ".tmp")tmp.write_bytes(data)os.replace(tmp, cached)@@ -1031,22 +965,20 @@ def _resume_windows_services(token: dict) -> None:verified_restarts = list(token.get("restarted_services") or [])restarted_services = []failed_services = []- for service_name in services:+ for service_name in map(str, services):try:- _start_windows_gateway_service(str(service_name))- restarted_services.append(str(service_name))- if str(service_name) not in verified_restarts:- verified_restarts.append(str(service_name))+ _start_windows_gateway_service(service_name)+ restarted_services.append(service_name)+ if service_name not in verified_restarts:+ verified_restarts.append(service_name)except Exception as exc:logger.warning("Could not restart Windows gateway service %s after update: %s", service_name, exc)print(f" ⚠ Could not restart Windows gateway service: {service_name}")- failed_services.append(str(service_name))-+ failed_services.append(service_name)token["restarted_services"] = verified_restarts+ token["services"] = failed_servicesif failed_services:- token["services"] = failed_servicesraise RuntimeError("Could not restart Windows gateway service(s): " + ", ".join(failed_services))- token["services"] = []if restarted_services:print("\n ✓ Restarted Windows gateway service(s): " + ", ".join(restarted_services))@@ -1071,27 +1003,21 @@ def _relaunch_paused_gateways(token: dict, profiles: dict, unmapped: list) -> turelaunched = []failed_profiles = {}for profile, old_pid in sorted(profiles.items()):- if _launched(- lambda p=profile, o=old_pid: launch_detached_profile_gateway_restart(str(p), int(o)),- "Could not restart Windows gateway profile %s after update: %s", profile,- ):+ if _launched(lambda p=profile, o=old_pid: launch_detached_profile_gateway_restart(str(p), int(o)),+ "Could not restart Windows gateway profile %s after update: %s", profile):relaunched.append(str(profile))else:failed_profiles[str(profile)] = int(old_pid)token["relaunched_profiles"] = relaunched-unmapped_relaunched = 0failed_unmapped = []for entry in unmapped:argv, old_pid = entry.get("argv"), entry.get("pid")- if argv and old_pid and _launched(- lambda o=old_pid, a=argv: launch_detached_gateway_restart_by_cmdline(int(o), list(a)),- "Could not restart unmapped Windows gateway (pid %s) after update: %s", old_pid,- ):+ if argv and old_pid and _launched(lambda o=old_pid, a=argv: launch_detached_gateway_restart_by_cmdline(int(o), list(a)),+ "Could not restart unmapped Windows gateway (pid %s) after update: %s", old_pid):unmapped_relaunched += 1else:failed_unmapped.append(entry)-token["profiles"] = failed_profilestoken["unmapped"] = failed_unmappedif failed_profiles or failed_unmapped:@@ -1132,12 +1058,10 @@ def _resume_windows_gateways_after_update(token: dict | None) -> None:if not _m()._is_windows():token["resume_needed"] = Falsereturn-# Regenerate launcher scripts before respawning so a legacy pythonw-era# autostart entry comes back on the current design at next login too._m()._refresh_windows_gateway_launchers()_resume_windows_services(token)-profiles = token.get("profiles") or {}unmapped = token.get("unmapped") or []if not profiles and not any(u.get("argv") for u in unmapped):@@ -1147,12 +1071,10 @@ def _resume_windows_gateways_after_update(token: dict | None) -> None:token["cold_start_if_installed"] = Falsetoken["resume_needed"] = Falsereturn-relaunched, unmapped_relaunched = _relaunch_paused_gateways(token, profiles, unmapped)if relaunched or unmapped_relaunched:_verify_relaunched_gateways_alive(token, profiles, unmapped)token["resume_needed"] = False-if relaunched:print(f"\n ✓ Restarting Windows gateway profile(s): {', '.join(relaunched)}")if unmapped_relaunched:@@ -1173,33 +1095,32 @@ def _resume_windows_gateways_and_merge_outcome(outcome, _windows_gateway_resume,print(f" ⚠ Windows gateway service restart incomplete: {_windows_resume_exc}")if gateway_mode:_write_gateway_update_exit_code(False)+ if not isinstance(_windows_gateway_resume, dict):+ return- if isinstance(_windows_gateway_resume, dict):- def _extend_unique(target: list, items) -> None:- target.extend(item for item in dict.fromkeys(items) if item not in target)-- token = _windows_gateway_resume- # Failed relaunches are absent from the token so they still surface. Best-effort.- with _best_effort('Could not merge Windows relaunch outcome into fleet reconciliation bookkeeping: %s'):- _extend_unique(outcome.relaunched_profiles, token.get("relaunched_profiles") or [])- windows_restarted = list(token.get("restarted_services") or [])- service_profiles = token.get("service_profiles") or {}- _extend_unique(outcome.restarted_services, windows_restarted)- _extend_unique(outcome.relaunched_profiles, (p for p in (service_profiles.get(n) for n in windows_restarted) if p))- _extend_unique(outcome.failed_or_stale_units, (str(service_profiles.get(n) or n) for n in (token.get("services") or [])))-- with suppress(Exception):- from hermes_cli.update_receipt import record_gateway_restart-- record_gateway_restart(- restarted_services=outcome.restarted_services,- relaunched_profiles=outcome.relaunched_profiles,- externally_supervised_profiles=outcome.externally_supervised_profiles,- killed_pids=sorted(outcome.killed_pids),- failed_units=outcome.failed_or_stale_units,- incomplete=outcome.incomplete or bool(outcome.failed_or_stale_units),- phase_error="; ".join(outcome.phase_errors) or None,- )+ def _extend_unique(target: list, items) -> None:+ target.extend(item for item in dict.fromkeys(items) if item not in target)++ token = _windows_gateway_resume+ # Failed relaunches are absent from the token so they still surface. Best-effort.+ with _best_effort('Could not merge Windows relaunch outcome into fleet reconciliation bookkeeping: %s'):+ _extend_unique(outcome.relaunched_profiles, token.get("relaunched_profiles") or [])+ windows_restarted = list(token.get("restarted_services") or [])+ service_profiles = token.get("service_profiles") or {}+ _extend_unique(outcome.restarted_services, windows_restarted)+ _extend_unique(outcome.relaunched_profiles, (p for p in (service_profiles.get(n) for n in windows_restarted) if p))+ _extend_unique(outcome.failed_or_stale_units, (str(service_profiles.get(n) or n) for n in (token.get("services") or [])))+ with suppress(Exception):+ from hermes_cli.update_receipt import record_gateway_restart+ record_gateway_restart(+ restarted_services=outcome.restarted_services,+ relaunched_profiles=outcome.relaunched_profiles,+ externally_supervised_profiles=outcome.externally_supervised_profiles,+ killed_pids=sorted(outcome.killed_pids),+ failed_units=outcome.failed_or_stale_units,+ incomplete=outcome.incomplete or bool(outcome.failed_or_stale_units),+ phase_error="; ".join(outcome.phase_errors) or None,+ )def _reap_and_rescan(message: str, pids, stop=None) -> list[tuple[int, str, str]]:@@ -1214,7 +1135,6 @@ def _reap_and_rescan(message: str, pids, stop=None) -> list[tuple[int, str, str]def _terminate_leftover_gateways(pids) -> None:"""Force-stop leftover gateways one by one; a failure is logged, never raised."""from gateway.status import get_process_start_time, terminate_pid-for _pid in pids:try:terminate_pid(int(_pid), force=True, expected_start_time=get_process_start_time(int(_pid)))@@ -1245,59 +1165,52 @@ def _clear_windows_venv_holders_or_exit(args, gateway_mode: bool, _windows_gatewrefused (the sync would corrupt against a locked .pyd)."""from hermes_cli.update_cmd import _m, _record_update_step, _refuse_gateway_ancestor_tree_kill- _venv_holders = _m()._detect_venv_python_processes()- if _venv_holders:- # Gateways the pause machinery owns (respawned in the pause->guard window or- # unmapped spawn path): stop and re-check; post-update resume brings them back.- _gateway_holders = _m()._leftover_pausable_gateway_pids(_venv_holders)- if _gateway_holders is not None:- if _refuse_gateway_ancestor_tree_kill(_gateway_holders, gateway_mode=gateway_mode):- _m()._resume_windows_gateways_after_update(_windows_gateway_resume)- sys.exit(2)- _venv_holders = _reap_and_rescan(- f" ⚠ {len(_gateway_holders)} gateway process(es) still hold the venv after the pause; stopping them",- _gateway_holders, stop=_terminate_leftover_gateways,- )- # Tree-reap rungs: (classifier, message). Ledger rung = positive identity in any context (self-registered- # backend, spawner provably dead; no PPID archaeology). Orphan rung = Desktop `serve` whose app is GONE- # (nothing respawns an orphan); live-Desktop backends return None and keep the refusal.++ def _resume_and_exit():+ _m()._resume_windows_gateways_after_update(_windows_gateway_resume)+ sys.exit(2)++ holders = _m()._detect_venv_python_processes()+ # Gateways the pause machinery owns (respawned in the pause->guard window or unmapped+ # spawn path): stop and re-check; post-update resume brings them back.+ if holders and (gateway_holders := _m()._leftover_pausable_gateway_pids(holders)) is not None:+ if _refuse_gateway_ancestor_tree_kill(gateway_holders, gateway_mode=gateway_mode):+ _resume_and_exit()+ holders = _reap_and_rescan(+ f" ⚠ {len(gateway_holders)} gateway process(es) still hold the venv after the pause; stopping them",+ gateway_holders, stop=_terminate_leftover_gateways,+ )+ # Tree-reap rungs. Ledger rung = positive identity in any context (self-registered backend, spawner+ # provably dead; no PPID archaeology). Orphan rung = Desktop `serve` whose app is GONE (nothing+ # respawns an orphan); live-Desktop backends return None and keep the refusal.for classifier, message in ((_m()._ledger_reapable_backend_pids, "ledger-identified orphaned Hermes backend process(es) hold the venv"),(_m()._orphaned_desktop_backend_pids, "orphaned Desktop backend process(es) still hold the venv"),):- if _venv_holders:- backends = classifier(_venv_holders)- if backends:- _venv_holders = _reap_and_rescan(f" ⚠ {len(backends)} {message}; stopping their trees", backends)- if _venv_holders:- # Manual serve/dashboard rung (e.g. `hermes serve --host <ip>` for a REMOTE Desktop):- # ledger identity only (spawner dead; Desktop-owned keep the refusal). Stop and- # register an idempotent atexit relaunch on the SAME host/port/profile — success or failure.- _serve_entries = _m()._ledger_manual_serve_holders(_venv_holders)- if _serve_entries:- def _stop_and_park(pids):- _m()._stop_process_trees(pids)- _record_update_step("serve_pause", True, f"stopped={len(_serve_entries)}")- import atexit as _serve_atexit-- _serve_atexit.register(_m()._relaunch_stopped_serves, {"pending": True, "entries": _serve_entries})-- _venv_holders = _reap_and_rescan(- f" ⚠ {len(_serve_entries)} manual serve/dashboard backend(s) hold the venv; stopping them for "- "the update (they will be relaunched on their recorded endpoints)",- [int(e["pid"]) for e in _serve_entries], stop=_stop_and_park,- )- if _venv_holders and _in_handoff_without_live_shim(args):- # Final rung: in a GUI hand-off the Desktop is contractually gone; surviving `serve`- # backends are leaks even with a live parent (which made the orphan-only rung bail- # and hang) — reap by cmdline.- _handoff_backends = _m()._handoff_reapable_backend_pids(_venv_holders)- if _handoff_backends:- _venv_holders = _reap_and_rescan(- f" ⚠ {len(_handoff_backends)} Hermes backend process(es) "- "still hold the venv after the Desktop hand-off; stopping their trees", _handoff_backends,- )- if _venv_holders:- print(_format_venv_python_holders_message(_venv_holders))- _m()._resume_windows_gateways_after_update(_windows_gateway_resume)- sys.exit(2)+ if holders and (backends := classifier(holders)):+ holders = _reap_and_rescan(f" ⚠ {len(backends)} {message}; stopping their trees", backends)+ # Manual serve/dashboard rung (e.g. `hermes serve --host <ip>` for a REMOTE Desktop): ledger identity+ # only (spawner dead; Desktop-owned keep the refusal). Stop and register an idempotent atexit relaunch+ # on the SAME host/port/profile — success or failure.+ if holders and (serve_entries := _m()._ledger_manual_serve_holders(holders)):+ def _stop_and_park(pids):+ _m()._stop_process_trees(pids)+ _record_update_step("serve_pause", True, f"stopped={len(serve_entries)}")+ import atexit as _serve_atexit+ _serve_atexit.register(_m()._relaunch_stopped_serves, {"pending": True, "entries": serve_entries})++ holders = _reap_and_rescan(+ f" ⚠ {len(serve_entries)} manual serve/dashboard backend(s) hold the venv; stopping them for "+ "the update (they will be relaunched on their recorded endpoints)",+ [int(e["pid"]) for e in serve_entries], stop=_stop_and_park,+ )+ # Final rung: in a GUI hand-off the Desktop is contractually gone; surviving `serve` backends are leaks+ # even with a live parent (which made the orphan-only rung bail and hang) — reap by cmdline.+ if holders and _in_handoff_without_live_shim(args) and (handoff_backends := _m()._handoff_reapable_backend_pids(holders)):+ holders = _reap_and_rescan(+ f" ⚠ {len(handoff_backends)} Hermes backend process(es) "+ "still hold the venv after the Desktop hand-off; stopping their trees", handoff_backends,+ )+ if holders:+ print(_format_venv_python_holders_message(holders))+ _resume_and_exit()