The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): stop reading gateway identity off the Windows restart watcher's argv (#107002) (#121635)
Austin Pickettfae9e5677a3e
diff --git a/gateway/status.py b/gateway/status.pyindex 91204957800..60c45293452 100644--- a/gateway/status.py+++ b/gateway/status.py@@ -528,6 +528,66 @@ def _read_process_cmdline(pid: int) -> Optional[str]:return None++def inline_source_flag_index(tokens: list[str]) -> int | None:+ """Index of the ``-c`` token when *tokens* is an interpreter running INLINE SOURCE, else None.++ Everything after ``-c`` is data the inline program receives, not this process's own identity.+ The detached gateway restart watcher (``gateway._spawn_gateway_restart_watcher``) is spawned as+ ``python -c <watcher source> <old_pid> <python> -m hermes_cli.main gateway run``: its trailing+ argv is the command the watcher will LATER spawn, so every argv matcher used to read it as a+ live gateway. See #107002 and the "never infer process identity from argv substrings" rule.++ Only interpreter options may precede ``-c``; the first non-option token ends the option block+ (``python -m hermes_cli.main …`` therefore never matches).++ The walk is VALUE-AWARE: ``-X``/``-W``/``-Q`` and ``--check-hash-based-pycs``/``--jit`` take a+ SEPARATE operand, so a naive "first non-option token ends the block" walk mistakes that operand+ for the end of the block and never reaches the ``-c`` behind it (``python -X utf8 -c <src> …``+ was still read as a live gateway). The operand sets are the canonical ones in+ ``hermes_state_holders``, not a second hand-rolled copy.++ *tokens* must be CASE-PRESERVING: the operand-taking ``-Q``/``-W``/``-X`` differ from the+ operand-less ``-q``/``-b``, so a lowercased argv would skip the token after a plain ``-q``.+ """+ from hermes_state_holders import (+ _PYTHON_LONG_OPTIONS_WITH_OPERANDS,+ _PYTHON_SHORT_OPTIONS_WITH_OPERANDS,+ )++ index = 1+ while index < len(tokens):+ token = tokens[index]+ if token == "--":+ return None+ if token in _PYTHON_LONG_OPTIONS_WITH_OPERANDS:+ index += 2 # the next token is this option's operand, not the end of the option block+ continue+ if token.startswith("--"):+ index += 1 # ``--opt=value`` and operand-less long options+ continue+ if not token.startswith("-") or token == "-":+ return None+ # Clustered short options (``-uc``, ``-IsB``). An operand-taking letter consumes the rest of+ # the cluster as its attached value, or the following token when the cluster ends there --+ # so ``-Xc`` is ``-X c``, NOT an inline-source ``-c``.+ cluster = token[1:]+ for position, letter in enumerate(cluster):+ if letter == "c":+ return index+ if letter in _PYTHON_SHORT_OPTIONS_WITH_OPERANDS:+ index += 1 if cluster[position + 1 :] else 2+ break+ else:+ index += 1+ return None+++def command_line_runs_inline_source(tokens: list[str]) -> bool:+ """True when *tokens* is an interpreter running INLINE SOURCE (``python -c <src> [args]``)."""+ return inline_source_flag_index(tokens) is not None++def _gateway_command_subcommand(command: str | None) -> str | None:"""Hermes gateway lifecycle subcommand from a command line, or None. No loose substring matches(``"gateway" in cmdline`` also matched ``gateway status`` / ``python -m tui_gateway``): needs a@@ -541,10 +601,16 @@ def _gateway_command_subcommand(command: str | None) -> str | None:except ValueError:raw_tokens = command.split()# Strip surrounding quotes, normalize slashes + case per token.- tokens = [t.strip("\"'").replace("\\", "/").lower() for t in raw_tokens]+ cased_tokens = [t.strip("\"'").replace("\\", "/") for t in raw_tokens]+ tokens = [t.lower() for t in cased_tokens]if not tokens:return Nonebasenames = [t.rsplit("/", 1)[-1] for t in tokens]+ # ``python -c <src> … -m hermes_cli.main gateway run``: the trailing argv belongs to the program+ # the inline source will spawn later, not to this process (#107002). Case-preserving tokens:+ # the operand-taking ``-X``/``-W``/``-Q`` must not be conflated with ``-q``/``-b``.+ if command_line_runs_inline_source(cased_tokens):+ return None# The launchd job's osascript wrapper (gateway_launchd.launchd_program_arguments) carries the gateway argv# inside one AppleScript string; the gateway itself is its child and is matched on its own command line.if basenames[0] == "osascript":@@ -582,6 +648,40 @@ def _gateway_command_subcommand(command: str | None) -> str | None:return None+def gateway_spawn_intent_subcommand(command: str | None) -> str | None:+ """Gateway lifecycle subcommand a command line would EVENTUALLY launch, or None.++ The identity matcher (``_gateway_command_subcommand``) deliberately refuses ``python -c <src>+ …``: the trailing argv is the inline program's data, not that process's own identity (#107002).+ Callers that inspect a command line as SPAWN INTENT — "if I launch this, does a gateway runtime+ eventually appear?" — need the opposite answer, because+ ``gateway._spawn_gateway_restart_watcher`` hides a real ``… -m hermes_cli.main gateway run``+ behind exactly that wrapper. ``tests/_fixtures/live_system_guard.py`` is the canonical caller.++ Still no substring matching: the wrapper is peeled token-wise and each remaining suffix is+ handed to the same canonical matcher.+ """+ direct = _gateway_command_subcommand(command)+ if direct is not None or not command:+ return direct+ try:+ raw_tokens = shlex.split(command, posix=False)+ except ValueError:+ raw_tokens = command.split()+ cased_tokens = [t.strip("\"'").replace("\\", "/") for t in raw_tokens]+ flag_index = inline_source_flag_index(cased_tokens)+ if flag_index is None:+ return None+ # Skip the interpreter, its options, ``-c`` and the source literal; then try every suffix —+ # the embedded argv starts at an unknown offset (the watcher prefixes it with the old PID).+ start = flag_index + 2+ for i in range(start, len(cased_tokens)):+ nested = _gateway_command_subcommand(" ".join(raw_tokens[i:]))+ if nested is not None:+ return nested+ return None++def looks_like_gateway_command_line(command: str | None) -> bool:"""True only for a real ``gateway run`` process command line."""return _gateway_command_subcommand(command) == "run"diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.pyindex 299b03ff3b3..a210a213de2 100644--- a/hermes_cli/gateway.py+++ b/hermes_cli/gateway.py@@ -977,6 +977,15 @@ def launch_detached_profile_gateway_restart(profile: str, old_pid: int) -> bool:)+GATEWAY_RESTART_WATCHER_TIMEOUT_S = 120+"""How long the detached restart watcher waits for the old PID to exit before giving up.++``hermes update``'s post-relaunch liveness check budgets against this: the watcher spawns the new+gateway only AFTER the old PID is gone, so a verification window shorter than this can expire+before the relaunch it is verifying has even started (#107002).+"""++def _restart_argv_is_host_gateway(argv: list[str]) -> bool:"""True when *argv* relaunches the host multiplexer, not a named profile's own gateway.@@ -1072,7 +1081,7 @@ def _spawn_gateway_restart_watcher(old_pid: int, run_argv: list[str], *, host: bcmd = sys.argv[2:]_respawn_cwd = {respawn_cwd_literal}_respawn_env_overlay = {respawn_env_literal}- deadline = time.monotonic() + 120+ deadline = time.monotonic() + {watcher_timeout_literal}while time.monotonic() < deadline:# ``os.kill(pid, 0)`` is not a no-op on Windows — use the cross-platform existence check.from gateway.status import _pid_exists@@ -1132,7 +1141,8 @@ def _spawn_gateway_restart_watcher(old_pid: int, run_argv: list[str], *, host: bexcept OSError:pass"""- ).strip().format(respawn_cwd_literal=json.dumps(respawn_cwd), respawn_env_literal=json.dumps(respawn_env_overlay))+ ).strip().format(respawn_cwd_literal=json.dumps(respawn_cwd), respawn_env_literal=json.dumps(respawn_env_overlay),+ watcher_timeout_literal=json.dumps(GATEWAY_RESTART_WATCHER_TIMEOUT_S))watcher_argv = [sys.executable, "-c", watcher, str(old_pid), *run_argv]devnull = {"stdout": subprocess.DEVNULL, "stderr": subprocess.DEVNULL}diff --git a/hermes_cli/update_cmd_windows.py b/hermes_cli/update_cmd_windows.pyindex d9481a4dfea..ef90b519a7d 100644--- a/hermes_cli/update_cmd_windows.py+++ b/hermes_cli/update_cmd_windows.py@@ -249,6 +249,11 @@ 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+ # ``python -c <src> … -m hermes_cli.main <subcommand>``: the entry token belongs to the argv the+ # inline source carries for a LATER spawn, not to this holder (#107002).+ from gateway.status import command_line_runs_inline_source+ if command_line_runs_inline_source([t.strip('"').replace("\\", "/") for t in tokens]):+ return Nonevalue_flags = _holder_value_flags()i = entry_idx + 1while i < len(tokens):@@ -1202,6 +1207,35 @@ def _relaunch_paused_gateways(token: dict, profiles: dict, unmapped: list) -> tureturn relaunched, unmapped_relaunched+_RELAUNCH_VERIFY_TIMEOUT_S = 30.0+++def _pending_relaunch_pids(profiles: dict, unmapped: list, pid_exists) -> list[int]:+ """Old PIDs a restart watcher is still waiting on, sorted; empty when every relaunch can have run.++ ``_spawn_gateway_restart_watcher`` respawns the gateway only once the PID it was handed is gone,+ so while any of them is alive the relaunch has provably not started yet. Pure function of data+ (``pid_exists`` is injected) so the decision is testable off Windows.+ """+ candidates = [int(pid) for pid in profiles.values()]+ candidates += [int(entry["pid"]) for entry in unmapped if entry.get("argv") and entry.get("pid")]+ return sorted({pid for pid in candidates if pid > 0 and pid_exists(pid)})+++def _relaunch_verify_timeout_s(profiles: dict, unmapped: list, pid_exists) -> float:+ """Liveness budget for the post-relaunch poll.++ The base window assumes the watchers respawn immediately. When an old PID is still alive the+ watcher is still in its wait loop, so the poll must reach at least the watcher's own deadline —+ otherwise ``hermes update`` declares "no stable gateway process appeared" for a gateway that was+ never scheduled to appear inside the window (#107002).+ """+ from hermes_cli.gateway import GATEWAY_RESTART_WATCHER_TIMEOUT_S+ if not _pending_relaunch_pids(profiles, unmapped, pid_exists):+ return _RELAUNCH_VERIFY_TIMEOUT_S+ return float(GATEWAY_RESTART_WATCHER_TIMEOUT_S) + _RELAUNCH_VERIFY_TIMEOUT_S++def _verify_relaunched_gateways_alive(token: dict, profiles: dict, unmapped: list) -> None:"""Gate success on the shared liveness poll: a truthy launch only proves the watcher was created.@@ -1209,8 +1243,10 @@ def _verify_relaunched_gateways_alive(token: dict, profiles: dict, unmapped: lis``all_profiles=True`` covers the fleet. Vouched PIDs are persisted so a death AFTER updater exitis reported by the next CLI invocation (best-effort)."""with _abort_on_error("Could not load Windows gateway liveness helpers"):+ from gateway.status import _pid_existsfrom hermes_cli import gateway_windows- ready_pids = gateway_windows._wait_for_gateway_ready(timeout_s=30.0, all_profiles=True)+ timeout_s = _relaunch_verify_timeout_s(profiles, unmapped, _pid_exists)+ ready_pids = gateway_windows._wait_for_gateway_ready(timeout_s=timeout_s, all_profiles=True)if not ready_pids:token["profiles"] = dict(profiles)token["unmapped"] = list(unmapped)diff --git a/tests/_fixtures/live_system_guard.py b/tests/_fixtures/live_system_guard.pyindex c4192ca7e29..7375f11cfe0 100644--- a/tests/_fixtures/live_system_guard.py+++ b/tests/_fixtures/live_system_guard.py@@ -334,14 +334,14 @@ def _live_system_guard(request, monkeypatch):# webhook port. 2026-09-03: 39 such orphans lived 6 days after a# sibling refactor moved the spawn seam and left tests patching the# facade. The canonical matcher, never an argv substring.- from gateway.status import _gateway_command_subcommand+ from gateway.status import gateway_spawn_intent_subcommand# A gateway launched INSIDE a container (`docker exec … hermes gateway start`) cannot# reach the host's systemd unit or webhook port; tests/docker/ exists to exercise it.in_container = _first_token_basename(cmd_str) in _CONTAINER_RUNTIMESif (not lookalike_okand not in_container- and _gateway_command_subcommand(cmd_str) in ("run", "start", "restart")+ and gateway_spawn_intent_subcommand(cmd_str) in ("run", "start", "restart")):raise RuntimeError(f"tests/conftest.py live-system guard: blocked "diff --git a/tests/gateway/test_control_socket_windows_live.py b/tests/gateway/test_control_socket_windows_live.pyindex e629e312a4e..e9e936d48c0 100644--- a/tests/gateway/test_control_socket_windows_live.py+++ b/tests/gateway/test_control_socket_windows_live.py@@ -30,6 +30,8 @@ from pathlib import Pathimport pytest+from tests.live_process_fixtures import sleeper_script_path+pytestmark = pytest.mark.platforms("windows") # live Windows named-pipe E2EPROJECT_ROOT = Path(__file__).resolve().parents[2]@@ -191,8 +193,10 @@ def test_pipe_gone_after_kill_falls_back(live_server, monkeypatch):standin = subprocess.Popen(# Use the real interpreter: a Windows venv's python.exe can be a shim- # whose PID differs from the process running the command line.- [getattr(sys, "_base_executable"), "-c", "import time; time.sleep(120)", "hermes", "gateway", "run"],+ # whose PID differs from the process running the command line. The+ # stand-in runs a SCRIPT, not `-c`: gateway identity is no longer+ # inferred from inline `-c` source (#107002).+ [getattr(sys, "_base_executable"), sleeper_script_path(), "hermes", "gateway", "run"],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,)diff --git a/tests/gateway/test_gateway_command_line_matcher.py b/tests/gateway/test_gateway_command_line_matcher.pyindex ddcae282a5f..79d7c67936b 100644--- a/tests/gateway/test_gateway_command_line_matcher.py+++ b/tests/gateway/test_gateway_command_line_matcher.py@@ -12,6 +12,7 @@ from __future__ import annotationsimport pytestfrom gateway.status import (+ gateway_spawn_intent_subcommand as spawn_intent,looks_like_gateway_command_line as matches,looks_like_gateway_runtime_command_line as matches_runtime,)@@ -58,6 +59,97 @@ def test_accepts_real_gateway_run(cmd):assert matches(cmd) is True[email protected]("cmd", REJECT)+def test_rejects_non_gateway_run(cmd):+ assert matches(cmd) is False+++# ``python -c <src> <old_pid> <gateway argv…>`` — the detached restart watcher+# (hermes_cli.gateway._spawn_gateway_restart_watcher). Its trailing argv is the command it will+# spawn LATER, so reading identity off it made the updater's post-relaunch liveness poll vouch for+# the watcher instead of a gateway (#107002).+INLINE_SOURCE_REJECT = [+ 'python -c "import time; time.sleep(1)" 14980 python -m hermes_cli.main gateway run',+ r'"C:\Users\me\hermes\venv\Scripts\python.exe" -c "import os" 14980 '+ r'"C:\Users\me\hermes\venv\Scripts\python.exe" -m hermes_cli.main gateway run',+ 'python -u -c "import os" 14980 python -m hermes_cli.main --profile work gateway run',+ 'python -uc "import os" 14980 hermes gateway run',+ # Options that take a SEPARATE operand must not end the option walk before ``-c`` (the operand+ # is not the start of the program's own argv). The repo itself spawns ``-I -S -B -X utf8 …``+ # (hermes_cli/_old_updater.py, _update_takeover.py), so this shape is not hypothetical.+ 'python -X utf8 -c "import os" 14980 python -m hermes_cli.main gateway run',+ 'python -W ignore -c "import os" 14980 python -m hermes_cli.main gateway run',+ 'python --check-hash-based-pycs always -c "import os" 14980 hermes gateway run',+ 'python -I -S -B -X utf8 -c "import os" 14980 python -m hermes_cli.main gateway run',+ # ``-q`` (quiet) takes NO operand, unlike ``-Q``; a case-folded walk would skip past the ``-c``.+ 'python -q -c "import os" 14980 python -m hermes_cli.main gateway run',+]+++# Real gateways whose interpreter carries operand-taking options must STILL be recognised — the+# value-aware walk must not over-reject. Mirror image of INLINE_SOURCE_REJECT.+INTERPRETER_OPTION_ACCEPT = [+ "python -X utf8 -m hermes_cli.main gateway run",+ "python -W ignore -m hermes_cli.main gateway run",+ "python -q -m hermes_cli.main gateway run",+ "python -I -S -B -X utf8 -m hermes_cli.main gateway run",+ "python --check-hash-based-pycs always -m hermes_cli.main gateway run",+]++[email protected]("cmd", INTERPRETER_OPTION_ACCEPT)+def test_accepts_gateway_behind_operand_taking_interpreter_options(cmd):+ assert matches(cmd) is True+++# The repo's own non-gateway ``-X utf8`` spawn shapes must stay unmatched.+ "cmd",+ [+ "python -I -S -B -X utf8 /tmp/update_takeover.py",+ "python -X utf8 -E script.py",+ ],+)+def test_operand_taking_options_do_not_manufacture_a_gateway(cmd):+ assert matches(cmd) is False++[email protected]("cmd", INLINE_SOURCE_REJECT)+def test_rejects_interpreter_running_inline_source(cmd):+ assert matches(cmd) is False+ assert matches_runtime(cmd) is False+++# Spawn INTENT is the mirror image of process identity: the same wrapper that must not be read as a+# live gateway MUST still be recognised as "launching this eventually produces a gateway runtime".+# tests/_fixtures/live_system_guard.py relies on it — without this, the autouse guard stopped+# blocking the detached restart watcher and real gateways leaked out of the test run.[email protected]("cmd", INLINE_SOURCE_REJECT)+def test_spawn_intent_sees_through_the_inline_source_wrapper(cmd):+ assert spawn_intent(cmd) == "run"++[email protected]("cmd", ACCEPT)+def test_spawn_intent_matches_plain_gateway_run(cmd):+ assert spawn_intent(cmd) == "run"++[email protected]("cmd", REJECT)+def test_spawn_intent_rejects_non_gateway_commands(cmd):+ assert spawn_intent(cmd) != "run"+++def test_spawn_intent_keeps_read_only_subcommands_spawnable():+ """The guard only blocks run/start/restart; a ``-c``-wrapped ``gateway status`` must stay+ launchable (tests/test_live_system_guard_self_test.py asserts it passes through)."""+ cmd = 'python -c "import sys; print(sys.argv[1:])" -m hermes_cli.main gateway status'+ assert spawn_intent(cmd) == "status"+++def test_spawn_intent_ignores_inline_source_without_a_gateway_argv():+ assert spawn_intent('python -c "import time; time.sleep(1)" 14980') is None++# Atomic Hermes' bundled desktop runner (regression for #22418): it shares# HERMES_HOME with the CLI and must be recognised as a gateway so# ``gateway run --replace`` enters the replace/lock-handoff path instead ofdiff --git a/tests/hermes_cli/test_desktop_lifecycle_windows_live.py b/tests/hermes_cli/test_desktop_lifecycle_windows_live.pyindex 4f08c6855f0..020c1f19129 100644--- a/tests/hermes_cli/test_desktop_lifecycle_windows_live.py+++ b/tests/hermes_cli/test_desktop_lifecycle_windows_live.py@@ -26,6 +26,8 @@ from pathlib import Pathimport pytest+from tests.live_process_fixtures import SLEEPER_MARKER, sleeper_script_path+pytestmark = pytest.mark.platforms("windows")PROJECT_ROOT = Path(__file__).resolve().parents[2]@@ -56,12 +58,12 @@ def sleeper():def _spawn(*tail: str) -> subprocess.Popen:p = subprocess.Popen(- [sys.executable, "-c", "import time; time.sleep(120)", *tail],+ [sys.executable, sleeper_script_path(), *tail],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,)procs.append(p)- assert _wait_until(lambda: _argv_visible(p.pid, "time.sleep(120)")), "sleeper argv never visible"+ assert _wait_until(lambda: _argv_visible(p.pid, SLEEPER_MARKER)), "sleeper argv never visible"return pyield _spawndiff --git a/tests/hermes_cli/test_plan_reconciliation_windows_live.py b/tests/hermes_cli/test_plan_reconciliation_windows_live.pyindex 51ff4bcc136..13ed7b283c3 100644--- a/tests/hermes_cli/test_plan_reconciliation_windows_live.py+++ b/tests/hermes_cli/test_plan_reconciliation_windows_live.py@@ -21,6 +21,8 @@ sys.path.insert(0, str(WORKTREE))import pytest+from tests.live_process_fixtures import SLEEPER_MARKER, sleeper_script_path+# The stand-in wears a `gateway run` argv; the test spawns and reaps it itself.pytestmark = [pytest.mark.platforms("windows"), pytest.mark.spawns_gateway_lookalike]@@ -54,16 +56,16 @@ def test_plan_reconciliation_live_windows(tmp_path, monkeypatch):# which requires a live `gateway run` command line (#109680), so the# stand-in wears one; a bare sleeper is recorded too and must NOT count.child = subprocess.Popen(- [sys.executable, "-c", "import time; time.sleep(120)", "hermes", "gateway", "run"],+ [sys.executable, sleeper_script_path(), "hermes", "gateway", "run"],stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,)foreign = subprocess.Popen(- [sys.executable, "-c", "import time; time.sleep(120)"],+ [sys.executable, sleeper_script_path()],stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,)try:assert _wait_until(lambda: _argv_visible(child.pid, "gateway")), "stand-in argv never visible"- assert _wait_until(lambda: _argv_visible(foreign.pid, "time.sleep(120)")), "sleeper never visible"+ assert _wait_until(lambda: _argv_visible(foreign.pid, SLEEPER_MARKER)), "sleeper never visible"import psutildiff --git a/tests/hermes_cli/test_stderr_timestamp.py b/tests/hermes_cli/test_stderr_timestamp.pyindex b938a60c045..37f233ea21c 100644--- a/tests/hermes_cli/test_stderr_timestamp.py+++ b/tests/hermes_cli/test_stderr_timestamp.py@@ -17,6 +17,21 @@ from gateway.restart import ()from hermes_cli import stderr_timestamp++def _script(tmp_path, name: str, source: str) -> str:+ """Write *source* to a real script file and return its path.++ Gateway-lookalike children must run from a FILE, never ``python -c <src> <tail>``: a ``-c``+ command line is an interpreter running inline source, and the identity matchers deliberately+ refuse to read the trailing argv off one — that tail belongs to a program the inline source+ may spawn LATER, which is how the post-update restart watcher was mistaken for a live+ gateway (#107002).+ """+ path = tmp_path / name+ path.write_text(source, encoding="utf-8")+ return str(path)++_STALE_GATEWAY_ARGV = [sys.executable,"-m",@@ -119,8 +134,10 @@ def test_main_forwards_launchd_label_to_child_only_under_launchd(tmp_path, monkeassert marker_path.read_text(encoding="utf-8") == expected-# The child is ``python -c <record argv>`` carrying a "gateway run" tail as inert data, which is-# exactly what the guard's real-gateway spawn check matches; it exits at once.+# The child is a SCRIPT carrying a "gateway run" tail, which is what the guard's real-gateway+# spawn check matches; it exits at once. Not ``python -c <src> <tail>``: a ``-c`` command line is+# an interpreter running inline source, and the identity matchers refuse to read the trailing argv+# off one — that tail belongs to a program the inline source may spawn LATER (#107002).@pytest.mark.spawns_gateway_lookalikedef test_main_injects_flag_into_stale_gateway_child(tmp_path, monkeypatch):"""Stale plist inner argv must grow --external-supervisor in the grandchild."""@@ -128,13 +145,15 @@ def test_main_injects_flag_into_stale_gateway_child(tmp_path, monkeypatch):monkeypatch.delenv(EXTERNAL_GATEWAY_SUPERVISOR_ENV, raising=False)log_path = tmp_path / "gateway.error.log"marker_path = tmp_path / "argv.txt"- code = (+ script = _script(+ tmp_path,+ "record_argv.py","import sys\n"- f"from pathlib import Path\n"+ "from pathlib import Path\n"f"Path({str(marker_path)!r}).write_text("- "'\\n'.join(sys.argv[1:]), encoding='utf-8')\n"+ "'\\n'.join(sys.argv[1:]), encoding='utf-8')\n",)- stale = [sys.executable, "-c", code, "-m", "hermes_cli.main", "gateway", "run", "--replace"]+ stale = [sys.executable, script, "-m", "hermes_cli.main", "gateway", "run", "--replace"]rc = stderr_timestamp.main(["--error-log", str(log_path), "--", *stale]@@ -208,6 +227,8 @@ def test_main_maps_gateway_ex_config_to_clean_stop(tmp_path):please-restart code (75) or a non-gateway child's 78."""log_path = tmp_path / "gateway.error.log"gateway_tail = ["-m", "hermes_cli.main", "gateway", "run"]+ exit_config = _script(tmp_path, "exit_config.py", f"raise SystemExit({GATEWAY_FATAL_CONFIG_EXIT_CODE})\n")+ exit_restart = _script(tmp_path, "exit_restart.py", f"raise SystemExit({GATEWAY_SERVICE_RESTART_EXIT_CODE})\n")rc_config = stderr_timestamp.main([@@ -215,8 +236,7 @@ def test_main_maps_gateway_ex_config_to_clean_stop(tmp_path):str(log_path),"--",sys.executable,- "-c",- f"raise SystemExit({GATEWAY_FATAL_CONFIG_EXIT_CODE})",+ exit_config,*gateway_tail,])@@ -226,8 +246,7 @@ def test_main_maps_gateway_ex_config_to_clean_stop(tmp_path):str(log_path),"--",sys.executable,- "-c",- f"raise SystemExit({GATEWAY_SERVICE_RESTART_EXIT_CODE})",+ exit_restart,*gateway_tail,])@@ -237,8 +256,7 @@ def test_main_maps_gateway_ex_config_to_clean_stop(tmp_path):str(log_path),"--",sys.executable,- "-c",- f"raise SystemExit({GATEWAY_FATAL_CONFIG_EXIT_CODE})",+ exit_config,])diff --git a/tests/hermes_cli/test_venv_holder_windows_live.py b/tests/hermes_cli/test_venv_holder_windows_live.pyindex bf056ef0687..e9a3ee792d2 100644--- a/tests/hermes_cli/test_venv_holder_windows_live.py+++ b/tests/hermes_cli/test_venv_holder_windows_live.py@@ -20,11 +20,14 @@ from __future__ import annotationsimport osimport subprocessimport sys+import tempfileimport timefrom pathlib import Pathimport pytest+from tests.live_process_fixtures import sleeper_script_path+pytestmark = [pytest.mark.platforms("windows"),# ``_spawn`` sleepers carry a "gateway run" argv tail as inert data (the guard's real-gateway@@ -38,12 +41,12 @@ PROJECT_ROOT = Path(__file__).resolve().parents[2]def _spawn(args: list[str], cwd: Path | None = None, python: str | None = None) -> subprocess.Popen:"""Spawn a real sleeper process whose argv carries the given tail.- ``python -c "sleep" <tail...>`` — the tail is inert data to the child+ ``python <sleeper.py> <tail...>`` — the tail is inert data to the childbut fully visible to psutil cmdline scans, which is what the detectioncode classifies on."""proc = subprocess.Popen(- [python or sys.executable, "-c", "import time; time.sleep(300)", *args],+ [python or sys.executable, sleeper_script_path(), *args],cwd=str(cwd or PROJECT_ROOT),stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,@@ -91,8 +94,7 @@ class TestDetection:lives in the checkout's ``.venv``, which ``project_venv_dir`` resolves since7a94b1fbf77, so a ``sys.executable`` child IS a venv holder by design. The baseinterpreter the venv was created from is the foreign python."""- import tempfile-+from hermes_constants import project_venv_dirbase = getattr(sys, "_base_executable", None) or sys.executable@@ -156,20 +158,24 @@ class TestAncestorExclusion:" 'pids': [p for p, _, _ in matches]}))\n",encoding="utf-8",)- parent_oneliner = (- "import subprocess, sys;"- f" r = subprocess.run([sys.executable, {str(child_file)!r}],"- f" capture_output=True, text=True, cwd={str(PROJECT_ROOT)!r});"- " print(r.stdout.strip());"- " sys.stderr.write(r.stderr[-500:])"+ # The parent's code lives in a FILE too: a ``python -c <src>`` command line is an+ # interpreter running inline source and carries no readable Hermes identity (#107002),+ # so a ``-c`` parent would not be a gateway to any classifier.+ parent_file = tmp_path / "parent_gateway.py"+ parent_file.write_text(+ "import subprocess, sys\n"+ f"r = subprocess.run([sys.executable, {str(child_file)!r}],\n"+ f" capture_output=True, text=True, cwd={str(PROJECT_ROOT)!r})\n"+ "print(r.stdout.strip())\n"+ "sys.stderr.write(r.stderr[-500:])\n",+ encoding="utf-8",)# The parent's argv carries `gateway run` so it IS a gateway to any# cmdline classifier; it runs the child synchronously.result = subprocess.run([sys.executable,- "-c",- parent_oneliner,+ str(parent_file),"-m","hermes_cli.main","gateway",diff --git a/tests/hermes_cli/test_windows_relaunch_verify_budget.py b/tests/hermes_cli/test_windows_relaunch_verify_budget.pynew file mode 100644index 00000000000..21fafb9e54d--- /dev/null+++ b/tests/hermes_cli/test_windows_relaunch_verify_budget.py@@ -0,0 +1,75 @@+"""Post-update gateway relaunch verification: watcher identity and liveness budget (#107002).++Two invariants, both host-independent (the platform enters as DATA, never by faking ``sys.platform``):++1. The detached restart watcher ``hermes_cli.gateway._spawn_gateway_restart_watcher`` actually+ spawns must not be classified as a running gateway. Its argv carries the gateway command it+ will spawn LATER, so an argv-substring identity read vouches for the watcher itself.+2. ``hermes update``'s post-relaunch liveness poll must not expire before the watchers it is+ verifying are even scheduled to respawn.+"""++from __future__ import annotations++import pytest++from gateway.status import (+ _gateway_command_subcommand, looks_like_gateway_command_line, looks_like_gateway_runtime_command_line,+)+from hermes_cli import gateway as gateway_mod+from hermes_cli.gateway import GATEWAY_RESTART_WATCHER_TIMEOUT_S+from hermes_cli.update_cmd_windows import (+ _hermes_holder_subcommand, _pending_relaunch_pids, _relaunch_verify_timeout_s,+)+++def _spawned_watcher_cmdline(monkeypatch) -> str:+ """The real watcher command line, captured from a stubbed ``Popen`` (nothing is started)."""+ captured: list[list[str]] = []++ def fake_popen(argv, **_kwargs):+ captured.append(list(argv))+ return object()++ monkeypatch.setattr(gateway_mod.subprocess, "Popen", fake_popen)+ assert gateway_mod.launch_detached_gateway_restart_by_cmdline(+ 14980, ["python", "-m", "hermes_cli.main", "gateway", "run"]+ )+ return " ".join(captured[0])+++def test_spawned_restart_watcher_is_not_identified_as_a_gateway(monkeypatch):+ cmdline = _spawned_watcher_cmdline(monkeypatch)+ # The watcher really does carry the gateway argv — that is what made this bite.+ assert "hermes_cli.main gateway run" in cmdline+ # No Hermes subcommand at all may be read off it — not even a wrong one (the watcher source+ # text tokenizes into whatever words it happens to contain).+ assert _gateway_command_subcommand(cmdline) is None+ assert looks_like_gateway_command_line(cmdline) is False+ assert looks_like_gateway_runtime_command_line(cmdline) is False+ assert _hermes_holder_subcommand(cmdline) is None+++ "profiles, unmapped, alive, expected",+ [+ ({}, [], set(), []),+ ({"default": 14980}, [], set(), []),+ ({"default": 14980}, [], {14980}, [14980]),+ # An unmapped entry without captured argv was never handed to a watcher.+ ({}, [{"pid": 4242, "argv": None}], {4242}, []),+ ({"default": 14980}, [{"pid": 4242, "argv": ["python"]}], {14980, 4242}, [4242, 14980]),+ ],+)+def test_pending_relaunch_pids(profiles, unmapped, alive, expected):+ assert _pending_relaunch_pids(profiles, unmapped, alive.__contains__) == expected+++def test_verify_budget_covers_the_watchers_own_wait_when_the_old_pid_is_still_alive():+ profiles = {"default": 14980}+ settled = _relaunch_verify_timeout_s(profiles, [], lambda _pid: False)+ pending = _relaunch_verify_timeout_s(profiles, [], lambda _pid: True)+ # A watcher only respawns once its PID is gone: verifying for less than its own deadline+ # reports "no stable gateway process appeared" before the relaunch could have happened.+ assert pending > GATEWAY_RESTART_WATCHER_TIMEOUT_S+ assert settled < pendingdiff --git a/tests/live_process_fixtures.py b/tests/live_process_fixtures.pynew file mode 100644index 00000000000..5f8354e9521--- /dev/null+++ b/tests/live_process_fixtures.py@@ -0,0 +1,35 @@+"""Sleeper script used by the live process-topology E2Es to stand in for real Hermes processes.++The fixtures spawn ``python <sleeper.py> <argv tail...>``: the tail is inert to the child but+fully visible to psutil / ``Win32_Process`` cmdline scans, which is what the detection and+classification code reads.++It must NOT be ``python -c "import time; time.sleep(...)" <tail>``. A ``-c`` command line is an+interpreter running inline source, and the identity matchers deliberately refuse to read the+trailing argv off one — that tail belongs to a program the inline source may spawn LATER, which is+how the post-update gateway restart watcher was mistaken for a live gateway (#107002). A ``-c``+fixture therefore no longer stands in for anything.+"""++from __future__ import annotations++import tempfile+from pathlib import Path++_SLEEPER_SOURCE = "import time\ntime.sleep(300)\n"+_sleeper_script: Path | None = None++#: Substring a caller can wait for in the spawned process's *command line* to know the argv is+#: visible to a cmdline scan. It must name the SCRIPT, not its source text: the source now lives in+#: a file and never appears in the command line the way a ``-c`` snippet used to.+SLEEPER_MARKER = "sleeper.py"+++def sleeper_script_path() -> str:+ """Path to the sleeper script, created once per test session."""+ global _sleeper_script+ if _sleeper_script is None:+ path = Path(tempfile.mkdtemp(prefix="hermes-live-sleeper-")) / "sleeper.py"+ path.write_text(_SLEEPER_SOURCE, encoding="utf-8")+ _sleeper_script = path+ return str(_sleeper_script)diff --git a/tests/test_live_system_guard_self_test.py b/tests/test_live_system_guard_self_test.pyindex d2ff7fb400b..468326d4cd4 100644--- a/tests/test_live_system_guard_self_test.py+++ b/tests/test_live_system_guard_self_test.py@@ -297,6 +297,19 @@ def test_subprocess_popen_real_gateway_restart_blocked():)+def test_subprocess_popen_inline_source_restart_watcher_blocked():+ """``gateway._spawn_gateway_restart_watcher`` hides the real gateway argv behind+ ``python -c <src> <old_pid> …``. The identity matcher must ignore that trailing argv (#107002),+ but the guard reads it as SPAWN INTENT — otherwise the watcher sails through, waits out its+ 120s deadline and leaves a real detached gateway squatting the webhook port."""+ with pytest.raises(RuntimeError, match="live-system guard"):+ subprocess.Popen(+ [sys.executable, "-c", "import time; time.sleep(1)", "4242",+ sys.executable, "-m", "hermes_cli.main", "gateway", "run"],+ start_new_session=True,+ )++def test_subprocess_run_gateway_status_passes_through():"""Only lifecycle verbs are blocked: ``gateway status`` (and every otherread-only subcommand) must still spawn — via the canonical matcher, not an