Skip to content

The agent that grows with you

test: keep the live-system guard from letting tests restart a real hermes-dashboard

unsupportedpastelsfca14bc283a1
diff --git a/tests/_fixtures/live_system_guard.py b/tests/_fixtures/live_system_guard.py
index 7293a7d27ac..18fb5ac1d19 100644
--- a/tests/_fixtures/live_system_guard.py
+++ b/tests/_fixtures/live_system_guard.py
@@ -1,4 +1,4 @@
-"""The autouse live-system guard: no real kills, systemctl writes, gateway spawns or checkout writes.
+"""The autouse live-system guard: no real kills, Hermes-unit systemctl writes, gateway spawns or checkout writes.
Imported into ``tests/conftest.py`` so pytest registers the fixture there;
``pytest_plugins`` is not an option because ``tests/conftest.py`` is not the
@@ -29,9 +29,11 @@ PROJECT_ROOT = Path(__file__).parent.parent.parent
# a hard ``RuntimeError`` so the offending test gets a stack trace
# instead of silently murdering the real gateway.
# • ``subprocess.run`` / ``subprocess.Popen`` / ``call`` / ``check_call`` /
-# ``check_output`` reject any ``systemctl ... <verb> hermes-gateway``
-# invocation that would mutate the live unit. Read-only systemctl
-# calls (``status``, ``show``, ``list-units``) still pass through.
+# ``check_output`` reject any ``systemctl ... <verb> <unit>`` invocation
+# that would mutate ANY live Hermes unit — ``hermes-gateway[-<profile>]``,
+# ``hermes-dashboard[-<profile>]``, ``hermes-serve[-<profile>]`` and every
+# other ``hermes``/``hermes-*`` unit. Read-only systemctl calls
+# (``status``, ``show``, ``list-units``, ``is-active``) still pass through.
#
# We intentionally do NOT stub ``find_gateway_pids`` / ``_scan_gateway_pids``
# here — tests of those functions themselves need the real implementation.
@@ -63,8 +65,10 @@ def _live_system_guard(request, monkeypatch):
• os.system / os.popen
• pty.spawn
• asyncio.create_subprocess_exec / create_subprocess_shell
+ A mutating systemctl verb is refused against every Hermes unit
+ (``hermes``/``hermes-*``: gateway, dashboard, serve, any profile).
Subprocess inspection looks at the WHOLE command string (not just
- tokens[0]), so ``bash -c "systemctl restart hermes-gateway"``,
+ tokens[0]), so ``bash -c "systemctl restart hermes-dashboard"``,
``sudo systemctl ...``, ``env systemctl ...``, ``setsid systemctl ...``
are all caught. ``pkill``/``killall``/``taskkill`` invocations
targeting hermes/python patterns are also blocked. Bare ``git``
@@ -76,6 +80,7 @@ def _live_system_guard(request, monkeypatch):
return
import os as _os
+ import re as _re
import shlex as _shlex
import subprocess as _subprocess
@@ -218,17 +223,28 @@ def _live_system_guard(request, monkeypatch):
low = cmd_str.lower()
return any(tok in low for tok in _HERMES_TOKENS)
+ def _shell_words(cmd_str: str) -> list[str]:
+ # Split on whitespace AND quoting/shell punctuation so a unit or verb
+ # inside ``bash -c "systemctl restart hermes-dashboard"`` is still a word.
+ return [w for w in _re.split(r"[\s'\"`;&|()<>]+", cmd_str) if w]
+
+ def _is_hermes_unit(word: str) -> bool:
+ # ``hermes`` / ``hermes-<anything>`` once any path and unit suffix are
+ # stripped: hermes-gateway[-<profile>], hermes-dashboard[-<profile>],
+ # hermes-serve[-<profile>], ... — never ``myhermes-dashboard`` or ``nginx``.
+ name = word.rsplit("/", 1)[-1].lower()
+ for suffix in (".service", ".timer", ".socket"):
+ name = name.removesuffix(suffix)
+ return name == "hermes" or name.startswith("hermes-")
+
def _is_blocked_systemctl(cmd) -> bool:
cmd_str = _cmd_to_string(cmd)
if "systemctl" not in cmd_str:
return False
- if not _matches_hermes_gateway(cmd_str):
+ words = _shell_words(cmd_str)
+ if not (_matches_hermes_gateway(cmd_str) or any(_is_hermes_unit(w) for w in words)):
return False
- try:
- tokens = _shlex.split(cmd_str)
- except ValueError:
- tokens = cmd_str.split()
- return any(verb in tokens for verb in _MUTATING_VERBS)
+ return any(verb in words for verb in _MUTATING_VERBS)
def _is_process_killer(cmd) -> bool:
cmd_str = _cmd_to_string(cmd)
@@ -312,8 +328,9 @@ def _live_system_guard(request, monkeypatch):
if _is_blocked_systemctl(cmd):
raise RuntimeError(
f"tests/conftest.py live-system guard: blocked "
- f"subprocess.{name}({cmd!r}) — would mutate the "
- "live hermes-gateway systemd unit. Mock "
+ f"subprocess.{name}({cmd!r}) — would mutate a live "
+ "Hermes systemd unit (hermes-gateway*, hermes-dashboard*, "
+ "hermes-serve*, ...). Mock "
"subprocess.run / _run_systemctl in the test, or "
"mark with @pytest.mark.live_system_guard_bypass."
)
diff --git a/tests/hermes_cli/test_update_serve_generation_recovery.py b/tests/hermes_cli/test_update_serve_generation_recovery.py
index ef99c8c0e1e..fb491f779e1 100644
--- a/tests/hermes_cli/test_update_serve_generation_recovery.py
+++ b/tests/hermes_cli/test_update_serve_generation_recovery.py
@@ -20,6 +20,7 @@ from __future__ import annotations
import io
import json
+import os
import subprocess
import sys
from types import SimpleNamespace
@@ -875,8 +876,58 @@ def test_no_survivors_prints_nothing(capsys):
# ---------------------------------------------------------------------------
-def test_recovery_module_reports_serve_units_in_a_real_process():
+def _fake_systemctl_path(tmp_path):
+ """A ``PATH`` whose first ``systemctl`` is a recording fake, plus its argv log.
+
+ The child interpreter is outside the in-process live-system guard and resolves
+ ``systemctl`` through ``shutil.which``; without this it restarted the developer's
+ real hermes-serve / hermes-dashboard units. The fake lists one active user-scope
+ ``hermes-serve.service`` whose ``MainPID`` changes once it is restarted.
+ """
+ bin_dir = tmp_path / "bin"
+ bin_dir.mkdir()
+ log = tmp_path / "systemctl.log"
+ marker = tmp_path / "restarted"
+ fake = bin_dir / "systemctl"
+ fake.write_text(
+ "#!/bin/sh\n"
+ f"printf '%s\\n' \"$*\" >> '{log}'\n"
+ 'case " $* " in\n'
+ ' *" --user list-units hermes-serve* "*) echo "hermes-serve.service loaded active running Hermes" ;;\n'
+ ' *" is-active "*) echo active ;;\n'
+ f" *\" show \"*) if [ -e '{marker}' ]; then echo 200; else echo 100; fi ;;\n"
+ f" *\" restart \"*) : > '{marker}' ;;\n"
+ "esac\n"
+ )
+ fake.chmod(0o755)
+ return f"{bin_dir}{os.pathsep}{os.environ.get('PATH', '')}", log
+
+
+def test_recovery_module_reports_serve_units_in_a_real_process(tmp_path):
"""The protocol survives a genuine subprocess round-trip."""
+ path, log = _fake_systemctl_path(tmp_path)
+ result = subprocess.run(
+ [sys.executable, "-m", "hermes_cli.update_restart_recovery", "--stdin"],
+ input=json.dumps(
+ {"profiles": [], "serve_units": {"recover": True, "skip": []}}
+ ),
+ capture_output=True,
+ text=True,
+ check=False,
+ timeout=120,
+ env={**os.environ, "PATH": path},
+ )
+ assert result.returncode == 0, result.stderr
+ payload = json.loads(result.stdout)
+ assert payload["serve_units"] == {"verified": ["user/hermes-serve"], "failed": []}
+ restarts = [line for line in log.read_text().splitlines() if " restart " in f" {line} "]
+ assert restarts == ["--user --no-ask-password restart hermes-serve.service"]
+
+
[email protected]("not linux")
+def test_recovery_module_reports_empty_serve_coverage_off_linux_in_a_real_process():
+ """Off Linux there is no systemd serve pass, but the protocol still round-trips."""
result = subprocess.run(
[sys.executable, "-m", "hermes_cli.update_restart_recovery", "--stdin"],
input=json.dumps(
@@ -889,7 +940,7 @@ def test_recovery_module_reports_serve_units_in_a_real_process():
)
assert result.returncode == 0, result.stderr
payload = json.loads(result.stdout)
- assert set(payload["serve_units"]) == {"verified", "failed"}
+ assert payload["serve_units"] == {"verified": [], "failed": []}
# ---------------------------------------------------------------------------
diff --git a/tests/hermes_cli/test_update_stale_dashboard.py b/tests/hermes_cli/test_update_stale_dashboard.py
index 0d8118c574f..0e9c510dccf 100644
--- a/tests/hermes_cli/test_update_stale_dashboard.py
+++ b/tests/hermes_cli/test_update_stale_dashboard.py
@@ -110,13 +110,22 @@ def test_update_cleanup_spares_backend_owned_by_valid_ssh_lock(tmp_path, monkeyp
assert pid in exclude_pids
return []
- with patch(
+ # ``restart_managed`` first probes for a managed hermes-dashboard unit; unstubbed, that
+ # probe found the developer's real unit and restarted it.
+ calls: list[list[str]] = []
+
+ def fake_run(args, *a, **kw):
+ calls.append(list(args))
+ return MagicMock(returncode=0, stdout="", stderr="")
+
+ with patch("subprocess.run", side_effect=fake_run), patch(
"hermes_cli.main_dashboard._find_stale_dashboard_pids",
side_effect=assert_owned_pid_is_excluded,
):
result = _kill_stale_dashboard_processes(restart_managed=True)
assert result == {"matched": [], "killed": [], "failed": []}
+ assert calls and all(call[:1] == ["systemctl"] and "list-unit-files" in call for call in calls)
def test_explicit_stop_does_not_spare_backend_owned_by_valid_ssh_lock(
diff --git a/tests/test_live_system_guard_self_test.py b/tests/test_live_system_guard_self_test.py
index 490c9b78cd0..fcc1b638d63 100644
--- a/tests/test_live_system_guard_self_test.py
+++ b/tests/test_live_system_guard_self_test.py
@@ -5,7 +5,9 @@ tests fail. If anyone adds a NEW kill primitive to the codebase without
adding it to the guard, the corresponding test added here will fail too.
The guard exists to protect the developer's live ``hermes-gateway`` process
-from being SIGTERMed by tests. See PR #23397 for the original incident
+from being SIGTERMed by tests, and every live Hermes systemd unit
+(``hermes-gateway*``, ``hermes-dashboard*``, ``hermes-serve*``) from being
+restarted or stopped by them. See PR #23397 for the original incident
(5+ live gateway kills in 3 days). Per Teknium 2026-05-10:
> "You better do such a deep scan and scrub of the tests that this
@@ -151,6 +153,42 @@ def test_subprocess_run_bash_c_systemctl_blocked():
+ "cmd",
+ [
+ ["systemctl", "--user", "restart", "hermes-dashboard.service"],
+ ["systemctl", "--user", "restart", "hermes-dashboard-work.service"],
+ ["systemctl", "--user", "stop", "hermes-serve"],
+ ["/usr/bin/systemctl", "--user", "--no-ask-password", "restart", "hermes-serve-work.service"],
+ ["bash", "-c", "systemctl --user restart hermes-dashboard.service"],
+ "systemctl --user restart hermes-dashboard-work.service",
+ 'bash -c "systemctl --user restart hermes-serve.service"',
+ ],
+)
+def test_subprocess_run_systemctl_mutating_any_hermes_unit_blocked(cmd):
+ """Not just the gateway: a test that forgot to stub the runner restarted the developer's
+ real hermes-dashboard / hermes-serve units, which the gateway-only tokens let through."""
+ with pytest.raises(RuntimeError, match="live-system guard"):
+ subprocess.run(cmd, shell=isinstance(cmd, str), check=False)
+
+
+ "cmd",
+ [
+ ["systemctl", "--user", "show", "hermes-dashboard.service", "--property=MainPID"],
+ ["systemctl", "--user", "status", "hermes-dashboard"],
+ ["systemctl", "--user", "is-active", "hermes-serve.service"],
+ ["systemctl", "--user", "restart", "nginx.service"],
+ ["systemctl", "--user", "restart", "myhermes-dashboard.service"],
+ ],
+)
+def test_subprocess_run_systemctl_read_only_or_foreign_unit_passes_guard(cmd):
+ """Read-only verbs on Hermes units and mutating verbs on other units reach the real
+ ``subprocess.run``; an empty PATH turns that into FileNotFoundError, never a real systemctl."""
+ with pytest.raises(FileNotFoundError):
+ subprocess.run(cmd, env={"PATH": "/nonexistent"}, check=False)
+
+
def test_subprocess_run_setsid_systemctl_blocked():
with pytest.raises(RuntimeError, match="live-system guard"):
subprocess.run(["setsid", "systemctl", "kill", "hermes-gateway"], check=False)