Skip to content

The agent that grows with you

fix(cli): select dashboard/serve backends by entrypoint + subcommand tokens, not argv substrings (#121156, salvage #121243)

teknium17bf1373cb84f
diff --git a/hermes_cli/dashboard_procs.py b/hermes_cli/dashboard_procs.py
index 72344603b78..baff8e4ef40 100644
--- a/hermes_cli/dashboard_procs.py
+++ b/hermes_cli/dashboard_procs.py
@@ -12,12 +12,6 @@ from pathlib import Path
from hermes_cli._startup_fast import is_desktop_ssh_backend_argv
-# Cmdline substrings identifying the long-lived server (``serve`` = the headless name Desktop
-# spawns; reaped on update for the same reason).
-_DASHBOARD_PATTERNS = tuple(
- f"{launcher} {cmd}"
- for cmd in ("dashboard", "serve")
- for launcher in ("hermes", "hermes_cli.main", "hermes_cli/main.py"))
_PS_RUN_KWARGS = dict(capture_output=True, text=True, encoding="utf-8", errors="replace")
@@ -86,13 +80,17 @@ def _scan_dashboard_processes(*, exclude_pids: set[int] | None = None) -> list[t
process; ``_kill_stale_dashboard_processes`` reads it and passes it here. (#37532)
"""
skip = {os.getpid(), *(exclude_pids or ())}
+ # Canonical token matcher, never argv substrings: ``hermes serve`` is a prefix of ``hermes
+ # server`` and this list decides a SIGTERM — ``herdr --session hermes server`` (a terminal
+ # multiplexer) was killed and its unit restarted by ``hermes update`` (#121156).
+ from hermes_cli.update_cmd_windows import _hermes_holder_subcommand
try:
found = [(pid, cmd) for pid, cmd in _iter_process_table()
- if pid not in skip and any(p in cmd for p in _DASHBOARD_PATTERNS)]
+ if pid not in skip and _hermes_holder_subcommand(cmd) in ("dashboard", "serve")]
except (FileNotFoundError, subprocess.TimeoutExpired, OSError):
return []
- # Spawn-ledger augmentation: substring patterns miss profiled launches (`hermes --profile p
- # serve`); the ledger holds live-verified pids. Unavailable ledger → scan-only.
+ # Spawn-ledger augmentation: an argv scan misses a truncated or unreadable cmdline; the ledger
+ # holds live-verified pids. Unavailable ledger → scan-only.
with contextlib.suppress(Exception):
# Every serve/ dashboard registers itself in the machine spawn ledger at startup with live-verified
# (pid, create_time), so ledger rows are positive identity, not argv guessing. Add any live ledger
diff --git a/hermes_cli/main_dashboard.py b/hermes_cli/main_dashboard.py
index 3d42936fcac..5a5ca614f41 100644
--- a/hermes_cli/main_dashboard.py
+++ b/hermes_cli/main_dashboard.py
@@ -36,22 +36,22 @@ def _find_stale_dashboard_pids(*, exclude_pids: set[int] | None = None,
_scan_dashboard_processes,
)
pids = [pid for pid, _cmd in _scan_dashboard_processes(exclude_pids=exclude_pids)]
- # The argv substring scan also selects the caller's own wrapper shell (``bash -c
- # 'hermes dashboard --stop'``); killing it takes down the invoking terminal.
+ # The scan also selects the caller's own wrapper shell (``bash -c 'hermes dashboard --stop'``);
+ # killing it takes down the invoking terminal.
ancestors = _caller_ancestor_pids()
pids = [pid for pid in pids if not _is_caller_wrapper_shell(pid, ancestors)]
return _pids_owned_by_hermes_home(pids, scope_home) if scope_home else pids
def _parse_dashboard_runtime(command: str) -> tuple[str, str, int] | None:
- """Best-effort parse of a dashboard/server cmdline into mode, host, and port."""
- mode = None
- for candidate in ("dashboard", "serve"):
- patterns = (f"hermes {candidate}", f"hermes_cli.main {candidate}", f"hermes_cli/main.py {candidate}")
- if any(pattern in command for pattern in patterns):
- mode = candidate
- break
- if mode is None:
+ """Best-effort parse of a dashboard/server cmdline into mode, host, and port.
+
+ The mode is the canonical holder subcommand, never an argv substring: this gates the launchd
+ backend inventory (a kill + kickstart path) and ``--status`` (#121156).
+ """
+ from hermes_cli.update_cmd_windows import _hermes_holder_subcommand
+ mode = _hermes_holder_subcommand(command)
+ if mode not in ("dashboard", "serve"):
return None
port = 9119
diff --git a/hermes_cli/update_cmd_windows.py b/hermes_cli/update_cmd_windows.py
index d1f602f41c4..d0d019d89b2 100644
--- a/hermes_cli/update_cmd_windows.py
+++ b/hermes_cli/update_cmd_windows.py
@@ -251,9 +251,9 @@ def _hermes_holder_subcommand(cmdline: str) -> str | None:
return None
def _is_entry(i: int, token: str) -> bool:
- low = token.lower().strip('"')
+ low = token.lower().strip("\"'").replace("\\", "/")
return (low.endswith("hermes_cli.main") and i > 0 and tokens[i - 1] == "-m") or (
- low.rsplit("\\", 1)[-1].rsplit("/", 1)[-1] in ("hermes", "hermes.exe"))
+ low.rsplit("/", 1)[-1] in ("hermes", "hermes.exe")) or low.endswith("hermes_cli/main.py")
entry_idx = next((i for i, token in enumerate(tokens) if _is_entry(i, token)), None)
if entry_idx is None:
diff --git a/tests/hermes_cli/test_dashboard_stop_spare_caller.py b/tests/hermes_cli/test_dashboard_stop_spare_caller.py
index 73ebfd9b2a0..759d087c0b9 100644
--- a/tests/hermes_cli/test_dashboard_stop_spare_caller.py
+++ b/tests/hermes_cli/test_dashboard_stop_spare_caller.py
@@ -1,8 +1,7 @@
"""Root selection for ``dashboard --stop`` / update cleanup must spare the caller.
-The argv substring scan (``_DASHBOARD_PATTERNS``) matches any process whose command
-line merely mentions ``hermes dashboard`` / ``hermes serve`` — including the shell the
-``--stop`` was typed into (``bash -c 'hermes dashboard --stop'``). Killing it takes down
+The dashboard scan also selects the shell the ``--stop`` was typed into (``bash -c 'hermes
+dashboard --stop'``: same entry token, same subcommand). Killing it takes down
the invoking terminal; the historical fix for the hosted-TUI case is descendant hygiene
(#113819), which is orthogonal to root selection.
"""
diff --git a/tests/hermes_cli/test_process_identity_canonical_matchers.py b/tests/hermes_cli/test_process_identity_canonical_matchers.py
index 28037f97e96..d9ccd9fa822 100644
--- a/tests/hermes_cli/test_process_identity_canonical_matchers.py
+++ b/tests/hermes_cli/test_process_identity_canonical_matchers.py
@@ -67,3 +67,31 @@ def test_profile_liveness_is_the_shared_ladder(tmp_path, monkeypatch):
assert seen["profile_dir"] == tmp_path
seen["pid_probe"](tmp_path / "gateway.pid")
assert calls == [(tmp_path / "gateway.pid", False)]
+
+
+# ``hermes serve`` is a substring of ``hermes server``: a terminal multiplexer started as
+# ``herdr --session hermes server`` was SIGTERMed by ``hermes update`` and its unit restarted (#121156).
+DECOY = "tool --name hermes server 30"
+BACKENDS = [
+ "/opt/hermes/venv/bin/python -m hermes_cli.main serve --port 0",
+ "/usr/bin/python3 /opt/hermes/hermes_cli/main.py dashboard --no-open",
+]
+
+
+def test_dashboard_scan_selects_entrypoint_plus_subcommand_tokens_never_substrings(monkeypatch):
+ import hermes_cli.dashboard_procs as dashboard_procs
+ import hermes_cli.process_identity as process_identity
+
+ monkeypatch.setattr(dashboard_procs, "_iter_process_table",
+ lambda: [(4242, DECOY), *((5000 + i, cmd) for i, cmd in enumerate(BACKENDS))])
+ monkeypatch.setattr(process_identity, "ledger_entries", lambda: [])
+ assert dashboard_procs._scan_dashboard_processes() == [(5000, BACKENDS[0]), (5001, BACKENDS[1])]
+
+
+def test_dashboard_runtime_parse_refuses_the_decoy_and_reads_a_real_backend():
+ from hermes_cli.main_dashboard import _parse_dashboard_runtime
+
+ assert _parse_dashboard_runtime(DECOY) is None
+ assert _parse_dashboard_runtime(BACKENDS[0]) == ("serve", "127.0.0.1", 0)
+ # launchd ProgramArguments arrive ``shlex.join``ed: a quoted path with spaces is still the entry.
+ assert _parse_dashboard_runtime("'/Users/a b/venv/bin/hermes' dashboard --port 9200") == ("dashboard", "127.0.0.1", 9200)