Skip to content

The agent that grows with you

fix(dashboard): --stop and the update sweep resolve backend ownership tri-state, never guess

teknium146500f9c7985
diff --git a/hermes_cli/dashboard_procs.py b/hermes_cli/dashboard_procs.py
index 22be3642276..987699b483b 100644
--- a/hermes_cli/dashboard_procs.py
+++ b/hermes_cli/dashboard_procs.py
@@ -106,20 +106,48 @@ def _scan_dashboard_processes(*, exclude_pids: set[int] | None = None) -> list[t
return found
-def _hermes_home_for_pid(pid: int) -> str | None:
- """Best-effort ``HERMES_HOME`` from *pid*'s environment (psutil, then /proc)."""
+def _pid_environ(pid: int) -> dict[str, str] | None:
+ """Exec-time environment of *pid* (psutil, then /proc); ``None`` when unreadable."""
with contextlib.suppress(Exception):
import psutil
- if home := psutil.Process(pid).environ().get("HERMES_HOME"):
- return home
+ return dict(psutil.Process(pid).environ())
try:
raw = Path(f"/proc/{pid}/environ").read_bytes()
except OSError:
return None
+ env: dict[str, str] = {}
for part in raw.split(b"\x00"):
- if part.startswith(b"HERMES_HOME="):
- return part.split(b"=", 1)[1].decode("utf-8", errors="replace") or None
- return None
+ key, sep, value = part.partition(b"=")
+ if sep:
+ env[key.decode("utf-8", errors="replace")] = value.decode("utf-8", errors="replace")
+ return env
+
+
+def _hermes_home_for_pid(pid: int) -> str | None:
+ """The Hermes home *pid* runs on, tri-state: ``None`` ONLY when its environment is unreadable
+ (another user, hardened ``/proc``) — callers spare those, never guess.
+
+ A readable environment always resolves: ``HERMES_HOME`` when exported at exec time, else the
+ platform default home of the process's own ``HOME`` / ``LOCALAPPDATA`` (the common install shape
+ exports nothing). ``hermes --profile X serve`` sets ``HERMES_HOME`` in ``os.environ`` AFTER
+ startup, which ``/proc/<pid>/environ`` never reflects, so a ``--profile``/``-p`` flag in the
+ argv selects ``<default root>/profiles/X`` — the home ``_apply_profile_override`` resolves.
+ """
+ env = _pid_environ(pid)
+ if env is None:
+ return None
+ if home := env.get("HERMES_HOME", "").strip():
+ return home
+ if sys.platform == "win32":
+ local_appdata = env.get("LOCALAPPDATA", "").strip()
+ base = Path(local_appdata) if local_appdata else Path(env.get("USERPROFILE") or Path.home()) / "AppData" / "Local"
+ default_home = base / "hermes"
+ else:
+ default_home = Path(env.get("HOME") or Path.home()) / ".hermes"
+ from hermes_cli.main_dashboard import _dashboard_cmdline_for_pid
+ if profile := _profile_flag_value(_dashboard_cmdline_for_pid(pid) or []):
+ return str(default_home / "profiles" / profile)
+ return str(default_home)
def _dashboard_subcommand_index(argv: list[str]) -> int | None:
@@ -184,13 +212,13 @@ def _normalized_home_for_compare(home: str) -> str:
def _pids_owned_by_hermes_home(pids: list[int], home: str) -> list[int]:
- """Return only *pids* whose live environment names ``home`` exactly.
+ """Return only *pids* whose resolved Hermes home (``_hermes_home_for_pid``) is ``home``.
Dashboard argv is discovery-only: it is not an ownership proof because
several Hermes installs and profiles can run the same command on one
- machine. An unreadable or missing process environment is deliberately
- not treated as a match, so a stop request fails closed rather than taking
- down an unrelated backend.
+ machine. An unreadable process environment is deliberately not treated
+ as a match, so a stop request fails closed rather than taking down an
+ unrelated backend.
"""
target = _normalized_home_for_compare(home)
return [
@@ -541,9 +569,7 @@ def _kill_stale_dashboard_processes(
# An SSH-owned backend belongs to an attached Desktop client; killing it strands that
# client's fixed SSH port-forward. Same ownership records as the reaper.
exclude |= _lock_owned_serve_pids()
- pids = _dash._find_stale_dashboard_pids(exclude_pids=exclude or None)
- if scope_home:
- pids = _pids_owned_by_hermes_home(pids, scope_home)
+ pids = _dash._find_stale_dashboard_pids(exclude_pids=exclude or None, scope_home=scope_home)
if not pids:
return _empty_result()
# Snapshot systemd unit/cgroup and argv BEFORE killing (the cgroup dies with the process).
diff --git a/hermes_cli/main.py b/hermes_cli/main.py
index 39957c9ef20..bb14dd90e8b 100644
--- a/hermes_cli/main.py
+++ b/hermes_cli/main.py
@@ -2470,19 +2470,21 @@ def _dashboard_lifecycle_flags(args, token_file) -> None:
_report_dashboard_status()
sys.exit(0) # status is informational, always 0
if getattr(args, "stop", False):
- if not _find_stale_dashboard_pids():
- print("No hermes dashboard processes running.")
+ # Scoped to the invoking home (`-p` applied by _apply_profile_override): another
+ # install's or profile's backend on this machine is never a target (#113978).
+ from hermes_constants import get_hermes_home
+
+ own_home = str(get_hermes_home())
+ if not _find_stale_dashboard_pids(scope_home=own_home):
+ print("No hermes dashboard processes running for this profile.")
sys.exit(0)
# Reuse the same SIGTERM-grace-SIGKILL path used after `hermes update`;
# it prints outcomes itself. Exit 1 only if a pid was unkillable — judged
# from the kill result, not a re-scan: a launchd KeepAlive job respawns
# its backend on a fresh PID, which is not a failed stop.
from hermes_cli.dashboard_procs import _kill_stale_dashboard_processes
- from hermes_constants import get_hermes_home
- result = _kill_stale_dashboard_processes(
- reason="requested via --stop", scope_home=str(get_hermes_home())
- )
+ result = _kill_stale_dashboard_processes(reason="requested via --stop", scope_home=own_home)
sys.exit(1 if result["failed"] else 0)
diff --git a/hermes_cli/main_dashboard.py b/hermes_cli/main_dashboard.py
index 8a74aea53b4..917df062acd 100644
--- a/hermes_cli/main_dashboard.py
+++ b/hermes_cli/main_dashboard.py
@@ -18,18 +18,27 @@ from hermes_cli.cli_output import line_input
_PRE_BUILD_HINT = " Pre-build first: npm install --workspace web && npm run build -w web"
-def _find_stale_dashboard_pids(*, exclude_pids: set[int] | None = None) -> list[int]:
- """Return PIDs of stale ``dashboard``/``serve`` processes for update cleanup."""
+def _find_stale_dashboard_pids(*, exclude_pids: set[int] | None = None,
+ scope_home: str | None = None) -> list[int]:
+ """PIDs of running ``dashboard``/``serve`` backends the caller may stop.
+
+ *scope_home*: keep only backends whose resolved Hermes home (see
+ ``_hermes_home_for_pid``) is this home; unreadable ownership is spared, never guessed.
+ ``--stop`` and the post-update cleanup pass their own home so another install's or
+ profile's backend on the same machine is never a target (#113978).
+ """
from hermes_cli.dashboard_procs import (
_caller_ancestor_pids,
_is_caller_wrapper_shell,
+ _pids_owned_by_hermes_home,
_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.
ancestors = _caller_ancestor_pids()
- return [pid for pid in pids if not _is_caller_wrapper_shell(pid, ancestors)]
+ 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:
diff --git a/tests/hermes_cli/test_dashboard_lifecycle_flags.py b/tests/hermes_cli/test_dashboard_lifecycle_flags.py
index 1d78547242d..1e70187aff6 100644
--- a/tests/hermes_cli/test_dashboard_lifecycle_flags.py
+++ b/tests/hermes_cli/test_dashboard_lifecycle_flags.py
@@ -85,7 +85,7 @@ class TestDashboardStop:
respawn is not a failed stop (the kill path already warns about it)."""
scans = iter([[12345, 12346], [12347]])
with patch("hermes_cli.main._find_stale_dashboard_pids",
- side_effect=lambda: next(scans)), \
+ side_effect=lambda **_: next(scans)), \
patch("hermes_cli.dashboard_procs._kill_stale_dashboard_processes",
return_value={"matched": [12345, 12346], "killed": [12345, 12346],
"failed": [], "unrecovered": [12345, 12346]}) as mock_kill, \
diff --git a/tests/hermes_cli/test_stale_pid_guard.py b/tests/hermes_cli/test_stale_pid_guard.py
index 7d1990af6e1..dbfcb5fa45f 100644
--- a/tests/hermes_cli/test_stale_pid_guard.py
+++ b/tests/hermes_cli/test_stale_pid_guard.py
@@ -220,7 +220,10 @@ class TestKillStaleDashboardProcesses:
foreign_home = "/tmp/hermes-foreign"
monkeypatch.setenv("HERMES_HOME", own_home)
- with self._patch_find((12345, 12346, 12347)), mock.patch.object(
+ with mock.patch.object(
+ dashboard_procs, "_scan_dashboard_processes",
+ return_value=[(12345, "hermes serve"), (12346, "hermes serve"), (12347, "hermes serve")],
+ ), mock.patch.object(dashboard_procs, "_caller_ancestor_pids", return_value=set()), mock.patch.object(
dashboard_procs, "_hermes_home_for_pid",
side_effect=lambda pid: {
12345: own_home,
@@ -235,3 +238,26 @@ class TestKillStaleDashboardProcesses:
kill.assert_called_once()
assert kill.call_args.args[0] == [12345]
assert result["matched"] == [12345]
+
+
+class TestHermesHomeForPid:
+ """Tri-state owner resolution: a readable environment always names a home."""
+
+ def test_readable_env_without_var_resolves_to_that_process_default_home(self, monkeypatch):
+ """The common install shape exports no HERMES_HOME: the backend lives in its user's
+ platform default home, and a default-home ``--stop`` must still find it (#113978)."""
+ monkeypatch.setattr(sys, "platform", "linux")
+ monkeypatch.setattr(dashboard_procs, "_pid_environ", lambda pid: {"HOME": "/home/alice"})
+ from hermes_cli import main_dashboard
+ monkeypatch.setattr(main_dashboard, "_dashboard_cmdline_for_pid",
+ lambda pid: ["hermes", "--profile", "work", "serve"] if pid == 2 else ["hermes", "serve"])
+
+ assert dashboard_procs._hermes_home_for_pid(1) == "/home/alice/.hermes"
+ # ``-p``/``--profile`` is applied to os.environ after exec, invisible in /proc environ.
+ assert dashboard_procs._hermes_home_for_pid(2) == "/home/alice/.hermes/profiles/work"
+ assert dashboard_procs._pids_owned_by_hermes_home([1, 2], "/home/alice/.hermes") == [1]
+
+ def test_unreadable_env_is_none_and_spared(self, monkeypatch):
+ monkeypatch.setattr(dashboard_procs, "_pid_environ", lambda pid: None)
+ assert dashboard_procs._hermes_home_for_pid(7) is None
+ assert dashboard_procs._pids_owned_by_hermes_home([7], "/home/alice/.hermes") == []
diff --git a/tests/hermes_cli/test_update_stale_dashboard.py b/tests/hermes_cli/test_update_stale_dashboard.py
index 2e756346963..17988a35cc3 100644
--- a/tests/hermes_cli/test_update_stale_dashboard.py
+++ b/tests/hermes_cli/test_update_stale_dashboard.py
@@ -115,7 +115,7 @@ def _write_valid_ssh_backend_lock(tmp_path, monkeypatch) -> int:
def test_update_cleanup_spares_backend_owned_by_valid_ssh_lock(tmp_path, monkeypatch):
pid = _write_valid_ssh_backend_lock(tmp_path, monkeypatch)
- def assert_owned_pid_is_excluded(*, exclude_pids=None):
+ def assert_owned_pid_is_excluded(*, exclude_pids=None, **_):
assert exclude_pids is not None
assert pid in exclude_pids
return []
@@ -135,7 +135,7 @@ def test_explicit_stop_does_not_spare_backend_owned_by_valid_ssh_lock(
):
pid = _write_valid_ssh_backend_lock(tmp_path, monkeypatch)
- def assert_owned_pid_is_not_excluded(*, exclude_pids=None):
+ def assert_owned_pid_is_not_excluded(*, exclude_pids=None, **_):
assert exclude_pids is None or pid not in exclude_pids
return []
diff --git a/website/docs/reference/cli-commands.md b/website/docs/reference/cli-commands.md
index ef7b28eb21c..c29395e60a6 100644
--- a/website/docs/reference/cli-commands.md
+++ b/website/docs/reference/cli-commands.md
@@ -1778,7 +1778,7 @@ Launch the web dashboard — a browser-based UI for managing configuration, API
| `--insecure` | off | **Deprecated / no-op.** Formerly bypassed auth on a non-loopback bind. Since the June 2026 hardening a public bind *always* requires an auth provider (password or OAuth). Bind `127.0.0.1` and tunnel to keep it local. |
| `--skip-build` | off | Skip the web UI build step and serve the existing `dist` directly. Useful for non-interactive contexts (Windows Scheduled Tasks, CI) where npm isn't available. Pre-build with `cd web && npm run build`. |
| `--isolated` | off | When launched from a named profile (`worker dashboard`), run a dedicated per-profile server instead of routing to the machine dashboard. |
-| `--stop` | — | Stop running `hermes dashboard` processes and exit. SIGTERM, a 10s grace, then SIGKILL; a hosted Chat TUI that outlives its backend is stopped too (it would otherwise keep the deleted `state.db-wal` open and block the next start). Messaging-gateway bots started from the dashboard are not touched. |
+| `--stop` | — | Stop the running `hermes dashboard` / `hermes serve` backend **of this Hermes home** and exit (`-p <profile>` / `HERMES_HOME` select which; backends of other profiles, other installs on the machine, and the shell you typed the command into are never touched — a backend whose owner cannot be read is left alone). SIGTERM, a 10s grace, then SIGKILL; a hosted Chat TUI that outlives its backend is stopped too (it would otherwise keep the deleted `state.db-wal` open and block the next start). Messaging-gateway bots started from the dashboard are not touched. |
| `--status` | — | List running `hermes dashboard` processes and exit. |
### `hermes dashboard register`